What is Palindrome String in C- C Programming For Beginners

🚀 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 →

Free C Programming Course · Strings

Palindrome String in C

Check whether a word or phrase reads the same both ways, using two indexes and no extra memory.

A word that reads the same forwards and backwards is called a palindrome, and writing a palindrome string in C checker is one of the best small exercises for learning how strings really work in memory. You need the null terminator, array indexing, pointers and a clean loop, all in about fifteen lines. In this lecture of our free C programming course we build the check step by step, harden it, extend it to whole phrases, and finish with an embedded twist: palindromic bit patterns. It is a practical piece of C programming for embedded systems as much as a classroom puzzle.

What You Will Learn

  • What counts as a palindrome string in C, including the empty string and single characters
  • The two-index technique that needs no extra memory
  • Why strlen minus one is a trap when the string is empty
  • How to read a word safely with fgets and test it
  • How to ignore case, spaces and punctuation for phrases
  • How the same idea applies to bit patterns in a byte

Prerequisites

You should know how a C string is stored as a char array ending in a null byte, how to use strlen from string.h, and how to loop with indexes or pointers. Earlier lectures in this free C tutorial covered all of that.

What Is a Palindrome String in C?

A palindrome is a sequence that equals its own reverse. Radar, madam, level and noon are palindromes. Embedded is not. Three rules decide the corner cases before you write any code:

  • A string of length one, such as a, is a palindrome because there is nothing to mismatch.
  • The empty string is conventionally a palindrome as well.
  • By default C compares character codes, so Radar with a capital R is not a palindrome. The letters R (0x52) and r (0x72) differ.

Odd-length words have a middle character that pairs with nothing and needs no check. Even-length words pair up completely. Both cases fall out naturally from the technique below.

The Two-Index Idea

You do not need to build a reversed copy. Keep one index at the first character and one at the last, compare them, and walk both toward the middle. The moment two characters differ, the answer is no. If the indexes meet or cross without a mismatch, the answer is yes.

Two-pointer walk over the word radar
Step 1: compare index 0 with index 4 -> r equals r
radar
Step 2: move inward, compare index 1 with index 3 -> a equals a
radar
Step 3: pointers meet at the middle -> loop ends, palindrome
radar

For a word of length n the loop runs at most n/2 times, and it uses a couple of integers rather than a second buffer, which matters on a microcontroller with only a few kilobytes of RAM.

Palindrome String in C: First Working Program

Save this as palindrome.c.

#include <stdio.h>
#include <string.h>

static int is_palindrome(const char *s)
{
    size_t left  = 0;
    size_t right = strlen(s);

    if (right == 0)
        return 1;                 /* empty string reads the same both ways */
    right--;

    while (left < right) {
        if (s[left] != s[right])
            return 0;             /* first mismatch settles it */
        left++;
        right--;
    }
    return 1;
}

int main(void)
{
    const char *words[] = { "radar", "madam", "level", "embedded", "noon", "a", "", "Radar" };
    const int count = (int)(sizeof words / sizeof words[0]);

    for (int i = 0; i < count; i++)
        printf("\"%s\" -> %s\n", words[i], is_palindrome(words[i]) ? "palindrome" : "not a palindrome");
    return 0;
}

Build and run:

gcc -std=c17 -Wall -Wextra -o palindrome palindrome.c
./palindrome
"radar" -> palindrome
"madam" -> palindrome
"level" -> palindrome
"embedded" -> not a palindrome
"noon" -> palindrome
"a" -> palindrome
"" -> palindrome
"Radar" -> not a palindrome

Pay attention to three design decisions in the function.

  • The empty-string guard. strlen returns size_t, an unsigned type. For an empty string, strlen(s) – 1 would wrap around to a gigantic number and the loop would read far outside the array. Returning early before the subtraction removes the problem.
  • Early return instead of a flag. The function answers as soon as it sees a mismatch. This is shorter than carrying a status variable through the loop and impossible to leave uninitialised.
  • The loop condition left < right. When the indexes meet on the middle character of an odd word, there is nothing left to compare, so strict less-than is exactly right.
Early exit on the first mismatch: embedded
embedded
index 0 is e, index 7 is d -> different, stop at once, answer is no

Read a Palindrome String in C With fgets

An interactive version has to read the word from the keyboard. Avoid scanf with a bare %s, because it has no length limit and stops at the first space. Read the line with fgets, which respects the buffer size, then strip the newline that fgets keeps.

#include <stdio.h>
#include <string.h>

static int is_palindrome(const char *s)
{
    size_t n = strlen(s);

    for (size_t i = 0; i < n / 2; i++)
        if (s[i] != s[n - 1 - i])
            return 0;
    return 1;
}

int main(void)
{
    char word[32];

    printf("Enter a word: ");
    if (fgets(word, sizeof word, stdin) == NULL) {
        puts("no input");
        return 1;
    }
    word[strcspn(word, "\n")] = '\0';        /* drop the newline fgets keeps */

    printf("\"%s\" %s a palindrome\n", word, is_palindrome(word) ? "is" : "is not");
    return 0;
}

The newline is removed with word[strcspn(word, "\n")] = '\0';. strcspn returns the position of the first newline, or the string length if there is none, so the assignment is always safe. Run it twice with piped input:

printf 'racecar\n' | ./palindrome_input
printf 'toolchain\n' | ./palindrome_input
Enter a word: "racecar" is a palindrome
Enter a word: "toolchain" is not a palindrome

When you type at a terminal your own Enter key moves the cursor to a new line. With piped input there is no keystroke to echo, so the answer appears right after the prompt on the same line. The program behaves identically in both cases.

Palindrome Phrases: Ignore Case and Punctuation

Famous phrases such as “A man, a plan, a canal: Panama” are palindromes only if you ignore spaces, commas and capitalisation. The fix is to let each pointer skip characters that are not letters or digits, and to compare lower-case versions of the rest.

Phrase mode: both pointers skip anything that is not a letter or digit
Aspaceman,…amanaP
left pointer moves right past spaces and commas, right pointer moves left past ? and :
tolower() on both sides, so A and a count as equal
#include <ctype.h>
#include <stdio.h>
#include <string.h>

static int is_phrase_palindrome(const char *s)
{
    const char *left  = s;
    const char *right = s + strlen(s);        /* one past the last character */

    while (left < right) {
        while (left < right && !isalnum((unsigned char)*left))
            left++;
        while (left < right && !isalnum((unsigned char)*(right - 1)))
            right--;
        if (left >= right)
            break;
        if (tolower((unsigned char)*left) != tolower((unsigned char)*(right - 1)))
            return 0;
        left++;
        right--;
    }
    return 1;
}

int main(void)
{
    const char *phrases[] = {
        "A man, a plan, a canal: Panama",
        "Was it a car or a cat I saw?",
        "No lemon, no melon",
        "Embedded Systems",
        "!!!"
    };
    const int count = (int)(sizeof phrases / sizeof phrases[0]);

    for (int i = 0; i < count; i++)
        printf("%-32s %s\n", phrases[i], is_phrase_palindrome(phrases[i]) ? "yes" : "no");
    return 0;
}
A man, a plan, a canal: Panama   yes
Was it a car or a cat I saw?     yes
No lemon, no melon               yes
Embedded Systems                 no
!!!                              yes

Here the right pointer is kept one position past the character under examination, so the code looks at *(right - 1). That avoids ever forming a pointer before the start of the string. Both ctype calls receive a value cast to unsigned char, which the standard requires for safe use with isalnum and tolower.

Edge case to discuss: the string !!! contains no letters or digits, so no pair ever mismatches and the function answers yes. Whether that is right depends on your application. If you need at least one alphanumeric character, count them while scanning and reject when the count is zero.

An Embedded Twist: Bit Palindromes

The same two-ended idea applies to numbers. Peripherals such as SPI shift registers sometimes need bits sent in the opposite order, so firmware often reverses the bits of a byte. A byte whose pattern equals its own reverse is a bit palindrome, and the test is simply reverse_bits(v) == v.

#include <stdint.h>
#include <stdio.h>

static uint8_t reverse_bits(uint8_t v)
{
    uint8_t r = 0;

    for (int i = 0; i < 8; i++) {
        r = (uint8_t)((r << 1) | (v & 1u));
        v = (uint8_t)(v >> 1);
    }
    return r;
}

static void show_bits(uint8_t v, char out[9])
{
    for (int i = 0; i < 8; i++)
        out[i] = (v & (0x80u >> i)) ? '1' : '0';
    out[8] = '\0';
}

int main(void)
{
    const uint8_t samples[] = { 0x81, 0x5A, 0xB4, 0x00, 0xFF, 0x3C };
    const int count = (int)(sizeof samples / sizeof samples[0]);

    for (int i = 0; i < count; i++) {
        char a[9], b[9];
        uint8_t rev = reverse_bits(samples[i]);

        show_bits(samples[i], a);
        show_bits(rev, b);
        printf("0x%02X = %s  reversed = %s  -> %s\n",
               samples[i], a, b, rev == samples[i] ? "bit palindrome" : "not a palindrome");
    }
    return 0;
}
0x81 = 10000001  reversed = 10000001  -> bit palindrome
0x5A = 01011010  reversed = 01011010  -> bit palindrome
0xB4 = 10110100  reversed = 00101101  -> not a palindrome
0x00 = 00000000  reversed = 00000000  -> bit palindrome
0xFF = 11111111  reversed = 11111111  -> bit palindrome
0x3C = 00111100  reversed = 00111100  -> bit palindrome

0x5A is 01011010, which reads the same from both ends. 0xB4 is 10110100, whose reverse 00101101 differs. This is a good reminder that a palindrome is an idea about symmetry, not about letters.

Common Mistakes

MistakeWhat happensFix
Computing strlen(s) – 1 for an empty stringUnsigned wrap-around, out-of-bounds readsHandle length zero first
Comparing the whole string with strcmp after copying a reversed versionWorks, but needs a second bufferCompare from both ends in place
Using scanf with %s and no widthBuffer overflow on long inputUse fgets with sizeof
Forgetting the newline fgets keepsEvery word looks like it ends with a newline, so nothing matchesStrip it with strcspn
Expecting Radar to matchCase-sensitive comparison says noConvert with tolower first
Passing a plain char to tolower or isalnumUndefined behaviour for negative valuesCast to unsigned char

Best Practices, Performance and Security

  • Make the check a small pure function that takes const char * and returns int. It is easy to test and reuse.
  • Test the boundaries: empty string, one character, two equal characters, two different characters, odd and even lengths.
  • The algorithm is O(n) in time and O(1) in extra memory, so it is safe even in tiny firmware.
  • Never trust the length of text coming from outside. Read with fgets and a fixed buffer.
  • Do not modify the input while checking. The const qualifier documents that promise and lets you pass string literals.

Summary and Key Takeaways

  • A palindrome string in C equals its own reverse, and the empty string and single characters count.
  • Two indexes moving inward solve it in n/2 steps with no extra memory.
  • Guard against strlen minus one on empty input.
  • Use fgets plus strcspn for safe line input.
  • For phrases, skip non-alphanumeric characters and compare lower-case values.
  • The same symmetry idea works on bit patterns in embedded code.

Conclusion

The palindrome string in C exercise looks like a toy, yet it rehearses everything that matters in real string handling: terminators, unsigned arithmetic traps, safe input and careful character classification. Once the idea is comfortable, try variations, for example checking only the first n characters, or returning the position of the first mismatch. Continue with the next lecture of this free embedded C course, where we change the case of a string and reverse it in place.

Frequently Asked Questions About Palindrome Strings in C

How do you check a palindrome string in C?

Put one index at the first character and one at the last, compare them, and move both toward the middle. Return false at the first mismatch and true if they meet.

Is the empty string a palindrome?

By convention yes. It reads the same in both directions because it has nothing to compare.

Why is strlen(s) – 1 dangerous?

strlen returns an unsigned size_t. For an empty string the subtraction wraps to a huge value, so the loop would read memory far outside the array.

How do I make the check ignore case?

Convert both characters with tolower before comparing, casting the argument to unsigned char first.

Do I need to reverse the string to test it?

No. Comparing from both ends works in place and uses no extra memory.

Can a number be a palindrome?

Yes. A decimal number or a bit pattern is a palindrome when its digits or bits read the same from both ends.

What is the time complexity of the two-index method?

It is O(n) in time, with at most n/2 comparisons, and O(1) in extra space.

Keep Building Your C Skills for Free

Every lecture in this free embedded C course pairs a clear idea with a program you can run. Carry on with strings next.

💬 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 →