C++ Program to Reverse an Integer Number.

In this post, we are going to learn how to reverse an integer and write code for it using the C++ programming language. This is a very good example to understand the while loop concept.


Let's understand the process of reversing an integer using one example:

Example:
Input: num = 2468
Output: 8642

Explanation:
num = 2468,  Let reverse = 0
reminder = 2468 % 10 = 8 
reverse = reverse * 10 + 8 
        = 0 * 10 + 8
        = 8
num = 2468 / 10 = 246

reminder = 246 % 10 = 6
reverse = reverse * 10 + 6 
        = 8 * 10 + 6
        = 86
num = 246 / 10 = 24

reminder = 24 % 10 = 4
reverse = reverse * 10 + 4 
        = 86 * 10 + 4
        = 864
num = 24 / 10 = 2

reminder = 2 % 10 = 2
reverse = reverse * 10 + 2 
        = 864 * 10 + 2
        = 8642 -> Output 
num = 2 / 10 = 0 
Loop end when we get num = 0.

So the basic logic behind the solution for this problem is there in below two points: 
  • Whenever we perform a modulo operation on any given integer by 10 then it returns us the remainder which is the last digit of that number. (432 % 10 = 2)
  • Whenever we divide any integer by 10 then it removes the last digit of that number. (432 / 10 = 43)

Below is the C++ Code Implementation:
//C++ Code for reversing an integer number
#include<iostream>
using namespace std;

int main(){
    int num, reverse, remainder;

    cout<<"Enter the number: ";
    cin>>num;

    while (num != 0)
    {
        remainder = num % 10;
        reverse = reverse * 10 + remainder;
        num = num / 10;
    }
    cout<<"The reverse number is: "<<reverse<<endl;

    return 0;
}
Output:
Enter the number: 4567
The reverse number is: 7654

Also see:

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS