c++ program to reverse a number using while loop

Program code to find Reverse of a Number:

#include<iostream.h>
#include<conio.h> void main()
{ int n,a,r,s=0; clrscr(); cout<<"n Enter The Number:"; cin>>n; a=n; //LOOP FOR FINDING THE REVERSE OF A NUMBER while(n>0) { r=n%10; s=s*10+r; n=n/10; } cout<<"n The Reverse Number of "<<a<<" is "<<s; getch();
}

Related: Reverse of a Number using while loop in C

Working:

  • First the computer reads a number from the user.
  • Then using while loop the reverse number is calculated and stored in the variable ā€˜sā€™.
  • Finally the reverse of a given number is printed.

Step by step working of the above C++ program:

Let us assume a number entered is 123.

So n=123 , s=0

  1.   n>0  (123>0)  while loop condition is true

r=n%10       (r=123%10)      So  r=3

s=s*10+r    (s=0*10+3)       So  s=3

n=n/10       (n=123/10)       So  n=12

  1.  n>0  (12>0)  while loop condition is true

r=n%10       (r=12%10)         So  r=2

s=s*10+r    (s=3*10+2)     So  s=32

n=n/10       (n=12/10)          So  n=1

  1.  n>0  (1>0)  while loop condition is true

r=n%10       (r=1%10)             So  r=1

s=s*10+r    (s=32*10+1)     So  s=321

n=n/10       (n=1/10)              So  n=0

  1.  n>0  (0>0)  while loop condition is false

It comes out of the while loop and prints the reverse number which is stored in variable ā€œsā€.

  1. Thus the program execution is completed.

Output:

reverse of a number

reverse of a number

TO DOWNLOAD THE PROGRAM CODE : CLICK HERE