C++ program to Reverse a Number

Write a C++ program to Reverse a Number with an example. In this reverse number example, the while loop checks whether the given value is greater than 0.

  • reminder = number%10 – It gives the last digit
  • reverse = reverse * 10 + reminder – It adds that last digit at the first position. Because of reverse * 10, the value will add at the 2nd, 3rd,…nth positions. Otherwise, it replaces the existing ones.
  • number= number/10 – it removes the last digit from it.
#include<iostream>

using namespace std;

int main()
{
	int number, reminder, reverse = 0;
	
	cout << "Please Enter the Number that you want to Reverse  =  ";
	cin >> number;
	
	while (number > 0)
	{
    	reminder = number % 10;
    	reverse = reverse * 10 + reminder;
    	number = number / 10;
	}
	cout << "\nReverse of given Number = " << reverse;
		
 	return 0;
}
C++ program to Reverse a Number using while loop

C++ program to Reverse a Number using For Loop

#include<iostream>

using namespace std;

int main()
{
	int number, reminder, reverse = 0;
	
	cout << "Please Enter the Num  =  ";
	cin >> number;
	
	for (;number > 0; number = number / 10)
	{
    	reminder = number % 10;
    	reverse = reverse * 10 + reminder;
	}
	cout << "\nReverse of given Num = " << reverse;
		
 	return 0;
}
Please Enter the Num  =  67859

Reverse of given Num = 95876

This C++ code helps to Reverse a Number using a Recursive Function.

#include<iostream>
using namespace std;

int reverseNumber(int number)
{
	static int reminder, reverse = 0;
	
	if (number > 0)
	{
    	reminder = number % 10;
    	reverse = reverse * 10 + reminder;
    	reverseNumber(number / 10);
	}
	
	return reverse;
	
}
int main()
{
	int num, rev = 0;
	
	cout << "Please Enter the Num  =  ";
	cin >> num;
	
	rev = reverseNumber(num);
	cout << "\nReverse of given = " << rev;
		
 	return 0;
}
Please Enter the Num  =  478956

Reverse of given = 659874

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.