C Program to check given string is Palindrome or not
Objective
Write a C program to check if a given string is a Palindrome.
Algorithm / Approach
- Read a string and find its length.
- Calculate the
lastindex (len - 1) and themidpoint (len / 2). - Run a loop from
beg = 0tomid. - If
a[beg] != a[last], setflag = 0andbreak(it's not a palindrome). - Decrement
last--on each iteration. - After the loop, check the flag to print the result.
main.c
#include<stdio.h>
int main( ) {
char a[100];
int beg, mid, last, len=0;
int flag = 1;
printf("Enter a String : ");
gets(a);
while(a[len] != '\0'){
len++;
}
last = len - 1;
mid = len/2;
for (beg=0; beg < mid; beg++){
if (a[beg] != a[last]) {
flag = 0;
break;
}
last--;
}
if (flag == 1){
printf("String is Palindrome ");
}
else {
printf("String is not Palindrome");
}
return 0;
}
Expected Output
<b>OUTPUT 1:</b> Enter a String : prowess String is not Palindrome <b>OUTPUT 2:</b> Enter a String : malayalam String is Palindrome
Explanation of the Program
- A Palindrome string reads the same forwards and backwards (e.g., "madam" or "racecar").
- Instead of building a reversed copy of the string and comparing them, this approach is mathematically optimized. We check the first character against the last character, the second against the second-to-last, moving inwards until we meet in the middle. If all mirror pairs match, it's a palindrome!
Complexity
Time Complexity
O(n) - Specifically O(n/2), which simplifies to O(n).
Space Complexity
O(1)