Wednesday 6 November 2013

C++ Program to reverse a number!

In this post, I'm gonna share you the program, to reverse an input number. i.e., if the input is 1234, the output should be 4321.

Here is the code:
#include<iostream.h>
#include<conio.h>

void Reverse(int num)
{
   int temp, rev_num=0;
   while(num!=0)
   {
      temp = num%10;
      rev_num = (rev_num*10) + temp;
      num = num/10;
   }
   cout<<"Reversed number is "<<rev_num;
}

void main()
{
    int number;
    cout<<"Enter the number to be reversed : ";
    cin>>number;
    Reverse(number);
    getch();
}

For newer IDEs, visit this page.
Working

In this program, I have used a function just to reverse the number, with the number num to be reversed as the parameter. I have also initialized two variables, temp, a temporary variable, and rev_num, the reversed number. As you can see, reversed number is initially set to 0. Suppose the number input (from the main) is 321. 
  1. temporary variable is changed to num%10. So, temp = 321%10 = 1.
  2. Then reversed number is changed to rev_num = (rev_num*10) + temp. As we have set, rev_num is 0 at first. So, rev_num now becomes, (0*10) + 1 = 1. Now the program has found out the resultant first term i.e., 1.
  3. Now num is changed to num/10 = 321/10 = 32.1 . But num is an integer and cannot have a decimal value. So num is automatically converted by the compiler to an integer, i.e., 32 (it just removes the decimal number). 
  4. Since num != 0, the loop is again processed. On this iteration, temp becomes 2. rev_num becomes (rev_num*10) + temp = (1*10) + 2  = 12. So the second digit is 2. num has now become 3.
  5. Since num != 0, the loop is again processed. On this iteration, temp becomes 3. rev_num becomes (rev_num*10) + temp = (12*10) + 3  = 123. So the third digit is 2. 
  6. Now, num = num/10 = 3/10 = .3 . .3 is not an integer and hence it is converted to 0. Now that num has become 0, the loop is terminated. 
  7. Final result turns out to be 123, and the function outputs it.
This program has significance in many other programs. For example, it can be used in the program to check if an input number is palindrome or not (which I will be posting soon). 

That's all for now, folks.

No comments:

Post a Comment

You might also like