C Program to Check Palindrome String
"Palindrome" if all match or "Not Palindrome" otherwise.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <string.h> int main() { char str[100]; int i, j, isPalindrome = 1; printf("Enter a string: "); scanf("%99s", str); i = 0; j = strlen(str) - 1; while (i < j) { if (str[i] != str[j]) { isPalindrome = 0; break; } i++; j--; } if (isPalindrome) printf("Palindrome\n"); else printf("Not Palindrome\n"); return 0; }
Dry Run
Let's trace the input "madam" through the code.
Input string
str = "madam"
Initialize pointers
i = 0 (points to 'm'), j = 4 (points to 'm')
Compare characters
str[i] == str[j] ('m' == 'm'), move i to 1, j to 3
Compare characters
str[i] == str[j] ('a' == 'a'), move i to 2, j to 2
Pointers meet
i == j (both 2), middle character 'd', no mismatch found
Result
All pairs matched, string is palindrome
| i | j | str[i] | str[j] | Match? |
|---|---|---|---|---|
| 0 | 4 | m | m | Yes |
| 1 | 3 | a | a | Yes |
| 2 | 2 | d | d | Yes |
Why This Works
Step 1: Two-pointer comparison
Using two pointers, one at the start and one at the end, lets us compare characters from both ends moving inward.
Step 2: Early exit on mismatch
If any pair of characters differ, we can stop immediately because the string cannot be a palindrome.
Step 3: Complete check
If all pairs match until pointers meet or cross, the string reads the same forwards and backwards, confirming it is a palindrome.
Alternative Approaches
#include <stdio.h> #include <string.h> int main() { char str[100], rev[100]; int len, i; printf("Enter a string: "); scanf("%99s", str); len = strlen(str); for (i = 0; i < len; i++) { rev[i] = str[len - i - 1]; } rev[len] = '\0'; if (strcmp(str, rev) == 0) printf("Palindrome\n"); else printf("Not Palindrome\n"); return 0; }
#include <stdio.h> #include <string.h> int isPalindrome(char str[], int start, int end) { if (start >= end) return 1; if (str[start] != str[end]) return 0; return isPalindrome(str, start + 1, end - 1); } int main() { char str[100]; printf("Enter a string: "); scanf("%99s", str); if (isPalindrome(str, 0, strlen(str) - 1)) printf("Palindrome\n"); else printf("Not Palindrome\n"); return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program compares characters from both ends once, so it runs in linear time proportional to the string length.
Space Complexity
It uses constant extra space by comparing in place without storing additional copies.
Which Approach is Fastest?
The two-pointer method is fastest and most memory efficient compared to reversing the string or recursion.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Two-pointer comparison | O(n) | O(1) | Fastest and memory efficient |
| Reverse string and compare | O(n) | O(n) | Simple but uses extra memory |
| Recursive check | O(n) | O(n) | Elegant but uses call stack |