Problem: Write a C program to check whether the given string is a palindrome string or not.
Example:
Input: mom Output: Palindrome
A palindrome string is a string which when reversed is equal to the original string. For example mom, noon, malayalam, etc.
The best method to check palindrome string is to compare the first half of the string with the reverse of its second half.
Steps to check palindrome number in C:
- Input a string.
- Find the length of the string.
- Loop from
i=0
toi<length/2
withk=length-1
.- check if
string[i] != string[k]
.- If the condition is true, then the characters are not the same hence the given string is not a palindrome, so
break
out of the ‘for’ loop.
- If the condition is true, then the characters are not the same hence the given string is not a palindrome, so
- check if
- Otherwise, the string is Palindrome.
Here is the implementation of the steps in C:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
char string[30];
int length;
bool flag = true;
//1. Input String
printf("Input a string \n");
scanf("%[^\n]s",string);
//2. Find the length of the input string
for(length=0; string[length] != '\0'; length++);
//3. Iterate through the 1st half of the string
for(int i=0, k=length-1; i<(length/2); i++, k--){
/*
*'k' is the backward index,
*'i' is the forward index
*/
//3.1 compare forward index character with the backward one
if(string[i] != string[k]){
/*
*If found that string is not palindrome,
*there is no need of further iteration
*/
flag = false;
break;
}
}
/*
*If flag remains true then-
*string is palindrome, otherwise not.
*/
flag ? printf("Palindrome \n") : printf("Not Palindrome \n");
}
Output:
To compare the first half of the string with its second half, we have used two index variable i
and k
.
After each iteration, we increment i
and decrement k
to keep comparing the successive characters of the first half with their corresponding characters in the second half.
If in any iteration the comparison fails (i.e. string[i] != string[k]), then the input string is not a palindrome.
It is important to note, that the above program to check palindrome string is case sensitive. If the user inputs “Mom” then the output will be “Not Palindrome”. In order to make it case sensitive, lower the case of the string after the user input.