Reverse a Number

ā€œReverse a Numberā€ is a very basic programming exercise problem for beginners. Here, we are given a number, entered by user and our task is to write a program to reverse a number.

Example:

INPUT:
Num = 45
OUTPUT:
Num = 54

The steps required to reverse a number are as follows:

  1. Scan a number from a user.
  2. Initialize a reverse_number with 0.
  3. Now, one by one fetch out the last digit from a number using modulus operator and concatenate to reverse_number.
  4. Finally, print the reverse number.

C++ Program to reverse a number is as follows:

#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    //Scan the number  
    int num;  
    cout<<"Enter the number:";  
    cin>>num;  
      
    //Printing the number before reversing  
    cout<<"Number Before Reversing:"<<num<<"\n";  
      
    // Reverse the number  
    int reverse = 0;  
    while(num > 0)  
    {  
        int digit = num % 10;  
        reverse = reverse*10 + digit;  
        num = num/10;  
    }  
    num = reverse;  
      
    // Printing the number after reversing  
    cout<<"Number After Reversing:"<<num<<"\n";  
}  
OUTPUT:
Enter the number: 27
Number Before Reversing: 27
Number After Reversing: 72

You may also like...

Leave a Reply

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