When i = 0
, f[n-i]
will be the terminating null character, which will never appear in the middle of the string.
Because of that, if the string is 2-char long or more, the condition f[i+1]==f[n-i]
will be false.
(If the string is 1-char long, f[i+1]
will be the terminating null character after the first (and only) character, so the condition will be true.)
The condition should be f[i]==f[n-i-1]
.
By the way,
- You shouldn't use
gets()
, which has unavoidable risk of buffer overrun, deprecated in C99 and removed from C11.
- You should use standard
int main(void)
in hosted environment instead of void main()
, which is illegal in C89 and implementation-defined in C99 or later, unless you have some special reason to use this non-standard signature (for example, forced to use this from your boss or teacher).
An example of full fixed code:
#include<stdio.h>
#include<string.h>
int main(void)
{
int i,n,count=0;
char f[30 + 1]; /* allocate one more element for storeing newline character */
char* lf;
printf("Enter the string. : ");
fgets(f, sizeof(f), stdin); /* change gets() to fgets() */
/* fgets() stores newline character while gets() doesn't, so remove it */
if ((lf = strchr(f, '\n')) != NULL) *lf = '\0';
n = strlen(f);
for(i=0;i<n;i++)
{
if(f[i]==f[n-i-1])
count=count+1;
}
if(count==n)
printf("\n Entered string is Palindrome");
else
printf("\n Entered string is NOT Palindrome");
}