🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Palindrome Number Program
Lecture 23 of our free C programming course: write a palindrome number program in C with functions, a hand trace, edge cases and an overflow warning.
Welcome back to the free C programming course from EmbeddedPathashala. In this free C tutorial we write a complete palindrome number program in C using two small functions: one that reverses the digits of a number and one that decides whether the number reads the same in both directions. It is the perfect exercise for practising function arguments and return values.
A palindrome is a number that remains the same when its digits are reversed, for example 3113 or 1221. The logic behind the palindrome number program in C uses only the remainder and division operators, so it is also a gentle introduction to the digit-by-digit processing that embedded C programming uses when it formats numbers for a display or parses them from a serial stream.
What You Will Learn
- How to design a palindrome number program in C with a reusable function
- How the remainder and division operators peel digits off a number
- How to trace the reverse loop by hand with a table
- Why passing a value to a function protects the caller’s variable
- How integer overflow can silently break a digit-reversal program
- Edge cases: zero, single digits and numbers that end in zero
- Two alternative ways to test for a palindrome
Prerequisites
Before you start
- You can write a
whileloop and use the%and/operators. - You understand function prototypes, arguments and return values from this chapter.
- You can compile a program with
gcc -Wall -Wextraand read its output.
What Is a Palindrome Number?
A palindrome number is a number that stays the same when you write its digits in reverse order. The number 3113 reversed is 3113, so it is a palindrome. The number 4096 reversed is 6904, so it is not. Single-digit numbers are trivially palindromes, because one digit reversed is itself.
Before writing any code, decide how a computer can reverse a number without turning it into text. The answer is arithmetic. Dividing an integer by 10 throws away its last digit, and taking the remainder after dividing by 10 reads that last digit. Repeating these two steps visits every digit from right to left.
n = 3113
n = 311
n = 31
n = 3
Algorithm for the Palindrome Number Program in C
The reverse operation builds a new number, usually called rev, starting from zero. For every digit we obtain, we shift the digits already collected one place to the left by multiplying by 10, and then add the new digit. After the last digit has been processed, rev holds the reversed number. The palindrome test is then a single comparison between the original and the reversed value.
- Set
revto 0. - While the number is greater than 0, read its last digit with
n % 10. - Update
rev = rev * 10 + digit. - Remove the last digit with
n = n / 10. - When the loop ends, compare the original number with
rev.
Start
rev = 0 and n holds a copy of the input.
Read digit
digit = n % 10 extracts the rightmost digit.
Build reverse
rev = rev * 10 + digit appends the digit to the result.
Shrink input
n = n / 10 drops the digit that was just used.
Test
If n is still greater than 0 repeat from step 2, otherwise return rev.
Tracing the Palindrome Check by Hand
Tracing is the best way to trust a loop. The table below follows the input 3113 through the loop. We confirmed each line by running a short program that prints the values after every pass.
| Pass | digit = n % 10 | rev = rev * 10 + digit | n = n / 10 |
|---|---|---|---|
| 1 | 3 | 3 | 311 |
| 2 | 1 | 31 | 31 |
| 3 | 1 | 311 | 3 |
| 4 | 3 | 3113 | 0 |
After pass 4 the value of n is 0, so the loop stops. The variable rev equals 3113, which equals the original input, so the number is a palindrome.
Complete Palindrome Number Program in C
Here is the full program. It tests six sample numbers so that you see both outcomes. Notice that the work is split into two functions with clear names. The program is entirely original code for this course, written with an ep_ prefix on every function.
Program palin.c
#include <stdio.h>
/* reverse the decimal digits of a non-negative number */
static unsigned long ep_reverse_digits(unsigned long n)
{
unsigned long rev = 0;
while (n > 0) {
rev = rev * 10 + (n % 10);
n /= 10;
}
return rev;
}
static int ep_is_palindrome(unsigned long n)
{
return n == ep_reverse_digits(n);
}
int main(void)
{
unsigned long samples[] = { 3113, 1221, 4096, 7, 120, 0 };
size_t count = sizeof samples / sizeof samples[0];
for (size_t i = 0; i < count; i++) {
printf("%lu -> reversed %lu -> %s\n",
samples[i], ep_reverse_digits(samples[i]),
ep_is_palindrome(samples[i]) ? "palindrome" : "not palindrome");
}
return 0;
}
Output:
3113 -> reversed 3113 -> palindrome
1221 -> reversed 1221 -> palindrome
4096 -> reversed 6904 -> not palindrome
7 -> reversed 7 -> palindrome
120 -> reversed 21 -> not palindrome
0 -> reversed 0 -> palindrome
gcc -std=c11 -Wall -Wextra -o palin palin.c
./palin
How the functions cooperate
ep_is_palindrome() calls ep_reverse_digits() and returns the result of the comparison, which is 1 for true and 0 for false in C. The main() function then uses the conditional operator to pick the words to print. Because both helper functions are declared static, they are private to this file, which is good practice for helper routines in embedded projects.
Why the Caller’s Variable Stays Safe
Inside ep_reverse_digits() the loop keeps dividing n by 10 until it reaches zero. You might worry that the original number is destroyed. It is not, because C passes arguments by value. The parameter n is a private copy, and changing the copy has no effect on the caller. That is why ep_is_palindrome() can still compare against the original after the reverse function has finished.
Caller
Holds the original value 3113 in samples[0]. It is never modified.
ep_reverse_digits
Receives a private copy named n. The loop reduces the copy to 0 and then returns rev.
ep_is_palindrome
Compares its own untouched parameter with the returned reversed value.
Edge Cases of a Palindrome Number Program in C
| Input | Reversed | Result | Why |
|---|---|---|---|
| 0 | 0 | Palindrome | The loop never runs, rev stays 0 |
| 7 | 7 | Palindrome | A single digit is its own reverse |
| 120 | 21 | Not a palindrome | The trailing zero disappears when reversed |
| 10 | 1 | Not a palindrome | Same reason, trailing zeros are lost |
| Negative numbers | Not handled | Needs a decision | With an unsigned parameter a negative input would be converted to a huge positive value, so check the sign first |
A number that ends in zero can never be a palindrome, because its reverse would have to begin with a zero digit, which numbers do not store. The program handles this correctly without any special code, as the output for 120 shows.
Overflow: The Silent Bug in Digit Reversal
Reversing a large number can produce a result that no longer fits in the variable. Suppose a 32-bit unsigned variable holds 4000000009. Its reverse should be 9000000004, which is larger than the biggest 32-bit unsigned value. We tested this with a short program, and the loop reported:
Observed result
reversed 4000000009 in 32-bit unsigned = 410065412 (true answer 9000000004)
The arithmetic wrapped around silently, and the printed number is wrong. For a palindrome check this could even produce a false positive. There are two common protections: use a wider type such as unsigned long long for rev, or compare the digits from both ends without building a reversed number at all.
Alternative Ways to Test for a Palindrome
| Method | Idea | Strength | Weakness |
|---|---|---|---|
| Full reverse (this lecture) | Build the reversed number and compare | Short and easy to explain | Can overflow on large inputs |
| Half reverse | Reverse only the second half of the digits and compare with the first half | Never overflows | Slightly harder to read |
| String comparison | Convert to text with snprintf and compare characters from both ends | Works for any length | Uses a buffer and library code, which costs memory in firmware |
Real-World Uses in Embedded C Programming
You will rarely need to test palindromes in production firmware, but the digit loop in this program is everywhere. A 4-digit seven-segment display needs the digits of a temperature reading separated by % 10 and / 10. A serial command parser builds a number by multiplying by 10 and adding each received digit, exactly like the rev update. Converting a counter to decimal characters for a log message uses the same pattern. Learning it here, in a small program, makes those tasks easy later in this free embedded C course.
Common Mistakes and Troubleshooting
| Mistake | Result | Fix |
|---|---|---|
Using while (n >= 0) | Infinite loop, because n never becomes negative | Use while (n > 0) |
Starting rev without initialising it | Garbage in the answer | Set rev = 0 |
| Dividing by 10 and forgetting the remainder | Digits are lost | Read the digit with % 10 before shrinking |
| Calling the reverse function with a negative value | Wrong result | Handle the sign before the call |
Declaring rev too small | Silent overflow | Use a wider type |
Best Practices, Performance and Security
Best practices
- Split the work into a reverse function and a test function so each can be reused and tested alone.
- Give every function a prototype or define it before use, and keep helpers
static. - Write down the range of valid inputs in a comment next to the function.
- Test the edge cases: 0, a single digit and a number ending in 0.
For performance, the loop runs once per digit, so its cost grows with the number of digits, which is at most about ten for a 32-bit value. The division operator is the slowest step on small microcontrollers without a hardware divider, so inside a time-critical interrupt handler you may prefer a lookup approach. For security, remember that any value that arrives from outside, such as a serial command, must be range-checked before you feed it to a loop that multiplies.
Summary and Key Takeaways
Remember
- Use
% 10to read the last digit and/ 10to drop it. - Build the reverse with
rev = rev * 10 + digit. - A number is a palindrome when it equals its own reverse.
- Pass by value means the original number survives the call.
- Numbers ending in zero are never palindromes, and large inputs can overflow.
Conclusion
You have built a clean palindrome number program in C from two functions, traced it by hand, run it and examined its weak points. The same digit-peeling pattern appears again in the next program, where we test numbers for primality. Keep practising in this free C programming course by trying the half-reverse method as a challenge, and compare your result with the output shown above.
Frequently Asked Questions
What is a palindrome number in C?
It is a number that equals its own reverse, such as 3113 or 1221. A C program finds the reverse with the remainder and division operators and then compares.
How do you reverse a number in C without strings?
Loop while the number is greater than 0. Read the last digit with n % 10, update rev = rev * 10 + digit and drop the digit with n /= 10.
Why does the original number not change after the function call?
C passes arguments by value, so the function works on a private copy of the number.
Is 120 a palindrome?
No. Its reverse is 21 because the trailing zero vanishes, so any number ending in zero fails the test.
Can the palindrome check overflow?
Yes. If the reversed value does not fit in the variable, the arithmetic wraps silently. Use a wider type or the half-reverse method.
Where is digit reversal used in embedded systems?
The same digit loop drives seven-segment displays, number parsing from serial input and formatting values for logs.
Is this part of a free embedded C course?
Yes. EmbeddedPathashala offers this free C programming course so that students can practise C programming for embedded systems at no cost.
Keep Going With the Free Embedded C Course
Next we use the same digit-by-digit thinking to write a prime number program with a reusable function.

2 Comments