A palindrome string is a string that reads the same backward as forward. For example, "racecar" is a palindrome string because it reads the same way from left to right and from right to left. Another example is "level". Write a C program to check whether a given string is a palindrome or not.
时间: 2024-03-20 11:41:33 浏览: 14
```
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int i, j, len;
int flag = 1; // flag = 1 means the string is a palindrome, flag = 0 means the string is not a palindrome
printf("Enter a string: ");
scanf("%s", str);
len = strlen(str);
for (i = 0, j = len - 1; i < len / 2; i++, j--)
{
if (str[i] != str[j])
{
flag = 0;
break;
}
}
if (flag == 1)
{
printf("%s is a palindrome.\n", str);
}
else
{
printf("%s is not a palindrome.\n", str);
}
return 0;
}
```
Explanation:
1. Declare a character array `str` to store the input string.
2. Declare integer variables `i`, `j`, and `len` to use in the for loop.
3. Declare an integer variable `flag` to indicate whether the string is a palindrome or not.
4. Use `printf` function to prompt the user to enter a string and use `scanf` function to read the input string.
5. Use `strlen` function to calculate the length of the input string and store it in `len`.
6. Use a for loop to check if the string is a palindrome. The loop runs from the beginning of the string to the middle of the string (len/2). The variable `i` starts from the beginning of the string and `j` starts from the end of the string. At each iteration, we compare the i-th character from the beginning of the string with the j-th character from the end of the string. If they are not equal, set `flag` to 0 and break out of the loop.
7. If `flag` is still 1, output that the string is a palindrome. Otherwise, output that the string is not a palindrome.