C++ Program to Reverse a Number
This program takes an integer as input and reverses the digits of the number.
Syntax
#include <iostream>
using namespace std;
int main() {
int num, rev = 0, rem;
cout << "Enter a number: ";
cin >> num;
while (num != 0) {
rem = num % 10;
rev = rev * 10 + rem;
num /= 10;
}
cout << "Reverse of the number is: " << rev << endl;
return 0;
}
Example
Enter a number: 12345
Reverse of the number is: 54321
Explanation
In this program, we take an integer as input using cin
and initialize variables rev
and rem
to 0. Using a while
loop, we iterate through the digits of the number by taking the modulo 10 of the number (num % 10
) and adding it to variable rev
multiplied by 10 (which is used to shift the digits to the left). We then update the value of num
by dividing it by 10 (num /= 10
) to remove the last digit that was added. The loop continues until num
becomes 0. Finally, we print the value of variable rev
using cout
.
Use
This program can be used to reverse the digits of any given number. It can be helpful in various mathematical and logical operations, such as checking if a number is a palindrome or finding the sum of the digits of a number.
Important Points
- The reversed number is obtained by taking the modulo 10 of the original number and shifting it to the left using multiplication with 10.
- The original number is updated by removing the last digit using division with 10.
- The loop continues until the original number becomes 0.
Summary
In summary, this program takes an integer as input and reverses its digits by using a while
loop to take the modulo 10 of the number and shift it to the left using multiplication with 10, and updating the original number by removing the last digit using division with 10. The reversed number is printed using cout
.