A palindrome is a word, sentence, or sequence that reads the same forward and backward — ignoring differences in capitalization for word-level palindromes. Examples: “racecar”, “GADAG”, “level”, “9009”. The most efficient check uses a two-pointer approach: one pointer starts at the left end, one at the right, and they advance toward each other until they meet or find a mismatch.
The original post used conio.h, void main(), and a non-standard initializer revString[25]={''}. It also manually built a reversed copy then compared — which is correct but allocates an extra buffer unnecessarily. The two-pointer approach in this rewrite needs O(1) extra space.
C Program: Palindrome String Check (Two-Pointer)
/* Check if a string is a palindrome (without strrev)
* Compile: gcc -ansi -Wall -Wextra palindrome_str.c -o palindrome_str */
#include <stdio.h>
#include <string.h>
int is_palindrome(const char *s)
{
int left = 0;
int right = (int)strlen(s) - 1;
while (left < right) {
if (s[left] != s[right])
return 0;
left++;
right--;
}
return 1;
}
int main(void)
{
char s[256];
printf("Enter a string: ");
if (fgets(s, sizeof(s), stdin) == NULL) return 1;
s[strcspn(s, "\n")] = '\0';
if (is_palindrome(s))
printf("\"%s\" is a palindrome.\n", s);
else
printf("\"%s\" is NOT a palindrome.\n", s);
return 0;
}
How to Compile and Run
gcc -ansi -Wall -Wextra palindrome_str.c -o palindrome_str
./palindrome_str
Sample Output
Enter a string: GADAG "GADAG" is a palindrome. Enter a string: racecar "racecar" is a palindrome. Enter a string: hello "hello" is NOT a palindrome. Enter a string: A "A" is a palindrome.
Two-Pointer Trace — “racecar” (length 7)
| Step | left | right | s[left] | s[right] | Match? |
|---|---|---|---|---|---|
| 1 | 0 | 6 | ‘r’ | ‘r’ | Yes → continue |
| 2 | 1 | 5 | ‘a’ | ‘a’ | Yes → continue |
| 3 | 2 | 4 | ‘c’ | ‘c’ | Yes → continue |
| 4 | 3 | 3 | left < right is false → exit loop → palindrome | ||
Two-Pointer Trace — “hello” (length 5)
| Step | left | right | s[left] | s[right] | Match? |
|---|---|---|---|---|---|
| 1 | 0 | 4 | ‘h’ | ‘o’ | No → return 0 |
Code Explanation
- Two-pointer technique — start left at index 0 and right at
strlen(s) - 1. Compare the characters at both ends. If they match, move both pointers inward. If they don’t match, the string is not a palindrome. When left and right cross or meet (left ≥ right), all pairs matched — it is a palindrome. - O(n/2) comparisons, O(1) space — each pair is checked once. The loop runs at most n/2 iterations. No reversed copy of the string is needed — only two integer index variables. Compare to the original approach (build reversed string + strcmp) which uses O(n) extra memory.
- Single-character strings are palindromes —
strlen("A") - 1 = 0, soright = 0andleft = 0. The conditionleft < rightis false immediately — the loop never executes and the function returns 1 (palindrome). Correct by definition. - Empty string edge case —
strlen("") - 1 = -1. Since right isint, it becomes -1, andleft < right(0 < -1) is immediately false. Returns 1 — the empty string is technically a palindrome. - Case sensitivity — this program is case-sensitive: “Racecar” is NOT a palindrome because ‘R’ != ‘r’. For case-insensitive checking, convert each character with
tolower()before comparing:if (tolower((unsigned char)s[left]) != tolower((unsigned char)s[right])).
What This Program Teaches
- The two-pointer pattern — two pointers moving toward each other from both ends of an array is one of the most useful patterns in competitive programming and interviews. It solves palindrome check, two-sum in a sorted array, container with most water, and many others in O(n) time with O(1) space.
- strlen returns size_t, not int —
strlen()returnssize_t, which is an unsigned type. Subtracting 1 fromstrlen("")would give a very large positive number if stored in size_t (unsigned underflow). Casting tointfirst gives the expected -1. Always be careful with unsigned arithmetic when computing lengths. - Separate the logic into is_palindrome() — extracting the check into a function makes main() clean and makes the check reusable. A function that returns int (0 = false, 1 = true) is the idiomatic C boolean.
Related Programs
- Palindrome Number Check in C
- Substring Search with strstr() in C
- String Functions in C — Complete Guide
- Compare Strings in C
- Pointers in C — Complete Guide
Recommended book:
The C Programming Language — Kernighan & Ritchie (India) |
(US)
|
C Programming: A Modern Approach — K.N. King (India) |
(US)
Practice what you learned: C Aptitude Questions — or try our C Programming Quiz App on Android.
3 comments on “C program to check whether a given string is palindrome or not”
Can I know Why there fflush(stdin); is used
Hello,
Good question. I assume you know why fflush is used in general. I'm sorry, I can't recall why I had to fflush in this program. The program is working fine without it too.
You can find many discussion threads on internet about this. I'm leaving it as it is for the time being. Will remove when I get time to find more about this.
Thanks for bringing this up btw.