C/C++ Arena

Step 6 of 6

Challenge: palindromes

This challenge combines what you've learned about strings with the two-index technique from reversing an array.

A palindrome reads the same forwards and backwards: level, racecar, noon. To check, compare the first character with the last, the second with the second-to-last, and so on toward the middle. If any pair differs, it's not a palindrome, and you can return 0 immediately. If every pair matches, return 1.

Finding the last character

The last real character of s is at index strlen(s) - 1 (the terminator is at strlen(s)). Start one index there and one at 0, and move them toward each other while the left one is still before the right one.

Here's a related loop that compares two strings character by character, ignoring upper and lower case. A palindrome check is similar, except it compares one string with itself, using one index from the front and one from the back:

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

int same_ignoring_case(const char a[], const char b[]) {
    size_t n = strlen(a);
    if (strlen(b) != n) {
        return 0;
    }
    for (size_t i = 0; i < n; i++) {
        if (tolower((unsigned char)a[i]) != tolower((unsigned char)b[i])) {
            return 0;
        }
    }
    return 1;
}

int main(void) {
    printf("%d %d\n", same_ignoring_case("Hello", "hELLO"), same_ignoring_case("cat", "car"));
    return 0;
}
1 0

Edge cases to think through

(The (unsigned char) cast before tolower is a C detail: the ctype functions require values that fit in an unsigned char, and some systems' char can be negative for non-English letters.)

Your turn: write int is_palindrome(const char s[]) returning 1 or 0. Compare characters from both ends moving inward, like reversing an array.

Previous: Characters are numbers