How to display numbers in reverse order in C++
In this shot, we will discuss how to display numbers in reverse order in C++.
Approach
We will use a loop to print numbers in reverse order.
Let’s look at the image below to understand it better.
In the image above, we can see that the number was initially written from left to right, but it is written from right to left when we reverse the number.
We will do the same. We can use the for loop to generate code to reverse a number in C++.
Code
Let’s look at the following code snippet to understand it better.
#include <iostream>using namespace std;int main() {int number, remainder, sum = 0;cin >> number;for (int i = number; number != 0; number = number/10){remainder = number % 10;sum = sum * 10 + remainder;}cout << "The number in reverse order is: " << sum << endl;return 0;}
Enter the input below
(Enter a number above to generate output)
Explanation
-
In line 5, we initialize the
number,remainder, andsumvariables. -
In line 6, we take the input as
number. -
From lines 7 to 11, we initialize a
forloop, where we give conditions to run the loop till the number is not equal to0. We store the value in thesumvariable. -
In line 12, we print the output stored in the variable
sum.
In this way, we can use loops to reverse a number in C++.