In this tutorial, you will learn writing program in the C to check whether a given string is palindrome or not .
The Complete logic behind to check whether a given string is palindrome or not:
- To check a given string is palindrome or not we just matching the first character with last and second with second last and so on.
- This process stops when it reached at mid of the string or if any character exist in string which not satisfy the given conditions means if they not matched.
Now before moving on writing the program first you should know
What is String palindrome?
A String is called as palindrome, when it not changes either we write it from starting point or last end of the String.
For example : “PeeP” is a palindrome string because we can write it either of any starting point or end point. But its meaning will not change. It will be always “PeeP”
But suppose “right” is a string and when we reverse it the it became “thgir”. Means “right” is not a palindrome. Because it become different after reverse.
How our program will behave?
This Program will take two String as an input. We will compare original string with string after reverse.
If the string matched after reverse with original then program will print “strings are palindrome”
And if Strings not matched then it will print “strings are not palindrome”.
C Program to check given string is palindrome or not
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main() {
char str[20];
int i, len, temp=0;
int flag = 0;
printf("Enter a string:");
scanf("%s", str);
len = strlen(str);
for(i=0; i < len ; i++) {
if(str[i] != str[len-i-1]) {
temp = 1;
break;
}
}
if (temp==0) {
printf("String is a palindrome");
}
else {
printf("String is not a palindrome");
}
return 0;
}
Output 1:
Enter a string:Quescol
String is not a palindrome
Output 2:
Enter a string:akaka
String is a palindrome
Explanation of the palindrome string program in c
- Above program is for to check a given string is palindrome or not.
- All logic is written in the main() method.
- In main() method we have 4 integer variables i, len, temp and flag. And one char variable str which is an array of character.
- Palindrome of string means we can read it either from left to right or right to left it appears same.
- So to check it we are comparing first character with last character and second character with second last character using for loop and so on until we reach at middle.
- If any position matches failed, then break for loop and set temp variable value to 1.
- Using if statement we compare if temp is equal to 0 then print “string is palindrome”. If temp is equal to 1 then print “string is not a palindrome”.
This was the all logic behind checking the given two strings are anagram or not.
If any doubt just do comment 🙂
Thank you.