What are C Palindrome Number Program- Free Online C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

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 while loop and use the % and / operators.
  • You understand function prototypes, arguments and return values from this chapter.
  • You can compile a program with gcc -Wall -Wextra and 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.

Peeling digits off 3113

n = 3113

n % 10 = 3 (last digit) n / 10 = 311 (remaining)

n = 311

n % 10 = 1 n / 10 = 31

n = 31

n % 10 = 1 n / 10 = 3

n = 3

n % 10 = 3 n / 10 = 0 (stop)

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.

  1. Set rev to 0.
  2. While the number is greater than 0, read its last digit with n % 10.
  3. Update rev = rev * 10 + digit.
  4. Remove the last digit with n = n / 10.
  5. When the loop ends, compare the original number with rev.
Flow of the reverse loop
1

Start

rev = 0 and n holds a copy of the input.

2

Read digit

digit = n % 10 extracts the rightmost digit.

3

Build reverse

rev = rev * 10 + digit appends the digit to the result.

4

Shrink input

n = n / 10 drops the digit that was just used.

5

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.

Passdigit = n % 10rev = rev * 10 + digitn = n / 10
133311
213131
313113
4331130

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.

Pass by value in this program

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

InputReversedResultWhy
00PalindromeThe loop never runs, rev stays 0
77PalindromeA single digit is its own reverse
12021Not a palindromeThe trailing zero disappears when reversed
101Not a palindromeSame reason, trailing zeros are lost
Negative numbersNot handledNeeds a decisionWith 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.

Watch out: Unsigned overflow wraps without any warning. Whenever you multiply inside a loop, ask what the largest possible value is and whether your type can hold it.

Alternative Ways to Test for a Palindrome

MethodIdeaStrengthWeakness
Full reverse (this lecture)Build the reversed number and compareShort and easy to explainCan overflow on large inputs
Half reverseReverse only the second half of the digits and compare with the first halfNever overflowsSlightly harder to read
String comparisonConvert to text with snprintf and compare characters from both endsWorks for any lengthUses 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

MistakeResultFix
Using while (n >= 0)Infinite loop, because n never becomes negativeUse while (n > 0)
Starting rev without initialising itGarbage in the answerSet rev = 0
Dividing by 10 and forgetting the remainderDigits are lostRead the digit with % 10 before shrinking
Calling the reverse function with a negative valueWrong resultHandle the sign before the call
Declaring rev too smallSilent overflowUse 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 % 10 to read the last digit and / 10 to 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.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →