o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
write a c code to print palindrome
- User
write a c code to print palindrome
- Assistant
write a c code to print palindrome
Certainly! Below is a C program that checks whether 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 case and non-alphanumeric characters).
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Function to check if a string is a palindrome
int isPalindrome(char str[]) {
int left = 0;
int right = strlen(str) - 1;
while(left < right) {
// Convert both characters to lowercase for case-insensitive comparison
char leftChar = tolower(str[left]);
char rightChar = tolower(str[right]);
// Move left index forward if current character is not alphanumeric
if(!isalnum(leftChar)) {
left++;
continue;
}
// Move right index backward if current character is not alphanumeric
if(!isalnum(rightChar)) {
right--;
continue;
}
// Compare the characters
if(leftChar != rightChar) {
return 0; // Not a palindrome
}
left++;
right--;
}
return 1; // Is a palindrome
}
int main() {
char str[100];
printf("Enter a string: ");
// Using fgets to allow spaces in the input
if(fgets(str, sizeof(str), stdin) != NULL) {
// Remove trailing newline character if present
size_t len = strlen(str);
if(len > 0 && str[len-1] == '\n') {
str[len-1] = '\0';
}
} else {
printf("Error reading input.\n");
return 1;
}
if(isPalindrome(str)) {
printf("\"%s\" is a palindrome.\n", str);
} else {
printf("\"%s\" is not a palindrome.\n", str);
}
return 0;
}
Input Handling:
fgets to read the input, allowing the user to include spaces in the string.fgets may store.Palindrome Checking (isPalindrome Function):
left starting at the beginning of the string and right starting at the end.0 indicating that the string is not a palindrome.1, indicating that the string is a palindrome.Output:
isPalindrome, the program prints whether the entered string is a palindrome.Example 1:
Enter a string: Racecar
"Racecar" is a palindrome.
Example 2:
Enter a string: Hello
"Hello" is not a palindrome.
Example 3 (ignoring non-alphanumeric characters and case):
Enter a string: A man, a plan, a canal: Panama
"A man, a plan, a canal: Panama" is a palindrome.
To compile and run the program, follow these steps:
Save the Code:
palindrome.c.Compile:
palindrome.c.gcc (GNU Compiler Collection):
gcc -o palindrome palindrome.c
palindrome.c and produces an executable named palindrome.Run:
./palindrome
palindrome.exe instead.)Interact:
tolower and isalnum checks.Feel free to modify and enhance the program according to your specific requirements!
Not yet included in a published release.