C++
#include <iostream>
using namespace std;
int main() {
int num, reversed = 0, remainder;
cout << "Enter a number: ";
cin >> num;
int original = num;
while (num != 0) {
remainder = num % 10;
reversed = reversed * 10 + remainder;
num /= 10;
}
cout << "Reverse of " << original << " is: " << reversed << endl;
return 0;
}Output
Enter a number: 1234 Reverse of 1234 is: 4321
Reverse a Number in C++
This program teaches you how to reverse a number in C++. Reversing a number means reading its digits from right to left instead of left to right. For example, reversing 1234 gives 4321. This is a common programming problem that helps you understand digit manipulation, loops, and number operations.
What This Program Does
The program takes a number and reverses its digits. For example:
- Input: 1234
- Output: 4321
The process involves extracting digits from the right (one's place, ten's place, etc.) and building a new number from left to right.
Algorithm
The core logic uses a while loop:
cppwhile (num != 0) { remainder = num % 10; reversed = reversed * 10 + remainder; num /= 10; }
Step-by-step for num = 1234:
- Extract last digit: 1234 % 10 = 4, reversed = 4
- Remove last digit: 1234 / 10 = 123
- Extract last digit: 123 % 10 = 3, reversed = 43
- Remove last digit: 123 / 10 = 12
- Continue until num becomes 0
- Final result: reversed = 4321
Key Operations
Modulo Operator (%):
- num % 10 gives the last digit of the number
- Example: 1234 % 10 = 4, 123 % 10 = 3
Integer Division (/):
- num / 10 removes the last digit
- Example: 1234 / 10 = 123, 123 / 10 = 12
Building the Reversed Number:
- reversed = reversed * 10 + remainder
- This shifts existing digits left and adds the new digit on the right
- Example: If reversed = 43 and remainder = 2, then 43 * 10 + 2 = 432
Edge Cases
-
Zero: 0 reversed is still 0
-
Single Digit: 5 reversed is 5
-
Numbers Ending in Zero: 100 reversed = 1 (leading zeros are dropped)
-
Negative Numbers: This program doesn't handle negatives (convert absolute value first)
Summary
- Reversing a number extracts digits from right to left using modulo and division.
- The reversed number is built by shifting digits left and adding new digits on the right.
- Modulo (%) extracts the last digit, division (/) removes the last digit.
- This algorithm is fundamental for understanding digit manipulation and number operations.
This program is essential for learning digit manipulation, understanding loops, and solving number-related problems in C++.