Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to check given string is Palindrome or not

C Code Example — String Programs

ADVERTISEMENT

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

  1. Read a string and find its length.
  2. Calculate the last index (len - 1) and the mid point (len / 2).
  3. Run a loop from beg = 0 to mid.
  4. If a[beg] != a[last], set flag = 0 and break (it's not a palindrome).
  5. Decrement last-- on each iteration.
  6. 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)
ADVERTISEMENT