Ads 468x60px

Saturday 19 January 2013

C++ Program to Reverse an Integer

This program will ask user to input a number and then it will calculate the reverse of the number and print that as the output. Data type long int is used in this program. 
#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();
 long int num,r=0;
 cout<<"Enter an integer:\t";
 cin>>num;
 while(num>0)
 {
  r=r*10;
  r=r+num%10;
  num=num/10;
 }
 cout<<"\nThe Revers of the number is "<<r<<endl;
 getch();
}
Explanation of the program
Two variables are declared one is for the number which is to be reversed and that will be defined by the user as an input and the other is r in which we will store the reverse of the number. 
Now the main task is happening in the loop, while loop is used in this program. 
Suppose we entered 123 
Now num = 123
The expression of while loop is true (123 is greater than 0); the control will come inside the loop and will execute the following statement
{
 r=r*10;
 r=r+num%10;
 num=num/10;
}
Now dry run it in your mind. 
r is initialized by 0 at the starting of the program, so we have the values 
r = 0;
num = 123;
Now calculate what will happen 
the value of r become 0 in first line. 
Then it will become 3
r = 0 + 123 % 10; 
r = 0 + 3;
r = 3
Now in the last statement num will become 12
num = 123 / 10;
num = 12
Because we have taken the data type as int so it will not take the decimal value. 
Now all the statements has executed so the loop will again check its expression which is again true (12 is greater than 0), so the control will again come inside the loop and will execute the statements with updated values, this process will continue until the expression in while don't become false and at last it will print the reversed value as the output. 
Share if you liked this Post using your favorite sharing service:

Subscribe Updates, Its FREE!

 
Related Posts Plugin for WordPress, Blogger...