سؤال

I can't find the problem in my code, it prints only press any key to continue nothing else. I don't seem to figure out the flow of the program because of the output shown. Help appreciated.

#include<stdio.h>
#include<stdlib.h>

int fcheck(char *name, int i, int j)
{
    if (i > j)
        return 1;

    if (name[i] != name[j])
        return 0;
    else
        fcheck(name, i++, j--);

    return 1;
}                               // close fcheck

int main()
{
    int c;

    char name[] = "mom";

    int i = 0, j = 2;

    c = fcheck(name, i, j);

    if (c == 1)
        printf("Palindrome");
    else
        printf("Not a Palindrome");

    return 0;
}                               // close main
هل كانت مفيدة؟

المحلول 2

1) Infinite loop problem

this line

fcheck(name,i++,j--);

should be

fcheck(name,++i,--j);

because

fcheck(name,i++,j--);

is equivalent to

fcheck(name,i,j);
i++;
j--;

so with this way of incrementation you will get an infinite loop because you are recalling fcheck() with the same arguments

and

fcheck(name,++i,--j);

is equivalent to

i++;
j--;
fcheck(name,i,j);

with this way you are not recalling fcheck() with the same arguments. So it should fix your infinite loop problem

2) should add return after the recursive call

As mentioned in the other answer, you should add return when you call the recursive function

return fcheck(name, ++i, --j);

نصائح أخرى

fcheck(name,i++,j--);

only changes the values of i or j after calling fcheck. This means that you get a repeating callstack for fcheck(name,0,2) which only terminates when your stack overflows.

If you want to use recursion here, you need to use pre-increment/decrement instead

return fcheck(name,++i,--j);

Note that I've also added a return here. Without this, any string whose first and last characters match will be reported a palindrome.

int fcheck(char *name, int i, int j){
    if (i > j)
        return 1;

    if (name[i] != name[j])
        return 0;

    return fcheck(name, i+1, j-1);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top