C++ Program to find the Reverse of a Number

Program to find the Reverse of a Number

Here we will discuss how to find the reverse of a given number using C++ programming

language.

To find the reverse of a number we will use loop and arithmetic operators(%, / ).

Let’s take an example for example:

When a number say 87201 is given as an input then its output or we can say its reverse
will be 10278.

Working

Let’s see how the code works

  • The user gives an input.
  • The input will be stored in an int type variable say num
  • A  do while loop is started
    • Modulus(%) of num is founded with 10 and stored in an int type variable say rem.

rem=num%10;

    •  An int variable reverse(initialised at 0) is multiplied by 10 and rem is added to it and the result is stored in reverse itself.

reverse=reverse*10+rem; 

    • num is divided by 10 and the value is stored in num itself.

num/=10;

    • The loop works until num is not equal to 0.

while(num!=0);

  •  reverse is printed as output as it is the reverse of the number entered by the user.
Program to find the reverse of a number

C++ Code

//C++ Program
//Reverse of a number
#include <iostream>
using namespace std;
//main program
int main()
{
//variables initialization
int num, reverse=0, rem;
cout<<"Enter a number: ";
//user input
cin>>num;
//loop to find reverse number
do
{
rem=num%10;
reverse=reverse*10+rem;
num/=10;
}while(num!=0);
//output
cout<<"Reversed Number: "<<reverse;
return 0;
}

Output

Enter a number: 1098
Reversed Number: 8901

Please Login/Signup to comment