Q:

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.

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