In this tutorial, we will write a C program to Check if a Given String is a Palindrome using string function. Before that, you may go through the C topic below.
Palindrome Number
A number is said to be a Palindrome number if it remains the same when its digits are reversed or are the same as forward. It is also applied to the word, phrase or other sequences of symbols.
For example: If we take the example of ‘mam‘ or ‘madam‘, these are also palindrome words as we will get the same result even if we write it backward.
C Program to Check if a Given String is a Palindrome
The program uses one of the string functions that is strlen()
function that returns the length of the string. And the header string.h
is included to use this function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <stdio.h> #include <string.h> int main() { char str[30], flag = 0; int i, length; printf("Enter the string:"); gets(str); //strlen() function is used length = strlen(str); for (i = 0; i < length / 2; i++) { if (str[i] != str[length - 1 - i]) { flag = 1; break; } } if (flag == 0) printf("%s :- is a palindrome.", str); else printf("%s :- is not a palindrome.", str); return 0; } |
Output:
//First Run
Enter the String:
madam
madam :- is a palindrome.
//Second Run
Enter the String:
step on no pets
step on no pets :- is a palindrome.
//Thirsd Run
Enter the String:
how are you
how are you :- is not a palindrome.