Encrypt and Decrypt

My programs encrypts 4digits and they are replaced with the result of adding 7 to the digit and getting the remainder after dividing the new value with 0. the 1st digit is then swap with the third and the second with the forth digit.

i succeeded in compiling this task:

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;


int main()
{
const int arraySize = 4;
int a[ arraySize ];
int n[ arraySize ];



cout << "Enter a four-digit number: ";
cin >> n[0] >> n[1] >> n[2] >> n[3];

a[0] = ( n[0] + 7 ) % 10;
a[1] = ( n[1] + 7 ) % 10;
a[2] = ( n[2] + 7 ) % 10;
a[3] = ( n[3] + 7 ) % 10;

if ( a[2] == 0 )
cout << "Encrypted number is "<< setw( 3 )<<a[3]<<a[0]<<a[1]<< endl;

else
cout << "Encrypted number is "<< setw( 3 )<<a[2]<<a[3]<<a[0]<<a[1]<< endl;


return 0;
}

so my result will produce
(1) 1 2 3 4
(2) 891011 after adding 7
(3) 8901 as the remainder of % 10
(4) 0189 after switching (encrypted integers)

however, i cant seem to think a way to reverse my program (decrypt) to input the encrypted integers(0189) to form the original number (1234)

i figured the formula though but it still didnt work out the way its supposed to

if ( a[ arraySize ] < 17 )

a[0] = n[0] + 10
and so on..
You cant reverse it ,because you use modulo operator (%) . You cant be sure that , number was bigger than 10 or not.
So, you better change your encryption algorithm.(or formula)
Last edited on
if you add 7 to a digit, the reverse would be to subtract 7. But since negative numbers don't play well with the modulo operator, I would add 10-7:

original number: 2

(2 + 7) % 10 = 9

to reverse:

(9 + 10-7) % 10 = 2


However as Dufresne suggested, this doesn't work with multi digit integers. Therefore I wouldn't read the digits in as ints. For example if the user inputs the following 12 11 10 9, your program will give very strange results.

I would read the data in as chars. But that might be beyond the scope of this assignment, so whatever.
Topic archived. No new replies allowed.