Sunday, 23 September 2018

Printing reverse of a number in C++

The reverse of a number


A reverse of a number is simply obtained by writing the number in reverse order. The reverse of 95405 is 50459.
This program uses the idea of the sum of digits of a multi-digit number.

The plus(+) operator is used to perform arithmetic addition. E.g. 5+3=8.
The minus(-) operator is used to perform arithmetic subtraction. E.g. 5-3=5.


Write a program in C++ to input a multi-digit number and print its reverse.


We need to input a multi-digit number. Then we extract the last digit of the multi-digit number by performing the mod operation with 10. The extracted value is added to a new variable which is multiplied by 10 every time. This increases one decimal place of each digit of the number in a new variable before adding the last digit to it. The last digit is then removed by using slash(/) operator and storing it in int data type. This process is continued until the multi-digit number is reduced to zero(0).
   

Program


#include<iostream.h>
#include<conio.h>
void main()
{
int a,b=0,rev=0;
clrscr();
cout<<"Enter a multidigit number=";
cin>>a;
while(a!=0)
{
b=a%10;
rev=(rev*10)+b;
a=a/10;
}
cout<<"\nThe reverse of the entered number is="<<rev;
getch();
}


Output


Producing a reverse of a number
PRINTING THE REVERSE OF ENTERED NUMBER








Explanation

Now we entered a=3682 which is not equal to zero. The while loop will be executed as follows:

a                 b=a%10                  rev=(rev*10)+b                     a=a/10           
3682           3682%10=2            (0*10)+2=2                          3682/10=368
368             368%10=8              (2*10)+8=28                        368/10=36
36               36%10=6                (28*10)+6=286                    36/10=3
3                 3%10=3                  (286*10)+3=2863                3/10=0
0

The while loop will terminate since a=0 and our final answer will be stored in rev.



No comments:

Post a Comment