Program to check a String palindrome in C

A string that reads the same a forwards and backwards is known as palindrome.

Like MADAM, RADAR, STATS, SOLOS, TENET, WOW

Here we will see programs to check whether a string is palindrome or not.

We use gcc 9.1.0 compiler to run our programs

We will discuss Palindrome program as below

  1. Simple program using loop
  2. Program using string reverse function
  3. Functions to check palindrome
  4. Recursion to check palindrome

1 Programs to check palindrome in C String

  1. Create a character array char str[100]
  2. Take input from user scanf("%s", str)
  3. Get String length strlen(str)
  4. match starting and ending characters by increasing loop counter for (i = 0; i <= length / 2; i++) up to mid of the string.
  5. Take one one character from start and end.
  6. From string starting take character in increasing order
  7. From string ending take character in decresing order
  8. match both characters if (str[i] == str[length - 1 - i])
  9. initialize counter to check each starting and ending characters are mating or not count++
  10. if loop variable and count variable is equal means all starting and ending characters are matching if (count == i)
  11. Display the result based on match or mismatch.

Output

2. Palindrome string program in c using string functions

program to check whether a string is palindrome or not can be also done using functions.

GCC 9.1.0 does not provide reverse functions.

Other compiler provides strrev() function.

We have created our own String reverse function to reverse the string.

Steps for checking string is palindrome or not

  1. Get String from user scanf("%s", str)
  2. Reverse the string using reverse(str, str1)
  3. Reverse string is stored in str1 variable
  4. Compare original and reversed string strcmp(str, str1)
  5. If string comparison is zero then string is palindrome else not.

3 Function to check String is Palindrome or not

Based on our first program we created a function checkPalindrome() that is used to check string is palindrome or not.

We created this function based on our second program.

Recursion to check string palindrome 

Recursion can also be used to check string palindrome.

  1. Create a function palindrome which takes character pointer as argument.
  2. find the length of string pointed by str.
  3. check condition if count variable i< length/2 then do step4 to step 6
  4. Match starting and ending character if matched increase variable c value
  5. increase the counter variable i value
  6. call again the same function with increasing base function palindrome(str + 1)
  7. if condition 3 is false again check if variable i and c are equal (c == i)
  8. if both are equal then string is palindrome so return 1. else return 0

variable i and c are declared as static because we have to track these value across multiple palindrome() function.