Before going in to the program you should know what is a palindrome first.
A palindrome is a word, phrase or a number which reads the same backward as forward. For example,
1. madam
2. civic
3. Madam, I’m Adam
4. A man, a plan, a canal: Panama.
5. No lemon, no melon.
the above phrases can be read same from forward and backward as well.
So basically we have to get the input from the user and reverse it and then compare if both are equal. If it equals then it is a Palindrome.
Let’s write the C program to check if a string is Palindrome or not (Not only strings you can check numbers as well):
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#include <stdio.h> #include <string.h> int main() { char inpstr[100], revstr[100], stripstr[100]; int i, j = 0; //print about the program printf("Palindrome Program in C\n"); printf("Enter a string: "); //get the input string from user gets(inpstr); //remove spaces & special characters for(i=0; i < strlen(inpstr); i++) { if (isalnum(inpstr[i])) { stripstr[j] = inpstr[i]; j++; } } stripstr[j] = '\0'; //reset i to 0 i = 0; //convert all characters to lowercase while( stripstr[i] ) { //store back the lower letter to mystr stripstr[i] = tolower(stripstr[i]); i++; } //copy stripstr to revstr strcpy(revstr, stripstr); //now reverse the revstr strrev(revstr); //compare if both the string are equal //if equal it is palindrome or it is not simple isn't :) if( strcmp(stripstr,revstr) == 0){ printf("It is Palindrome"); }else{ printf("Not a Palindrome"); } return 0; } |
Read the comments in the above script to understand each and every line.
You could find lot of examples online for this palindrome program. But here in this code, I am not only reversing the string but also removing special characters, spaces and converting Uppercase to Lowercase. So even if you give the input with spaces and special characters still you can able to check whether the entered string is a Palindrome or not.
Example Output:
1 2 3 |
Palindrome Program in C Enter a string: A man, a plan, a canal: Panama. It is Palindrome |
Enjoy the day!