String Palindrome in C Program

#include <stdio.h>
#include <string.h>
int main()
{
   char str[100];
   int i, len;
   int flag = 0;

   printf("Enter a string: ");
   gets(str);

   len = strlen(str);

   for(i=0;i<len;i++)
   {
      if(str[i] != str[len-i-1])
      {
         flag = 1;
         break;
      }
   }

   if (flag)
   {
      printf("%s is not a palindrome", str);
   }
   else
   {
      printf("%s is a palindrome", str);
   }

   return 0;
}

OUTPUT

Explanations

  1. Declare an array str of type char to store the input string.
  2. Declare integer variables i and len to store the loop counter and the length of the string, respectively.
  3. Declare an integer variable flag and initialize it to 0. This variable is used to indicate whether the string is a palindrome or not.
  4. Prompt the user to enter a string and read the input string using the gets() function.
  5. Calculate the length of the input string using the strlen() function.
  6. Use a for loop to iterate through the string characters. For each character, check if it is equal to the corresponding character from the end of the string. If not, set the flag variable to 1 and break out of the loop.
  7. If the flag variable is set to 1, print a message indicating that the string is not a palindrome. else, print a message indicating that the string is a palindrome.