1. ## Explination?

hi i had a question how to reverse numbers, and someone graciously furnished me a script after alot of explination, but one thng i dont get is how this little snippit of cod can evaluate ALL integers with one loop! look.

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int reverse ( int val )
{
int ret = 0;

while ( val != 0 ) {
ret = ( val % 10 ) + ret * 10;
val /= 10;
}

return ret;
}

int main()
{
int num = 0;

cout<<"Enter a number (CTRL+Z to quit): ";
while (cin>>num ) {
cout<<"Your number reversed was: "<<reverse ( num ) <<endl;
cout<<"Enter a number (CTRL+Z to quit): ";
}

return 0;
}

thanks

2. Mathematics is a wonderful thing, isn't it...?

Basically, what that code does, is take the last digit of Val and add it first to Ret (until there are no more digits in Val), thus reversing the digits of the number.

3. Here's how the code works (it looks like mine ).

As long as the number is not zero, take the lowest order digit and add it to the return value, then remove it. These two operations are performed with the modulus operator and a division, both by the base of the number:

If the number is 12345 in decimal, then 12345 % 10 == 5, which is the lowest order digit. Add that to the return value and then 12345 / 10 == 1234. Do the same thing with each digit, when the value is 1 and you do 1 / 10, the result is 0 and the loop exits. So the function uses remainders and division to reverse a value with any number of digits representable by an int.

-Prelude