Write a C program to check whether a string is a palindrome
Description: Take a word as input. Print if it is a palindrome, like “madam” or “level”.
Hint:
- Compare the first character with the last, the second with the second last, and so on.
C program to check a palindrome string
#include <stdio.h>
#include <string.h>
int main(void) {
char s[50];
int isPalindrome = 1;
printf("Enter a word: ");
scanf("%49s", s);
int n = strlen(s);
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - 1 - i]) {
isPalindrome = 0;
break;
}
}
if (isPalindrome) {
printf("%s is a palindrome\n", s);
} else {
printf("%s is not a palindrome\n", s);
}
return 0;
}
Output:
Output of the above program is
Enter a word: level
level is a palindrome
How it works
- We only need to check half of the string (
n / 2pairs). - One mismatch is enough to say it is not a palindrome, so we stop with
break.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |