C Program to Check Whether a Given String is Palindrome or Not

Here i am writing two different programs two check whether an input string is palindrome or not. The first program checks the string manually character by chatter from both ends. The other program make use of a string function strrev() (under string.h) to reverse the string. Therefore, the second program is more compact.

Program 1:

#include<stdio.h>

#include<string.h>

void main()

{

char a[20];

int i, len;

printf("\nEnter the string:\n");

gets(a);

len = strlen(a);

for (i = 0; i < len / 2; i++)

{

if (a[i] != a[len - i - 1])

break;

}

if (i == len / 2)

printf("\nThe string is palindrome");

else

printf("\nThe string is not palindrome");

}


Program 2

#include<stdio.h>

#include<string.h>

void main()

{

 char a[20], b[20];

 printf("\nEnter the string:\n");

 gets(a);

 strcpy(b, a);    /* copying a to b */

 strrev(a);    /* string a reversed */

 if (strcmp(a, b) == 0)

  printf("\nThe string is palindrome");

 else

  printf("\nThe string is not palindrome");

}


No comments :

Post a Comment