Original Post
Just looking for feedback on how I solved this. This is from Exercise 2.37 of the book "C++ How to Program 4e". Functions and Arrays have not yet been covered so I don't use those here. :) The exercise reads as follows: "A company wants to transmit data over a telephone, but is concerned that its phones could be tapped. All of the data are transmitted as four-digit integers. The company has asked you to write a program that encrypts the data so that it can be transmitted more securely. Your program should read a four-digit integer and ecrypt it as follows: Replace each digit by (the sum of that digit plus 7) modulus 10. Then, swap the first digit with the third, swap the second digit with the fourth and print the ecrypted integer. Write a separate program that inputs an encrypted four digit integer and decrypts it to form the original number." I've combined the exercise into one program for simplicity. It seems to work fine but I would like to know if anyone has any tips on making it better without using any advanced functionality not yet covered. :) my code:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int input;
int n1, n2, n3, n4;
int copy;
cout << "Enter a 4 digit number: " << endl;
cin >> input;
// break number down
copy = input;
n4 = copy % 10;
copy /= 10;
n3 = copy % 10;
copy /= 10;
n2 = copy % 10;
copy /= 10;
n1 = copy;
// encrypt number
n1 = (n1 + 7) % 10;
n2 = (n2 + 7) % 10;
n3 = (n3 + 7) % 10;
n4 = (n4 + 7) % 10;
// move numbers around
int temp;
temp = n1;
n1 = n3;
n3 = temp;
temp = n2;
n2 = n4;
n4 = temp;
cout << "Encrypted number: ";
cout << n1 << n2 << n3 << n4 << endl << endl; // display encrypted number
// decrypt to original
n1 = n1 - 7;
if ( n1 < 0 )
n1 += 10;
n2 = n2 - 7;
if ( n2 < 0 )
n2 += 10;
n3 = n3 - 7;
if ( n3 < 0 )
n3 += 10;
n4 = n4 - 7;
if ( n4 < 0 )
n4 += 10;
// move numbers back to original location
temp = n1;
n1 = n3;
n3 = temp;
temp = n2;
n2 = n4;
n4 = temp;
cout << "Decrypted number: ";
cout << n1 << n2 << n3 << n4 << endl << endl; // display decrypted number
return 0;
}