# 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

1. 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].
2. Checking that input number is positive or not, if it is negative program will be terminated.

## Logic for reversing a number in C++

1. Run a loop till num is greater than zero
2. Get digit using modulus operator (digit = num%10)
3. Add digit with sum*10 to make number reverse (sum = (sum*10) +digit)
4. Divide num by to 10 so that we can get another digit
5. 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!!!
```