Course contentsShow
← C
Lesson 442 of 1,2196. Arrays and StringsFree lesson

Checking if a string is a palindrome

Checking if a string is a palindrome

What you'll learn: How to use a "two-pointer" approach to determine if a word reads the same forward and backward.

The Mirror Concept

A palindrome is a string that is a mirror image of itself. Words like "level," "radar," or "racecar" are perfect examples. In C, checking for a palindrome is a classic exercise in array navigation.

Think of the string as a hallway with a person at each end. To see if the hallway is symmetrical, both people walk toward the middle, one step at a time. At every step, they shout out the color of the floor tile they are standing on. If their colors ever disagree, the hallway isn't a palindrome. If they meet in the middle without any disagreements, you've found a match!

The Two-Pointer Technique

To translate this into code, we use two integer variables to act as our "pointers" (or indices). One starts at index 0 (the beginning), and the other starts at length - 1 (the last character before the null terminator).

We compare the characters at these two positions. If they match, we move the start index forward and the end index backward. If they don't match, we can stop immediately—it's not a palindrome.

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

int main() {
    char word[] = "radar";
    int start = 0;
    int end = strlen(word) - 1;
    bool isPalindrome = true;

    while (start < end) {
        // Compare characters at both ends
        if (word[start] != word[end]) {
            isPalindrome = false;
            break; // No need to keep checking
        }
        
        // Move toward the center
        start++;
        end--;
    }

    if (isPalindrome) {
        printf("%s is a palindrome!\n", word);
    } else {
        printf("%s is not a palindrome.\n", word);
    }

    return 0;
}

Why stop in the middle?

In the code above, the condition start < end is vital. We don't need to check the entire string twice. Once the two pointers meet or cross in the middle, every character has already been compared to its partner on the opposite side. If we kept going, we would just be re-checking what we already know, which makes the algorithm less efficient.

Key takeaway

To check for a palindrome, use two indices to compare characters from the outside in, stopping early if a mismatch is found.