The following example will check for a palindrome in C. You know one of those 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 character 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;
}




Last Modified: 12 December 2016

Releated Posts


2013-02-16 - C - Some simple examples of using strcat
2012-11-03 - C - How to override malloc / free
2012-09-22 - Linux Programming - Using inotify for detecting file modifications
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-04-05 - Using gdb to debug a core file
2012-03-15 - C - Is the stdin a tty
2012-03-13 - C - Converting from char / string to int using atoi
2012-03-08 - C - UDP Socket example
2012-02-20 - C - Get home dir location in linux
2012-02-17 - C - IP address validation
2012-02-15 - C - Get current ip address of an interface
2012-02-10 - Using asprintf instead of sprintf or snprintf
2012-01-31 - C - Example of how to overwrite argv
2012-01-30 - C - The string reverse
2012-01-27 - C - Palindrome
2012-01-26 - C - Example of using popen
2011-12-28 - C - gethostbyname example
2011-12-11 - C - Linux get mac address from interface
2011-07-22 - CSharp - Fibonacci sum
2011-07-13 - CSharp - Palindrome
2011-07-11 - CSharp - The string Reverse
2011-07-10 - CSharp - Interviews FizzBuzz