Search code examples
crecursionpalindrome

Code doesn't output correctly


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

Solution

  • 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);