Exercise 11-2 - CBD page 383 - Kurt Nørmark

Solution index                   Textual C program


/* Programmed by Kurt Normark, April 2003 */

#include <stdio.h>

int is_palindrome_len(char *str, int lgt);

int is_palindrome(char *str){
  int lgt = strlen(str);
  return is_palindrome_len(str, lgt);
}

int is_palindrome_len(char *str, int lgt){
  int result;

  if (lgt >= 2)
   result = 
     str[0] == str[lgt-1] &&
     is_palindrome_len(str+1, lgt-2);
  else
    result = 1;

  return result;
}


int main(void) {

  char str[100];

  do{
    printf("Enter string: ");
    scanf("%s", str);

    if (strcmp(str,"exit") != 0){
      if (is_palindrome(str))
        printf("%s is a palindrome\n", str);
      else
        printf("%s is NOT a palindrome\n", str);
    }
  }
  while (strcmp(str,"exit") != 0);

  return 0;
}

In this dissection we explain the predicate (boolean function) which finds out if a string is a palindrome. A palindrome reads the same both forward and backward.
 

int is_palindrome(char *str){
  int lgt = strlen(str);
  return is_palindrome_len(str, lgt);
}
The function is_palindrome uses a helping function is_palindrome_len, which also takes the string length as a parameter. The helping function is programmed in order to avoid repeated calculations of the length of the palindrome candiate string.
 

int is_palindrome_len(char *str, int lgt){
  int result;

  if (lgt >= 2)
   result = 
     str[0] == str[lgt-1] &&
     is_palindrome_len(str+1, lgt-2);
  else
    result = 1;

  return result;
}
The function is_palindrome_len does the real work. First, if the length of the string is less than two, the string is always considered as a palindrome. In that case, we just return true (1). In case the string length is 2 or more, the string is a palindrome if the first and last letter in the string are equal, and if the 'middle part of the string' recursively is a palindrome. As an example, the middle part of the string "computer" is "ompute". Notice the way we use pointer arithmetic to find the middle part of a string.
 

int main(void) {

  char str[100];

  do{
    printf("Enter string: ");
    scanf("%s", str);

    if (strcmp(str,"exit") != 0){
      if (is_palindrome(str))
        printf("%s is a palindrome\n", str);
      else
        printf("%s is NOT a palindrome\n", str);
    }
  }
  while (strcmp(str,"exit") != 0);

  return 0;
}
In the main function we prompt the user for a string which is exercised for the palindrome property. Around this we have a simple loop, which terminates if we enter the string "exit".
 


Generated: Wednesday, March 29, 2006, 12:33:08
This program dissection page is generated from an XML-in-LAML source file