0

C program to check palindrome.

#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int len,flag,i,j;
clrscr();
printf(“Enter a string:”);
scanf(“%s”,str);
len=strlen(str);
for(i=0,j=len;i<=len,j>=0;i++,j–)
{
if(str[i]==str[j])
flag=1;
else
{
flag=0;

break;

}
}
if(flag==1)
printf(“PALINDROME!!”);
else
printf(“NOT A PALINDROME!!”);
getch();
}

So lets have an explanation of the code.

first of all what is palindrome palindrome is a string that remain same when reversed. so here in the program we are taking an input string. and also calculated length of string by strlen() function.

lets say the user enter a word “naman” now the main task starts from for loop where there is two variables i and j incrementing and decrementing respectively. first look at i it will increment till the length i.e. string ends and at the same time j is starting from string end and decrementing till 0. these two are acting as the index of the str string. so you can see that at the start of the loop value of str [i] = n and the str[j] have the last value which is also n in this case. after that if condition checks whether the str[i] and str[j] are equal or not if they are equal the flags turns 1. the value of flag can be changed till the loop runs.

so in next iteration the value of i and j incremented and decremented respectively and then the values at their respective index is checked. If it is equal then the loop do another iteration and if not then flags turns 0 and loop breaks out.

we will then print whether it is palindrome or not by checking the value of flag.

ks007

Leave a Reply

Your email address will not be published. Required fields are marked *