L-4 MCS 275 Wed 17 Jan 2001

Below are listings for programs we discussed in class.
/* MCS 275 L-4 Wed 17 Jan 2001 program to illustrate strings */

#include <stdio.h>

#define  MAXLEN  80    /* maximum #characters in string */

int char_cnt (char s[]);
/* counts the number of characters in a string */
void invert (int n, char s[], char is[]);
/* given a string s of n characters, the string "is" on return
   contains the string s spelled backward */
int is_palindrome (int n, char s[]);
/* returns 0 if the word spelled backwards reads the same,
   returns 1 otherwise */

int main()
{
   char word[MAXLEN], inverse[MAXLEN];
   int n;

   printf("Give a word : ");
   scanf("%s", word);
   n = char_cnt(word);
   printf("The word \"%s\" contains %d characters.\n", word, n);
   invert(n,word,inverse);
   printf("The word spelled backwards : %s\n", inverse);
   if (is_palindrome(n,word) == 0)
      printf("The word is not a palindrome.\n");
   else
      printf("The word is a palindrome.\n");
   return 0;
}

int char_cnt (char s[])
{
   int i;
   for (i=0; i < MAXLEN; ++i)
      if (s[i] == '\0')
         return i;
   return MAXLEN;
}

void invert (int n, char s[], char is[])
{
   int i;
   for (i=0; i < n; ++i)
      is[i] = s[n-1-i];
   is[n] = '\0';
}

int is_palindrome (int n, char s[])
{
  int i;
  for (i=0; i < n/2; ++i)
     if (s[i] != s[n-1-i])
        return 0;
  return 1;
}