Determining whether the string is a Palindrome

Last Updated On Saturday 6th Nov 2021

A palindrome is a string that reads the same regardless of whether it is forward or backward.

For example, the word madam is a palindrome because it reads the same way forwards and backward.

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

void main() {
   char str[80], rev[80];
   int n, i, x;
   printf("Enter a string: ");
   scanf("%s", str);
   n = strlen(str);
   x = 0;
   for (i = n - 1; i >= 0; i--) {
      rev[x] = str[i];
      x++;
   }
   rev[x] = '\0';
   if (strcmp(str, rev) == 0)
      printf("The %s is palindrome", str);
   else
      printf("The %s is not palindrome", str);
}
	
	// Enter a string: you
// The you is not a palindrome

// Enter a string: madam
// The madam is palindrome
	

Using the build-in strlen library function, we will compute the length of the entered string and assign it to the new variable.

By executing the for loop in reverse order, each of the characters of the string is accessed in reverse order.

Compare the two strings, the given string, and the reversed string, using strcmp.If Both equals, then this is a Palindrome.