Thursday, May 26, 2011

The classic Palindrome problem

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

int isPalindrome( char *s );

int main ( void )
{
   int i = 0;
   int ch;
   char s[100];
 
   while ((ch = getchar()) != ('\n')) {
      if (isalpha(ch)) {
         ch = toupper(ch);
         s[i] = ch;
         i++;
      }
   }
   s[i]='\0';
 
   if ( isPalindrome(s) == 1) {
      printf("Yes, it is a palindrome.\n");
   } else {
      printf("No, it is not a palindrome.\n");
   }
 
   getchar();  
   return 0;
 
}
 
int isPalindrome( char *s )
{
   int i = strlen(s)-1;
   int j = 0;
 
   while (j < i) {
      if(s[j] != s[i]) {
         return 0;
      }
      i--;
      j++;
   }
   return 1;
}

No comments:

Post a Comment