In this post, you will learn how to Reverse a Number in C++.
This lesson will teach you how to Reverse a Number, with a while loop, assignment operator and mathematical functions using the C++ Language. Let’s look at the below source code.
How to Reverse a Number?
RUN CODE SNIPPETSource Code
#include <iostream> using namespace std; int main() { int n, rev=0, rem; cin>>n; cout<<"Enter a number: "<<n<<endl; while(n!=0) { rem=n%10; rev=rev*10+rem; n/=10; } cout<<"\nReversed Number: "<<rev; return 0; }
Input
23456
Output
Enter a number: 23456 Reversed Number: 65432
The statements #include<iostream>, using namespace std, int main are the main factors that support the function of the source code. Now we can look into the working and layout of the code’s function.
- Declare the the variables n, rev, rem as integers and assign the value 0 to rev
- Collect the number from the user and store it in the variable n using function
cin>>
 and display the value usingcout<<
 and the Insertion Operators'<<‘ , ‘>>’. - Create the while loop with the condition that the value n is not equal to 0.
- In the loop statement first we find the reminder of the value of n when divided by 10 and store the value in rem.
rev=rev*10+rem
we execute this statement where the value of rev is 0 and the value of rem is the reminder of the previous function.- We then replace the value stored in rev and replace it with the new value. In this function statement we obtain the number in the one’s place as the answer.
- The next function we divide the value of n with 10 and using the divide AND assignment operator store the value in n.
- When the loop is executed the new values are used, and the all the mathematical functions are performed.
- The loop is executed multiple times until the condition is false and the loop is terminated.
- The answer is displayed using the cout statement.
Note: The ‘ << endl ‘ in the code is used to end the current line and move to the next line and ‘\n’ is also a new line function, to understand how both the functions work exclude it from the code, move it around and work with it.