Thread: Explination?

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    51

    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. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    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.
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    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
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I need a decent explination.....
    By tetraflare in forum C++ Programming
    Replies: 2
    Last Post: 11-20-2002, 10:06 AM
  2. Need example and explination...
    By Gamma in forum C++ Programming
    Replies: 1
    Last Post: 04-15-2002, 09:38 PM