# C++ program to reverse a number

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

Extras:

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:

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

## Reverse an integer number in C++

﻿

```#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!!!
```

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates