C++ Program to Reverse an Integer
#include <iostream>
using namespace std;
int main() {
int number, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> number;
while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
cout << "Reversed Number: " << reversedNumber;
return 0;
}
Explanation
- Include the necessary header files.
- Declare the main function.
- Declare integer variables
number
, reversedNumber
, and remainder
. - Prompt the user to enter an integer.
- Read the integer input from the user.
- Use a while loop to reverse the number:
- Calculate the remainder by finding the modulus of the number with 10.
- Update the
reversedNumber
by multiplying it by 10 and adding the remainder. - Divide the number by 10 to remove the last digit.
- Display the reversed number.