Tuesday, January 24, 2012

Write a C program to check for palindromes

Method1


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

void isPalindrome(char *string);

int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
exit(0);
}

void isPalindrome(char *string)
{
char *start, *end;

if(string)
{
start = string;
end = string + strlen(string) - 1;

while((*start == *end) && (start!=end))
{
if(start < end)start++;
if(end > start)end--;
}

if(*start!=*end)
{
printf("\n[%s] - This is not a palidrome!\n", string);
}
else
{
printf("\n[%s] - This is a palidrome!\n", string);
}
}
printf("\n\n");
}





Method2


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

int isPalindrome(char string[]);

int main()
{
isPalindrome("avon sees nova");
isPalindrome("a");
isPalindrome("avon sies nova");
isPalindrome("aa");
isPalindrome("abc");
isPalindrome("aba");
isPalindrome("3a2");
return(0);
}

int isPalindrome(char string[])
{
int count, countback, end, N;

N = strlen(string);
end = N-1;

for((count=0, countback = end); count <= (end/2); ++count,--countback)
{
if(string[count]!=string[countback])
{
return(1);
}
}

printf("\n[%s] is a palidrome!\n", string);
return(0);
}

No comments:

Post a Comment