Palindrome Checker in C

 

 

Palindrome Checker in C

This program checks if a given string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).

Code


#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX_LENGTH 100

int isPalindrome(char str[]);

int main() {
    char str[MAX_LENGTH];
    printf("Enter a string: ");
    fgets(str, MAX_LENGTH, stdin);

    // Remove the newline character from the string
    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;
}

int isPalindrome(char str[]) {
    int left = 0;
    int right = strlen(str) - 1;

    while (left < right) {
        // Ignore non-alphanumeric characters
        while (left < right && !isalnum((unsigned char)str[left])) {
            left++;
        }
        while (left < right && !isalnum((unsigned char)str[right])) {
            right--;
        }

        // Compare characters case-insensitively
        if (tolower((unsigned char)str[left]) != tolower((unsigned char)str[right])) {
            return 0;  // Not a palindrome
        }

        left++;
        right--;
    }

    return 1;  // Is a palindrome
}
    

Explanation

The program includes the following steps:

  1. Include necessary header files: <stdio.h> for input/output functions, <string.h> for string manipulation functions, and <ctype.h> for character handling functions.
  2. Define a constant MAX_LENGTH to limit the length of the input string.
  3. Declare the isPalindrome function that checks if a given string is a palindrome.
  4. In the main function:
    • Declare a character array str to hold the input string.
    • Use fgets to read the input string from the user.
    • Remove the newline character from the input string.
    • Call the isPalindrome function to check if the input string is a palindrome.
    • Print the result.
  5. In the isPalindrome function:
    • Initialize two pointers, left and right, to the beginning and end of the string, respectively.
    • Use a while loop to compare characters from both ends of the string, ignoring non-alphanumeric characters and considering characters case-insensitively.
    • If any mismatch is found, return 0 (not a palindrome).
    • If the loop completes without finding a mismatch, return 1 (is a palindrome).

 

Leave a Reply

Your email address will not be published. Required fields are marked *