Check Palindrome or Not in C
This program is a C program that checks if a given string is a palindrome or not.
- The header file "stdio.h" is included, which contains the standard input/output library functions.
- The "main()" function is defined as the starting point of the program.
- Two integer variables "i", "n", and "s" are declared. "n" is used to store the length of the string and "s" is used to store the number of matching characters in the original and reversed string.
- Two character arrays "a" and "b" with 100 elements each are declared to store the input string and its reverse.
- The "printf()" function is used to print the prompt "Enter the string:".
- The "gets()" function is used to get the string input from the user.
- The first "for" loop is used to find the length of the string by incrementing the value of "n" until the null character ('\0') is reached.
- The second "for" loop is used to reverse the string by copying each character of the original string to the corresponding position in the reverse string, starting from the end.
- The third "for" loop is used to compare each character of the original and reversed string. If a matching character is found, the value of "s" is incremented.
- An "if-else" statement is used to check if the value of "s" is equal to the length of the string. If it is, the string is a palindrome and the "printf()" function is used to print "This is a palindrome:%s" along with the original string. If not, the string is not a palindrome and the "printf()" function is used to print "This is not a palindrome:%s" along with the original string.
- The "return 0;" statement is used to indicate that the program executed successfully.
Source Code
#include<stdio.h>
int main()
{
int i,n=0,s=0;
char a[100],b[100];
printf("\nEnter the string:");
gets(a);
for(i=0;a[i]!='\0';i++)
{
n++;
}
for(i=0;i<n;i++)
{
b[i]=a[n-i-1];
}
for(i=0;i<n;i++)
{
if(b[i]==a[i])
{
s++;
}
}
if(s==n)
{
printf("\nThis is a palindrome:%s",a);
}
else
{
printf("\nThis is not a palindrome:%s",a);
}
return 0;
}
To download raw file
Click Here
Output
Enter the string: madam
This is a palindrome