by
ThePhantom on March 22, 2011 @ 05:36 AM
Hi. Thanks for being a member of Digital Phantom
Here is the code for reversing the number. With the comments, it's self explanatory but I'm going to explain you the logic anyways.
#include <iostream>
using namespace std;
//function prototype
int reverse(int);
int main(){
// keep program running for multiple executions
while(cin){
int number;
cout << "Please enter a number to reverse: " << endl;
cin >> number;
cout << "\nReverse:\t" << reverse(number) << "\n" << endl;
}
return 0;
}
//function declaration
int reverse(int number){
//declare the digit variable and the reverse number variable.
//initialize reverse number to 0
int digit, reverseNumber = 0;
//get the absolute value of the number
number = abs(number);
//if number is 0 then just output 0
if(number == 0){
return 0;
}
else {
//while the number is greater than 0 then keep looping
while(number > 0){
//get the last digit from right to left
digit = number % 10;
//trim the last digit
number /= 10;
//create the rever number with each digit
reverseNumber = reverseNumber * 10 + digit;
}
// return the number
return reverseNumber;
}
}
If you were going to do this by hand you will start writing the digits from right to left; so in programming with do this by taking the remainder of the number when we divide it by
10. For example:
10 % 10 = 0 so that will be the last digit. Now we divide that by ten and the result is
1. Once again we get the remainder
1 % 10 = 1, and thats the other digit. Now we put the the digits together to form the reverse number.
Last Updated by:
ThePhantom @ Mar 22, 2011 @ 03:45 PM