C program to check whether a string is palindrome or not


A string is a palindrome if it reads same from forward as well as backward. This is a C program to check whether a string is palindrome or not.

For instance “madam”

For proper understanding, the knowledge of following topics is required

C program to check whether a string is palindrome

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

int main()
{
   char text[20], reverse_text[20];
   int i,n, length = 0;

   printf("Enter text: ");
   gets(text);

   for (i = 0; text[i] != '\0'; i++)
   {
      length++; //this will calculate the length of given text
   }
   //Reverse the original text and store into reverse_text
   for (i = length - 1; i >= 0; i--)
   {
      reverse_text[length - i - 1] = text[i];
   }

   //Check whether reverse_text is same to original text
   for (n = 1, i = 0; i < length; i++)
   {
      if (reverse_text[i] != text[i])
      n = 0;
   }

   if (n == 1)
      printf("%s is a palindrome.", text);
   else
      printf("%s is not a palindrome", text);

   return 0;
}

Output

c program to check whether a string is palindrome or not

 

Explanation

At first, the original string is stored in text and reversed string is stored in reverse_text.  The length of the string is calculated and stored in length variable that is used while reversing the string from backward.

The third for loop is used to check whether the character of original and reversed string are same or not and if the character doesn’t match the value of n is set to 0.

The above program can be easily accomplished using standard library functions.

c program to check whether a string is palindrome or  not using function

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

int main()
{
   char string[50], string_reverse[50];

   printf("Enter the string: ");
   gets(string);

   strcpy(string_reverse, string);  //copy string into string_reverse
   strrev(string_reverse);          //reverse the value of string_reverse

   if (strcmp(string, string_reverse) == 0)  //compare both string
      printf("The given string is a palindrome.\n");
   else
      printf("The given string is not a palindrome.\n");

   return 0;
}

Output
palindrome string function output