In this post, we will learn how to reverse a number using C++ Programming language.
This program asks the user to enter an integer, then it reverse the integer using a while loop.
So, without further ado, let’s begin this tutorial.
C++ Program to Reverse a Number
// C++ Program to Reverse a Number #include <iostream> using namespace std; int main(){ int n, rem, reverse_number = 0; // Asking for input cout << "Enter an integer: "; cin >> n; // Reversing the number while (n != 0){ rem = n % 10; reverse_number = reverse_number * 10 + rem; n = n / 10; } // Displaying output cout << "Reversed Number: " << reverse_number << endl; return 0; }
Output
Enter an integer: 746
Reversed Number: 647
How Does This Program Work ?
int n, rem, reverse_number = 0;
In this program, we have declared three integer data type variables named n, rem and reverse_number. reverse_number variable has assigned a value of 0.
// Asking for input cout << "Enter an integer: "; cin >> n;
The user is asked to enter a number which he wants to reverse. This value gets stored in the ‘n‘ named variable.
// Reversing the number while (n != 0){ rem = n % 10; reverse_number = reverse_number * 10 + rem; n = n / 10; }
The entered integer gets reversed using a while loop. Suppose, the user enters an integer 746.
- 1st While Loop Iteration: while (746 != 0), here the condition is True, so the loop continues.
- rem = n % 10 = 746 % 10 = 6
- reverse_number = reverse_number * 10 + rem = 0 * 10 + 6 = 0 + 6 = 6
- n = n / 10 = 746 / 10 = 74
Now, n becomes 74 and reverse_number becomes 6.
- 2nd While Loop Iteration: while (74 != 0), here the condition is also True, so the loop continues.
- rem = n % 10 = 74 % 10 = 4
- reverse_number = reverse_number * 10 + rem = 6 * 10 + 4 = 60 + 4 = 64
- n = n / 10 = 74 / 10 = 7
Now, the value of n becomes 7 and reverse_number becomes 64.
- 3rd While Loop Iteration: while (7 != 0), here the condition is True, so the loop continues.
- rem = n % 10 = 7 % 10 = 7
- reverse_number = reverse_number * 10 + rem = 64 * 10 + 7 = 640 + 7 = 647
- n = n / 10 = 7 / 10 = 0
Now, the value of n becomes 0 and reverse_number becomes 647.
- 4th While Loop Iteration: while (0 != 0), here the condition is False, so the loop terminates and we get reverse_number = 647 which is the reverse of the original number.
// Displaying output cout << "Reversed Number: " << reverse_number << endl;
Then, the reversed number of the entered integer is displayed on the screen using the cout statement.
Conclusion
I hope after going through this post, you understand how to reverse a number using C++ Programming language.
If you have any doubt regarding the program, then contact us in the comment section. We will be delighted to assist you.
Also Read: