C Program to Reverse Number Using While Loop
num % 10, building the reversed number with rev = rev * 10 + digit, and reducing the original number with num = num / 10 until it becomes zero.Examples
How to Think About It
%. Then, add each digit to a new number by shifting the existing digits left (multiply by 10) and adding the new digit. Repeat this until the original number is fully processed (becomes zero).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 to see how it reverses.
Initial values
num = 1234, rev = 0
First iteration
digit = 1234 % 10 = 4; rev = 0 * 10 + 4 = 4; num = 1234 / 10 = 123
Second iteration
digit = 123 % 10 = 3; rev = 4 * 10 + 3 = 43; num = 123 / 10 = 12
Third iteration
digit = 12 % 10 = 2; rev = 43 * 10 + 2 = 432; num = 12 / 10 = 1
Fourth iteration
digit = 1 % 10 = 1; rev = 432 * 10 + 1 = 4321; num = 1 / 10 = 0
Loop ends
num is 0, reversed number is 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.
Step 2: Build reversed number
Multiply the current reversed number by 10 to shift digits left, then add the extracted digit.
Step 3: Remove last digit
Divide the original number by 10 to remove the last digit and prepare for the next iteration.
Alternative Approaches
#include <stdio.h> void reverse(int num) { if (num == 0) return; printf("%d", num % 10); reverse(num / 10); } int main() { int num; printf("Enter a number: "); scanf("%d", &num); printf("Reversed number: "); reverse(num); printf("\n"); 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--) { printf("%c", 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 the time complexity is O(d), where d is the number of digits.
Space Complexity
Only a few integer variables are used, so the space complexity is O(1), constant space.
Which Approach is Fastest?
The while loop method is efficient and uses constant space, while recursion adds call stack overhead and string conversion uses extra memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| While loop | O(d) | O(1) | Numeric reversal with minimal memory |
| Recursion | O(d) | O(d) | Simple code but uses call stack |
| String reversal | O(d) | O(d) | When input is treated as text |