C Palindrome String Program
A palindrome is a string that reads the same forward and backward, ignoring spaces, punctuation, and capitalization. In C, you can write a program to check whether a given string is a palindrome by comparing characters from the start and end of the string, moving towards the center. Below is an explanation and implementation of a palindrome string program in C.
Implementation of Palindrome String Program
Here is a simple implementation of a palindrome check in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: Includes standard input-output functions.#include <string.h>
: Includes string manipulation functions.#include <ctype.h>
: Includes functions for character classification.
Function Definition:
int isPalindrome(char str[])
: This function checks if the input string is a palindrome.- Parameters: It takes a character array (string) as input.
Variables:
left
: Pointer starting from the beginning of the string.right
: Pointer starting from the end of the string.
While Loop:
- The loop runs as long as
left
is less thanright
. - The inner
while
loops ignore non-alphanumeric characters using theisalnum
function. - Characters at the
left
andright
indices are compared usingtolower
to ensure the comparison is case-insensitive.
- The loop runs as long as
Character Comparison:
- If the characters at the
left
andright
indices do not match, the function returns0
(indicating it is not a palindrome). - If they match, both pointers move towards the center.
- If the characters at the
Return Value:
- If the loop completes without finding any mismatches, the function returns
1
, indicating the string is a palindrome.
- If the loop completes without finding any mismatches, the function returns
Main Function:
- An array
str
is declared to hold the input string. - The user is prompted to enter a string using
fgets
to include spaces. - The
strcspn
function removes any newline character from the string. - The palindrome check function is called, and the result is displayed.
- An array
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
Conclusion
This palindrome string program in C checks for palindromes by considering only alphanumeric characters and ignoring cases. It demonstrates how to manipulate strings, use character classification functions, and implement logic using loops and conditional statements.