Numbers · beginner
C Program to Reverse a Number
Reverse the digits of a number in C with % and / in a while loop, check whether it is a palindrome number, and avoid overflow when reversing large values.
- while loop
- building a number digit by digit
- palindrome numbers
- overflow
Reversing 12345 gives 54321. The trick is to build the result one digit at a time: multiply what you have by 10 and add the next digit. Comparing a number with its reverse also tells you whether it is a palindrome number, such as 12321.
The program
#include <stdio.h>
long long reverse(long long n) {
long long reversed = 0;
while (n != 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
return reversed;
}
int main(void) {
long long tests[] = {12345, 1200, 12321};
for (int i = 0; i < 3; i++) {
long long r = reverse(tests[i]);
printf("%lld reversed is %lld%s\n", tests[i], r, r == tests[i] ? " (palindrome)" : "");
}
return 0;
}12345 reversed is 54321
1200 reversed is 21
12321 reversed is 12321 (palindrome)How it works
- n % 10 takes the last digit of n.
- reversed * 10 + digit shifts the digits built so far one place left and appends the new digit.
- n /= 10 drops the digit that was just used; the loop stops when n is 0.
- Trailing zeros disappear: 1200 reversed is 21, because a number cannot start with zeros.
Another way: Print the digits in reverse instead
If you only need to print the digits backwards, keeping the zeros, print each digit as it is removed.
#include <stdio.h>
int main(void) {
int n = 1200;
do {
printf("%d", n % 10);
n /= 10;
} while (n != 0);
printf("\n");
return 0;
}0021Common mistakes
- Using int for the reversed value: 1,000,000,009 is a valid int, but its reverse 9,000,000,001 overflows.
- Using while (n > 0), which skips negative numbers; n != 0 works for both signs because % keeps the sign.
- Expecting leading zeros to be kept in a reversed number.
Try it yourself
- Read the number with scanf and say whether it is a palindrome.
- Count how many palindrome numbers there are between 1 and 10,000.
Open the program in the C Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 C examples, or write your own program in the online C Compiler.