is_palindrome
Here's an example of a C program that checks if a given string is a palindrome:
#include <stdio.h>
#include <string.h>
int is_palindrome(char *str) {
int length = strlen(str);
int i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
if (str[i] != str[j]) {
return 0;
}
}
return 1;
}
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove the trailing newline character from the input
str[strcspn(str, "\n")] = '\0';
if (is_palindrome(str)) {
printf("%s is a palindrome.\n", str);
} else {
printf("%s is not a palindrome.\n", str);
}
return 0;
}
This program defines a function is_palindrome
that takes a string as input and returns 1 if the string is a palindrome, and 0 otherwise. It uses a two-pointer approach to compare characters from both ends of the string, checking if they are equal. If at any point the characters are not equal, the function returns 0. Otherwise, it returns 1.
In the main
function, the user is prompted to enter a string. The string is read using fgets
and stored in the str
array. The newline character at the end of the input is removed using strcspn
function. Then, the is_palindrome
function is called to check if the entered string is a palindrome, and the result is printed accordingly.
Please note that this program assumes that the input string is null-terminated and has a maximum length of 100 characters. It also doesn't consider special characters or white spaces when checking for palindromes.