Example program in C to detect palindromes

This is an example C program which checks whether the words on its command line are palindromes.

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

int palindrome (const char * s)
{
    int length;
    int j;
    int mid;

    length = strlen (s);
    mid = length / 2;
    for (j = 0; j < mid; j++) {
        char left = s[j];
        char right = s[length - j - 1];

        if (left != right) {
            return 0;
        }
    }
    return 1;
}

int main (int argc, char ** argv)
{
    int i;
    for (i = 1; i < argc; i++) {
        printf ("%s is ", argv[i]);
        if (! palindrome (argv[i])) {
            printf ("not ");
        }
        printf ("a palindrome.\n");
    }
    return 0;
}

(download)

The output of the example, run with

./p cat dog abba minim

looks like this:

cat is not a palindrome.
dog is not a palindrome.
abba is a palindrome.
minim is a palindrome.


Copyright © Ben Bullock 2009-2018. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer