Home »
C++ programs »
C++ Most popular & searched programs
C++ program to reverse a number
Given a number, we have to reverse the given number using C++ program.
[Last updated : February 27, 2023]
Problem statement
In this program, we will learn how to reverse an integer number in C++?
Here, we will read an integer number through the keyboard and print its reverse number, let suppose input number is "16789", program will print "98761".
Steps to reverse a number
- Declaring integer variable num (to store input number) and sum (to store reverse number) as long integer so that we can input and reverse a large value [Read long integer and its value range].
- Checking that input number is positive or not, if it is negative program will be terminated.
Logic for reversing a number in C++
- Run a loop till num is greater than zero
- Get digit using modulus operator (digit = num%10)
- Add digit with sum*10 to make number reverse (sum = (sum*10) +digit)
- Divide num by to 10 so that we can get another digit
- Run this program until num is not less than or equal to zero
C++ program to reverse a number
#include <iostream>
using namespace std;
int main()
{
long int num, sum;
int digit;
//input integer number
cout << "Enter an integer number: ";
cin >> num;
//check validation
if (num < 0) {
cout << "Input positive number!!!" << endl;
return -1;
}
//Reverse number
sum = 0;
while (num > 0) {
digit = num % 10; //get digit
sum = (sum * 10) + digit;
num = num / 10;
}
cout << "Reverse number is: " << sum << endl;
return 0;
}
Output
First run:
Enter an integer number: 16789
Reverse number is: 98761
Second run:
Enter an integer number: -123
Input positive number!!!