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.
c++ program to reverse a number

Algorithm:-

  1. Take integer number as input and store it in num
  2. we have to extract the digits of number using Modulus % operator
  3. reverse intialized to 0
  4. A  do while loop is started
    • unit digit is extracted and stored in rem

                       rem=num%10;

    •  We have to shift the reverse to left by multiplying by 10 and add remainder to it

                       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);

      5. reverse is printed as output as it is the reverse of the number entered by the user.

 

c++ reverse a number

C++ Code

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

Output

Enter a number:345
Reversed Number:543