C++ Program to Reverse a Number

Reverse of number means reverse the position of all digits of any number. For example reverse of 839 is 938

Example

#include<iostream.h>
#include<conio.h>

void main()
{
int no,rev=0,r,a;
clrscr();
cout<<"Enter the num: ";
cin>>no;
a=no;
while(no>0)
{
 r=no%10;
 rev=rev*10+r;
 no=no/10;
}
cout<<"\nReverse of "<<a<<" is: "<<rev;
getch();
}

Output

Enter any num : 964
Reverse of 164 is 469

Explanation of code

Code

while(no>0)
 {
  r=no%10;
  rev=rev*10+r;
  no=no/10;
 }
In Above code we first check number is greater than zero, now find reminder of number and get last digits of number after this step we place last digit at first postion (at unit place) usning "rev=rev*10+r". Again we divide number by 10 (no=no/10) and value are store in "no" variable. now we have a new number which have all digites except last digit. again check while loop and find remainder and get last digits of number. same process is repeted again and again untill condition is true.

Reverse of any Number Using for loop

Example

#include<iostream.h>
#include<conio.h>

  void main()
  {
   int no,rev=0,r,a;
   clrscr();
   cout<<"Enter any numb: ";
   cin>>no;
   a=no;
   for(;no>0;)
   {
    r=no%10;
    rev=rev*10+r;
    no=no/10;
   }
  cout<<"\nReverse of "<<a<<" is: "<<rev;
  getch();
 }

Output

Enter any num : 164
Reverse of 164 is 461

0 comments: