C Palindrome example

27. January 2012 17:36

 

The following example will check for a palindrom in C. You know one of thoose words spelt the same forwards as backwards. The smart part of this program is the edge case where you have an odd number of letters in the string. Well actually this can simply be ignored since there is no point in comparing the middle charecter to its self.

 

 

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

int try(char *str) {
    int len = strlen(str);
    int i;
    for(i =0;i<len/2;i++)
        if (str[i] != str[len - 1 - i])
            return 0;
    return 1;
}

int main(int argc, char**argv) {
    char *s1 = "ffoof";
    char *s2 = "foof";
    char *s3 = "fooof";

    if (try(s1))
        printf("%s\n", s1);

    if (try(s2))
        printf("%s\n", s2);

    if (try(s3))
        printf("%s\n", s3);

    return 0;
}

 

E-mail Kick it! DZone it! del.icio.us Permalink


Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading