C++ Program to find Reverse of a Number

In this simple C++ program, we have to reverse a number. It is a beginner-level C++ program.

What is the reverse of a number?

Reversing a number means swapping the places of the number. That means we are printing the number in reverse order. For example, if we have a number 1234, we have to print that as 4321 using C++.

What is the reverse of a number?

The place value of the numbers is changed when we reverse the number.

How to find the reverse of a number in C++?

To find the reverse of the number entered by the user in c++, first, we have to take an integer input from the user and store it in a variable n. declare an integer variable reverse and set it to 0; reverse = 0. And a variable remainder.

For reversing a number we are using the while loop in C++. Loops are used to repeat a block of code. For example, if we want to repeat something 10 times, instead of writing it 10 times, we can use a loop.

Here we are using the while loop


While ( condition )
{ body of the loop }
 

Here,  The while loop evaluates the condition. If the condition is true, the code inside the while loop body is executed. The condition is repeated and the process continues until the condition goes wrong. When the condition gets false the loop terminates.

Here ,condition is n!=0;


While ( n!=0 )
{
     remainder = n;
     reverse = reverse * 10 + remainder;
     n /= 10;
}
 

Print the value of reverse on the screen. And exit the program.

What is the reverse of a number?

 ALGORITHM

Step 1:  Call the header file iostream.

Step 2:  Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare an integer type variable n, reverse=0, remainder.

Step 5: Print a message “Enter an integer”.

Step 6: Read the value to the variable n.

Step 7: Perform the following sub-steps until the condition 'n> 1' becomes false

  • Perform the operation 'n% 10' and assign the value to the variable remainder to store the remainder
  • Perform the operation 'reverse * 10 + remainder' and assign the value to the variable reverse to store in reverse
  • Perform the operation 'n/ 10' and assign the value to the variable to store the number without the last

Step 8: Print the reversed number

Step 9: Exit.

C++ Source Code

                                          #include <iostream>
using namespace std;

int main() {

  int n, reverse = 0, remainder;

  cout << "Enter an integer: ";
  cin >> n;

  while(n != 0) {
    remainder = n % 10;
    reverse = reverse * 10 + remainder;
    n /= 10;
  }

  cout << "Reversed Number = " << reverse;

  return 0;
}
                                      

OUTPUT

Enter an integer: 5624
Reversed Number = 4265