Write a C++ program that reverses a given integer entered by the user.
Input and Output Examples
- Input: 123
Output: The reverse of 123 is 321. - Input: 9876
Output: The reverse of 9876 is 6789.
Algorithm to reverse a number:
- Start the Program: Include necessary headers and declare the use of the standard namespace.
- Prompt for Input: Ask the user to enter an integer.
- Read the Input: Store the integer in a variable.
- Reverse the Number: Use a method to reverse the digits of the number.
- Display the Output: Print the reversed number.
- End the Program: Finish execution cleanly.
C++ Programs with Different Methods to Reverse a Number
Method 1: Using Arithmetic Operations
This method involves using arithmetic operations to extract digits from the number and build the reversed number.
#include <iostream>
using namespace std;
int main() {
int num, reversedNum = 0; // Declare variables for the input number and the reversed number.
cout << "Enter an integer: ";
cin >> num;
// Reverse the number using arithmetic operations
while (num != 0) {
int digit = num % 10; // Extract the last digit of num.
reversedNum = reversedNum * 10 + digit; // Append the digit to reversedNum.
num /= 10; // Remove the last digit from num.
}
cout << "The reverse of " << num << " is " << reversedNum << "." << endl; // Display the reversed number.
return 0;
}
Method 2: Using String Conversion
This method converts the number to a string, reverses the string, and then converts it back to an integer.
#include <iostream>
#include <string>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
string numStr = to_string(num); // Convert the integer to a string.
string reversedNumStr(numStr.rbegin(), numStr.rend()); // Reverse the string.
int reversedNum = stoi(reversedNumStr); // Convert the reversed string back to an integer.
cout << "The reverse of " << num << " is " << reversedNum << "." << endl;
return 0;
}