Search code examples
clogicpalindrome

The following code for palindrome doesn't work?is there a logical mistake?


Could someone point me to the error in this code. Iam using codingblocks IDE.

#include <stdio.h>
main()
{
    char a[100],b[100];int i,j=0; 
    scanf("%s",&a);
    for(i=strlen(a)-1,j=0;i>=0;i--)
    {
        b[j]=a[i];
        j=j+1;
    }
    b[j]='\0';
    if(a==b) # on printing i get both 'a' and 'b' as equal however this condition still remains
             # false

        printf("true"); #doesnot print?

}

Solution

  • Change this statement

    if(a==b)
    

    to

    if ( strcmp( a, b ) == 0 )
    

    Otherwise you are comparing addresses of the first elements of the arrays.

    Also you need to include header <string.h>. Function main shall have return type int. Change this statement

    scanf("%s",&a);
    

    to

    scanf( "%s", a);
    

    Take into account that there is no need to define second array that to determine whether a string is a palindrome. You could do this check "in place".