- Define two 80-character strings called str and rev(assuming your string will not exceed 79 characters). Your string can be of any length, but remember that the last position in the string is fixed for the null character \0:
char str[80],rev[80];
- Enter characters that will be assigned to the str string:
printf("Enter a string: ");
scanf("%s",str);
- Compute the length of the string using the strlen function and assign this to the n variable:
n=strlen(str);
- Execute a for loop in reverse order to access the characters in the str string in reverse order, and then assign them to the rev string:
for(i=n-1;i >=0; i--)
{
rev[x]=str[i];
x++;
}
rev[x]='\0';
- Compare the two strings, str and rev, using strcmp:
if(strcmp(str,rev)==0)
- If str and rev are the same, then the string is a palindrome.
In C, the functionality of specific built-in functions is specified in the respective libraries, also known as header files. So, while writing C programs, whenever built-in functions are used, we need to use their respective header files in the program at the top. The header files usually have the extension .h. In the following program, I am using a built-in function called strlen, which finds out the length of a string. Therefore, I need to use its library, string.h, in the program.
The palindrome.c program for finding out whether the specified string is a palindrome is as follows:
#include<stdio.h>
#include<string.h>
void main()
{
char str[80],rev[80];
int n,i,x;
printf("Enter a string: ");
scanf("%s",str);
n=strlen(str);
x=0;
for(i=n-1;i >=0; i--)
{
rev[x]=str[i];
x++;
}
rev[x]='\0';
if(strcmp(str,rev)==0)
printf("The %s is palindrome",str);
else
printf("The %s is not palindrome",str);
}
Now, let's go behind the scenes to understand the code better.