Introduction
A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Examples include “radar”, “level”, and “madam”. This C program checks if a given string is a palindrome.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_LENGTH 100
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while (left < right) {
// Ignore non-alphanumeric characters
while (left < right && !isalnum(str[left])) {
left++;
}
while (left < right && !isalnum(str[right])) {
right--;
}
// Compare characters, case insensitive
if (tolower(str[left]) != tolower(str[right])) {
return 0; // Not a palindrome
}
left++;
right--;
}
return 1; // Is a palindrome
}
int main() {
char str[MAX_LENGTH];
printf("Enter a string: ");
fgets(str, MAX_LENGTH, stdin);
// Remove the newline character if present
str[strcspn(str, "\n")] = '\0';
if (isPalindrome(str)) {
printf("'%s' is a palindrome.\n", str);
} else {
printf("'%s' is not a palindrome.\n", str);
}
return 0;
}
Explanation
- Libraries Used:
stdio.h
: For standard input/output functions.string.h
: For string manipulation functions.ctype.h
: For character handling functions liketolower()
andisalnum()
.
- Function
isPalindrome
:- Takes a string as input and initializes two pointers:
left
at the start andright
at the end of the string. - It uses a loop to compare characters from both ends, ignoring non-alphanumeric characters and comparing them in a case-insensitive manner.
- If characters do not match, it returns
0
(not a palindrome); if all characters match, it returns1
(is a palindrome).
- Takes a string as input and initializes two pointers:
- Main Function:
- Prompts the user to enter a string.
- Uses
fgets
to read the string, allowing spaces. - Removes the newline character that
fgets
might include. - Calls
isPalindrome
to check and prints the result.
Input/Output
Input Example:
Enter a string: A man, a plan, a canal: Panama
Output Example:
'A man, a plan, a canal: Panama' is a palindrome.
Conclusion
This C program effectively checks if a given string is a palindrome by comparing characters from both ends while ignoring spaces, punctuation, and capitalization. It showcases basic string manipulation and control flow in C. The program can be easily modified to enhance functionality, such as handling more complex input or providing detailed error messages.