Shail
Shail

Reputation: 901

Test for Palindrome using a recursive function in C

I tried to write the program for testing a string if it's a palindrome or not, but I always get the output as it's not one. What's wrong with my code?

#include <stdio.h>
#include <string.h>

int is_palindrome(int start, int end, char *str)
{
    if (str[start] != str[end])
        return 0;
    else if (start == end)
        return 1;
    else
        return is_palindrome(++start, --end, str);

    return 0;

}
int main()
{
    char str[20];
    int length,start=0,end=length-1;
    int result;
    printf("Enter the String.\n");
    fgets( str, sizeof( str ), stdin );
    length = strlen(str);

    if(is_palindrome(start,end,str))
        printf("It's a palindrome!\n");
    else
        printf("It's not a palindrome! \n");
    return 0;
}

Upvotes: 1

Views: 25647

Answers (4)

Kartik Thakral
Kartik Thakral

Reputation: 1

On the line with if(start==end) there is logical error.

This is caused by the last recursive call, where the value of last and end will always be same i.e they both will be at the center of the array. Consequently the function is_palindrome() will always return 1 and the output will always be It's a palindrome!

Upvotes: 0

Samiul Alam Shamim
Samiul Alam Shamim

Reputation: 21

In this is_palindrome() function you must need to check it otherwise it will not work for the even number character of palindrome word

if(start>end)
    return 1;

Upvotes: 0

perreal
perreal

Reputation: 98058

You have two main issues,

1) You are initializing end using length without first initializing length:

length = strlen(str);
/* initialize end here */

2) You are not considering the newline you get at the end of the string from fgets:

end = length - 2; /* don't include the newline */

Upvotes: 1

djechlin
djechlin

Reputation: 60788

What happens when ++start and --end pass each other?

else if (start == end)

Should be >=.

Upvotes: 3

Related Questions