Google Add

Search

C++ Program to Reverse a Number

Write a C++ program to reverse a number. In this tutorial, we are going to write a program which takes an input number from a user and reverse this  number.

C++ Program to Reverse a Number


C program to reverse a number

C++ Program to Reverse a Number


 #include<iostream>
  using namespace std;

  int main()
  {
     int num, temp, rev=0;

     cout << "Enter a number \n";
     cin  >> num;

 
     while(num != 0){

       temp = num%10;
       rev  = (rev*10) + temp;
       num  = num/10;

     }

     cout<<"\n Reverse of a input number is "<< rev;

     return 0;

 }




Output -

Enter a number   243

Reverse of a input number is   342


Explanation -  


 We have input a number 243. 

STEP 1 -  While loop condition is true, as num is 243. Initially the value of rev is equal to 0.

 rev = 0 * 10 + 3; 
 num = 24; 

 STEP 2 -Now num is 24 and rev is 3. In next iteration while loop condition is true, 

 rev = 3*10 + 4; 
 num = 2; 

 STEP 3- Now num is 2 and rev = 34. So again, while loop condition is true, 

 rev = 34 * 10 + 2 
 num = 0; 

 Now number is zero while loop will break the value of rev is 342.


No comments:

Post a Comment