Palindrome is the term used to represent the condition in which the given number or string is same as its reverse. For eg, 12321, 5445, 93439 are palindrome number, MADAM, NAYAN, NOON, MOM are the palindrome string. From these examples we can easily understand that, in order check palindrome we need to reverse the string or number first. In C language, we have built in string handling function to reverse the given string. i.e. strrev ( ). Using this function we can check palindrome directly. In addition we have to use other string function such as strcpy and strcmp to copy and compare strings. So, we have to include a header file in following C program.
#include<stdio.h>
#include<string.h>
int main()
{
char n[10],x[10];
long int i,l,j=0;
printf("Enter string");
scanf("%s",n);
strcpy(x, n);
strrev(n);
if(strcmp(x,n)==0)
{
printf("%s is palindrome", n);
}
else
{
printf("%s is not palindrome", n);
}
return 0;
}
Since, most of the latest version of C doesn't support strrev () function, In this case, to reverse the string we transfer every character of the given string from last to form a new string. let us consider, If we supply “cat” as an input then it is stored in a variable “n” as
n[0] | n[1] | n[2] | n[3] | n[4] | [n5] |
‘c’ | ‘a’ | ‘t’ | ‘\0’ |
Then, we will create new variable let use say ‘x’ which stores each character from the last (length of the string -1). This is because our character array starts from 0
x[0] | x[1] | x[2] | x[3] | x[4] | x[5] |
n[2] | n[1] | n[0] | |||
‘t’ | ‘a’ | ‘c’ | ‘\0’ |
#include<stdio.h>
#include<string.h>
int main()
{
char n[10],x[10];
long int i,l,j=0;
printf("Enter string");
scanf("%s",n);
l=strlen(n);
for(i=l-1;i>=0;i--)
{
x[j]= n[i];
j=j+1;
}
printf("Reverse is %s", x);
return 0;
}
Now, after reversing the given string, we compare the original and reversed string by using another string handling function strcmp(). This function compares two strings and return 0 if both are equal.
#include<stdio.h>
#include<string.h>
int main()
{
char n[10],x[10];
long int i,l,j=0;
printf("Enter string");
scanf("%s",n);
l=strlen(n);
for(i=l-1;i>=0;i--)
{
x[j]= n[i];
j=j+1;
}
if(strcmp(x,n)==0)
{
printf("%s is palindrome", n);
}
else
{
printf("%s is not palindrome", n);
}
return 0;
}
Click here for full C course and program examples.