3 Simple C programs to check palindrome string

Simple C Program to check palindrome string or whether string is palindrome or not: To check palindrome, declare a variable flag and initialize it to 1 and then compare first element with last element then second element with second last element and so on.

 Now if you find any unmatched pair like in string str[3]="abc", str[0]!=str[1]. then initialize flag to 0 and break the loop other do nothing.
string aabaa, babaabab are palindrome and cbasic, examples are not palindrome.

C Program to check palindrome

/* C program to check palindrome string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[100];
 int n,i,j,flag=1;
 printf("Enter a string: ");
 /* gets to read space in string */
 gets(str);
 /* length of the string */
 n=strlen(str);
 i=0;
 j=n-1;
 /* compare string elements */
 while(i<j)
 {
  if(str[i]!=str[j])
  {
   flag=0;
   break;
  }
  i++;
  j--;
 }
 if(flag)
 printf("String is palindrome\n");
 else
 printf("String is not palindrome\n");
 return 0;
}

Another C Program to check palindrome

/* C program to check palindrome string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[100];
 int n,i,j;
 printf("Enter a string: ");
 /* gets to read space in string */
 gets(str);
 /* length of the string */
 n=strlen(str);
 i=0;
 j=n-1;
 /* compare string elements */
 while(i<j)
 {
  if(str[i]!=str[j])
  {
   break;
  }
  i++;
  j--;
 }
 if(i>=j)
 printf("String is palindrome\n");
 else
 printf("String is not palindrome\n");
 return 0;
}

C Program to check palindrome using another string

/* C program to check palindrome string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[100];
 char str2[100];
 int n,i,j;
 printf("Enter a string: ");
 /* gets to read space in string */
 gets(str);
 strcpy(str2,str);
 strrev(str2);
 
 if(strcmp(str,str2)==0)
 printf("String is palindrome\n");
 else
 printf("String is not palindrome\n");
 return 0;
}



Popular posts from this blog