Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C Program to Check if a Given String is a Palindrome?
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward. Words such as "madam" or "racecar" or the number "10801" are palindromes.
To check if a string is a palindrome, we need to compare characters from both ends moving toward the center. If the first character matches the last, second matches second-last, and so on, then the string is a palindrome.
Syntax
int isPalindrome(char str[]); // Returns 1 if palindrome, 0 otherwise
Example 1: Using Character Comparison
This approach compares characters from both ends of the string −
#include <stdio.h>
#include <string.h>
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
if (str[left] != str[right]) {
return 0; // Not a palindrome
}
left++;
right--;
}
return 1; // Is a palindrome
}
int main() {
char str1[] = "naman";
char str2[] = "hello";
if (isPalindrome(str1)) {
printf("%s is a palindrome<br>", str1);
} else {
printf("%s is not a palindrome<br>", str1);
}
if (isPalindrome(str2)) {
printf("%s is a palindrome<br>", str2);
} else {
printf("%s is not a palindrome<br>", str2);
}
return 0;
}
naman is a palindrome hello is not a palindrome
Example 2: Case-Insensitive Palindrome Check
This example handles both uppercase and lowercase characters −
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isPalindromeIgnoreCase(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
if (tolower(str[left]) != tolower(str[right])) {
return 0;
}
left++;
right--;
}
return 1;
}
int main() {
char str[] = "Madam";
if (isPalindromeIgnoreCase(str)) {
printf("%s is a palindrome (ignoring case)<br>", str);
} else {
printf("%s is not a palindrome<br>", str);
}
return 0;
}
Madam is a palindrome (ignoring case)
Key Points
- The basic approach has O(n/2) time complexity and O(1) space complexity.
- The algorithm only needs to check half the string length.
- Use
tolower()function for case-insensitive comparison. - Empty strings and single characters are considered palindromes.
Conclusion
Palindrome checking in C can be efficiently done using the two-pointer technique. This approach compares characters from both ends moving inward, providing optimal time and space complexity for the problem.
