C Palindrome String
A string is a Palindrome string, if this string is same as its reversed value.
In this tutorial, we will a C Program, where we read a string from user, and check if this string is a Palindrome or not.
C Program
In the following program, we read a string into str
, we reverse it and and check if this reversed string equals str
.
We reverse the string using C For Loop, and we compare the strings using strcmp(). strcmp() returns zero if both the strings are same.
main.c
</>
Copy
#include <stdio.h>
#include <string.h>
int main() {
char str[30];
printf("Enter a string : ");
scanf("%s", str);
char reversed[30];
int len = strlen(str);
for (int i = 0; i < len; i++) {
reversed[i] = str[len - i - 1];
}
printf("Given String : %s\n", str);
printf("Reversed String : %s\n", reversed);
//check if given string equals reversed
if (strcmp(str, reversed) == 0) {
printf("Given string is a Palindrome.\n");
} else {
printf("Given string is not a Palindrome.\n");
}
}
Output
Enter a string : pup
Given String : pup
Reversed String : pup
Given string is a Palindrome.
Program ended with exit code: 0
Output
Enter a string : hello
Given String : hello
Reversed String : olleh
Given string is not a Palindrome.
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to check if given string is a Palindrome or not using C program.