A palindrome is a word, phrase, number, or sequence of characters that reads the same forward and backward. Some common examples are "madam"
, "level"
, and "radar"
. In C programming, checking if a string is a palindrome helps you understand string manipulation, looping, recursion, and pointers.
This problem may look simple, but it teaches important concepts such as comparing characters, handling string length, and working with indexes. It is also a popular question in programming interviews because it shows how well you can handle string operations in C.
In this article, we will write several programs to check if a string is a palindrome. We will cover approaches using loops, pointers, and recursion. Each example will be explained step by step so you can fully understand how the code works.
Understanding the Problem
The goal is to read a string and check whether it reads the same when reversed.
For example:
- Input:
"madam"
→ Output: Palindrome - Input:
"hello"
→ Output: Not a Palindrome - Input:
"level"
→ Output: Palindrome
We will ignore the newline character \n
from input. For simplicity, we will also treat uppercase and lowercase letters as different (case-sensitive).
Program 1: Using a Loop
The simplest way to check for a palindrome is to compare the first character with the last, the second with the second last, and so on until the middle of the string.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
int i, len, flag = 1;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// remove newline character if present
str[strcspn(str, "\n")] = '\0';
len = strlen(str);
for (i = 0; i < len / 2; i++) {
if (str[i] != str[len - i - 1]) {
flag = 0;
break;
}
}
if (flag)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
This approach is efficient because it stops checking as soon as a mismatch is found.
Program 2: Using Pointers
We can also use two pointers, one starting at the beginning and the other at the end of the string, and move them towards each other.
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char *left, *right;
int flag = 1;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// remove newline character if present
str[strcspn(str, "\n")] = '\0';
left = str;
right = str + strlen(str) - 1;
while (left < right) {
if (*left != *right) {
flag = 0;
break;
}
left++;
right--;
}
if (flag)
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
This method shows the power of pointers in C, allowing direct traversal from both ends.
Program 3: Using Recursion
Recursion can also be used by comparing the first and last characters, then calling the function again on the substring in between.
#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: ");
fgets(str, sizeof(str), stdin);
// remove newline character if present
str[strcspn(str, "\n")] = '\0';
int len = strlen(str);
if (isPalindrome(str, 0, len - 1))
printf("The string is a palindrome.\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
This recursive approach is elegant but can be slightly less efficient due to repeated function calls.
Program 4: Case-Insensitive Palindrome Check (Ignoring Spaces and Punctuation)
In many cases, when we say a string is a palindrome, we usually mean it should match even if the case is different or if spaces and punctuation are present. For example:
"Madam"
should be treated as a palindrome."A man a plan a canal Panama"
is also a palindrome if we ignore spaces."No lemon, no melon"
is another famous palindrome that works only when ignoring punctuation and case.
To handle this, we need to first clean the input string by:
- Converting all characters to the same case (lowercase).
- Removing spaces and punctuation.
After that, we can check if the cleaned string is a palindrome using the same logic as before.
Here is a complete program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int isPalindrome(char *str) {
int left = 0, right = strlen(str) - 1;
while (left < right) {
if (str[left] != str[right])
return 0;
left++;
right--;
}
return 1;
}
int main() {
char str[200], cleaned[200];
int i, j = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// remove newline character if present
str[strcspn(str, "\n")] = '\0';
// Clean the string: keep only alphanumeric characters and convert to lowercase
for (i = 0; str[i] != '\0'; i++) {
if (isalnum((unsigned char)str[i])) {
cleaned[j++] = tolower((unsigned char)str[i]);
}
}
cleaned[j] = '\0';
if (isPalindrome(cleaned))
printf("The string is a palindrome (ignoring case, spaces, and punctuation).\n");
else
printf("The string is not a palindrome.\n");
return 0;
}
This program uses isalnum()
to check if a character is alphanumeric (letters or numbers) and tolower()
to convert everything to lowercase. The cleaned string is then passed to the palindrome-checking function.
This approach is closer to how palindromes are understood in natural language. It is also useful in applications like text analysis, searching, and natural language processing.
FAQs on Checking Palindromes in C
1. What is a palindrome?
A palindrome is a string that reads the same forwards and backwards, e.g., "madam"
, "level"
, or "radar"
.
2. Why do we need to remove the newline \n
from input?fgets()
keeps the newline character if there’s room in the buffer. If we don’t remove it, the program might incorrectly report that the string is not a palindrome.
3. Which method is the most efficient?
- Loop method: Fast and simple, stops checking at the first mismatch.
- Pointer method: Elegant and efficient, especially with large strings.
- Recursive method: Teaches recursion but can be slower and uses more stack space.
4. How do I check palindromes ignoring case, spaces, and punctuation?
- Convert all characters to the same case (e.g., lowercase).
- Remove non-alphanumeric characters using
isalnum()
. - Then check the cleaned string using any of the methods above.
5. Can I use ==
to compare characters in C?
Yes, you can compare individual characters with ==
, but you cannot use ==
to compare entire strings—that would compare memory addresses, not content.
6. What if the string contains numbers?
Numbers are treated like any other characters. For example, "12321"
is a palindrome, and "12345"
is not.
7. Is recursion always safe for palindrome checking?
For short strings, yes. But for very long strings, recursion can consume a lot of stack memory, making the loop or pointer approach safer.
8. Can palindromes include punctuation or spaces?
Yes, but usually we clean the string first to ignore spaces, punctuation, and case when checking for natural-language palindromes.
9. Should the check be case-sensitive?
It depends on the use case. If you want "Madam"
to be considered a palindrome, convert all letters to lowercase before comparison.
Conclusion
Checking if a string is a palindrome is a classic beginner problem in C programming. It helps you understand string handling, loops, conditions, and sometimes recursion. We started with a simple program that checks palindromes by comparing characters one by one, then improved it using recursion, and finally explored a more advanced version that ignores spaces, punctuation, and case differences.
The basic palindrome check is excellent for practice and for learning how to process strings. However, in real-world scenarios, people expect palindrome checks to be case-insensitive and to ignore spaces and punctuation. That is why the advanced version is more practical and closer to real applications.
By experimenting with all these methods, you will not only strengthen your understanding of C strings but also gain confidence in handling more complex problems in programming.
References & Additional Resources
A curated collection of textbooks, tutorials, and documentation for learning string manipulation and palindrome checks in C.
- Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language, 2nd Edition, Prentice Hall, 1988 – The classic reference covering strings, arrays, pointers, and essential C programming concepts.
- GeeksforGeeks: Check if a String is a Palindrome in C – Step-by-step explanation of multiple methods to check if a string is a palindrome, with beginner-friendly and advanced approaches.
- Tutorialspoint: C Strings – Overview of string declaration, initialization, manipulation, and character-handling functions in C.
- Cprogramming.com: Strings in C – Guide on manipulating strings, including comparisons, palindrome checks, and basic string algorithms.
- ASCII Table Reference – Useful resource for understanding character codes, case conversions, and comparisons in C.
- ISO C Standard Library Reference – Official reference for standard C string functions like
fgets()
,strlen()
, and other character-handling utilities.