Palindrome Program in C

Palindrome Program in C


Learn C Program for String Palindrome

By SimplilearnLast updated on Jul 8, 20211170

C Program for String Palindrome (Turning a String Over Its Head)

Table of Contents

Algorithmic Logic of C Program for String Palindrome

C Program for String Palindrome Using the Standard Method

C Program for String Palindrome Using a Function

C Program for String Palindrome Using Recursion

C Program for String Palindrome Using String Library Functions

View More

In this article, we will write a C program to check if a string is a palindrome. A string is said to be palindrome if it remains the same on reading from both ends. It means that when you reverse a given string, it should be the same as the original string. For instance, the string ‘level’ is a palindrome because it remains the same when you read it from the beginning to the end and vice versa. However, the string ‘Simplilearn’ is not a palindrome as the reverse of the string is ‘nraelilpmis,’ which is not the same.

Algorithmic Logic of C Program for String Palindrome

To write a C program for string palindrome, we need to follow the logic below:

  1. Create a function to check if the string is a palindrome: isPalindrome(str)
  2. Initialize indexes for low and high levels to be 0 and n-1, respectively
  3. Until the low index (l) is lower than the high index (h), do the following:
    1. If str(l) is different from str(h), return false
    2. If str(l) and str(h) are same, increment l, i.e., l++ and decrement h, i.e., h--
  4. If we reach this step, it means there is no mismatch, and the string is a palindrome; otherwise, if step 3.A is true, it is not a palindrome.

Let’s use this logic to write a C program to check if the given string is a palindrome.

#include <stdio.h>

#include <string.h>

// Implementing the logic in a function

void isPalindrome(char str[]){

// Initializing indexes

int l = 0;

int h = strlen(str) - 1;

// Step 4 to keep checking the characters until they are same

while (h > l){

if (str[l++] != str[h--]){

printf("%s is not a palindrome string\n", str);

return;

}

}

printf("%s is a palindrome string\n", str);

}