COMP1917 Computing 1
Session 2, 2016

Lab - Week 7


  1. Create a directory called lab7, and cd to this directory.

  2. A palindrome is a string which contains the same letters forwards as backwards (for example: "dad", "radar", "repaper").
    Start a new file called palindrome.c and write a function
    int isPalindrome( char s[] )
    
    which returns 1 if the string s is a palindrome, 0 otherwise. (Again, try to do it just using the string itself, i.e. without declaring or copying the characters to any other array.)

    Add a main() function which reads a string, calls the function isPalindrome() and prints "Yes, is a palindrome." or "No, not a palindrome." depending on the return value. (Try to do it without actually changing the string itself, or copying it into another string.)
    [Note: fgets() keeps the newline character '\n' at the end of the string. You may have to skip over this character in order to correctly check for a palindrome.]

    Now modify the isPalindrome() function so that it ignores case, word boundaries and non-alphabetic characters. You are free to use library functions like isalpha() and toupper(). Here are some famous palindromes which your program should correctly classify:

    kayak
    Madam, I'm Adam.
    Able was I ere I saw Elba.
    A man, a plan, a canal: Panama.
    Are we not drawn onward, we few, drawn onward to new era?
    
    (Again, try to do it without modifying the original string.)

  3. Recall that a string is an array of characters, with the special character '\0' used to mark the end of the string. As disussed in the tutorial, write a function
    char* reverse_string( char s[] )
    
    which takes a string s as parameter and returnes a dynamically allocated reversed string. For example, the string "live on" would be converted to "no evil".

    Combine your function with this main() function to produce a program called tnirp.c
    P.S. you should modify it to perform any cleanup.

    #define  MAXLEN  128
    
    int main( void )
    {
       char s[MAXLEN];
    
       printf("Enter string:\n");
       fgets( s, MAXLEN, stdin );
       char *rev = reverse_string( s );
       printf("%s\n", rev);
    
       return 0;
    }
    
    Here's how the input and output of your program should look:
    $ ./tnirp
    Enter String:
    The quick brown fox jumped over the lazy dog.
    
    .god yzal eht revo depmuj xof nworb kciuq ehT
    
    $ ./tnirp
    Enter String:
    It was the best of times. It was the worst of times.
    
    .semit fo tsrow eht saw tI .semit fo tseb eht saw tI
    
  4. When you have finished, show your work to your tutor and submit it using
    $ give cs1917 lab7 tnirp.c palindrome.c