HomeC++C++ Program to Reverse a Number

C++ Program to Reverse a Number

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 SNIPPET

Source 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.

  1. Declare the the variables n, rev, rem as integers and assign the value 0 to rev
  2. Collect the number from the user and store it in the variable n using function cin>>  and display the value using cout<< and the Insertion Operators'<<‘ , ‘>>’.
  3. Create the while loop with the condition that the value n is not equal to 0.
  4. In the loop statement first we find the reminder of the value of n  when divided by 10 and store the value in rem.
  5. 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.
  6. 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.
  7. The next function we divide the value of n with 10 and using the divide AND assignment operator store the value in n.
  8. When the loop is executed the new values are used, and the all the mathematical functions are performed.
  9. The loop is executed multiple times until the condition is false and the loop is terminated.
  10. 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.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this post, you will learn how to Generate Multiplication Table using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Display Fibonacci Sequence using C++ programming language. This lesson will teach you...
  • C++
  • January 30, 2022
In this post, you will learn how to Find GCD of two Numbers using C++ programming language. This lesson will...
  • C++
  • January 30, 2022