Reverse of a Number using do-while loop in C++

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
    do
    {
        r=n%10;
        s=s*10+r;
        n=n/10;
    }while(n>0);
    
    cout<<"\n  The Reverse Number of "<<a<<" is "<<s;
    getch();
}

Related: Reverse of a Number using do-while loop in C

Working:

  • First the computer reads a number from the user.
  • Then using do-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 4321.

So n=4321 , s=0

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

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

   n=n/10        (n=4321/10)       So  n=432

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

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

s=s*10+r    (s=1*10+2)        So  s=12

n=n/10       (n=432/10)       So  n=43

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

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

s=s*10+r    (s=12*10+3)      So  s=123

n=n/10       (n=43/10)          So  n=4

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

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

s=s*10+r    (s=123*10+4)      So  s=1234

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

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

It comes out of the do-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

 

1 Response

  1. sohail Ahmad says:

    out class wonder full

Leave a Reply

Your email address will not be published. Required fields are marked *