Friday, May 13, 2011

Check if a String is Palindrome in C

"A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers." - Wikipedia

This is a C program to check if a given string is a palindrome or not.
/**
* A palindrome is a word, phrase, number or other sequence
* of units that can be read the same way in either direction
**/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(void)
{
int i, j, l;
char str1[20], str2[20];
printf("Enter any word:");
scanf("%s", str1);
/* Find the length of the string */
l = strlen(str1);
j = 0;
/* Store the reversed string in another string str2 */
for(i = l - 1; i >= 0; i-- )
str2[j++] = str1[i];
str2[j] = '\0';
/* Compare str1 and str2 */
/* strcmp returns 0 when the strings are equal, */
/* a negative integer when s1 is less than s2, */
/* or a positive integer if s1 is greater than s2, */
/* according to the lexicographical order. */
if(strcmp(str1, str2) == 0)
printf("The word is a palindrome\n");
else
printf("The word is not a palindrome\n");
return 0;
}
view raw palindrome.c hosted with ❤ by GitHub
Written by

No comments:

Post a Comment