C Program to Reverse a Number with Output and Explanation
num % 10, build the reversed number by rev = rev * 10 + digit, and remove the last digit with num = num / 10 until num becomes zero.Examples
How to Think About It
%. Each digit you get, add it to a new number that you build by shifting its digits left (multiply by 10) and adding the new digit. Keep doing this until the original number is fully processed.Algorithm
Code
#include <stdio.h> int main() { int num, rev = 0, digit; printf("Enter a number: "); scanf("%d", &num); while (num != 0) { digit = num % 10; rev = rev * 10 + digit; num = num / 10; } printf("Reversed number: %d\n", rev); return 0; }
Dry Run
Let's trace the number 1234 through the code
Initial values
num = 1234, rev = 0
First loop iteration
digit = 1234 % 10 = 4; rev = 0 * 10 + 4 = 4; num = 1234 / 10 = 123
Second loop iteration
digit = 123 % 10 = 3; rev = 4 * 10 + 3 = 43; num = 123 / 10 = 12
Third loop iteration
digit = 12 % 10 = 2; rev = 43 * 10 + 2 = 432; num = 12 / 10 = 1
Fourth loop iteration
digit = 1 % 10 = 1; rev = 432 * 10 + 1 = 4321; num = 1 / 10 = 0
Loop ends
num = 0, reversed number = 4321
| num | digit | rev |
|---|---|---|
| 1234 | 4 | 4 |
| 123 | 3 | 43 |
| 12 | 2 | 432 |
| 1 | 1 | 4321 |
Why This Works
Step 1: Extract last digit
Using num % 10 gets the last digit of the number, like peeling one digit off.
Step 2: Build reversed number
Multiply the reversed number by 10 to shift digits left, then add the extracted digit to append it.
Step 3: Remove last digit
Divide the original number by 10 using integer division to drop the last digit and continue the process.
Alternative Approaches
#include <stdio.h> int reverse(int num, int rev) { if (num == 0) return rev; return reverse(num / 10, rev * 10 + num % 10); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); printf("Reversed number: %d\n", reverse(num, 0)); return 0; }
#include <stdio.h> #include <string.h> int main() { char str[20]; printf("Enter a number: "); scanf("%s", str); int len = strlen(str); printf("Reversed number: "); for (int i = len - 1; i >= 0; i--) { putchar(str[i]); } printf("\n"); return 0; }
Complexity: O(d) time, O(1) space
Time Complexity
The loop runs once for each digit in the number, so time depends on the number of digits d.
Space Complexity
Only a few integer variables are used, so space is constant O(1).
Which Approach is Fastest?
The iterative method is fastest and uses least memory; recursion adds overhead, and string method is less numeric.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative (mod/div) | O(d) | O(1) | Numeric reversal, efficient |
| Recursion | O(d) | O(d) | Elegant code, but uses stack memory |
| String reversal | O(d) | O(d) | Simple for text, not numeric operations |