Search code examples
crecursionfactorial

Factorial tail recursion returns vague number


I'm trying out a factorial tail recursive program, if I enter number 4, the factorial of it should printed out, but instead 32767 is printed out always. What's wrong with this code? and Why does it print out 32767 ?

int factTR(unsigned int n, unsigned int a)
{
    if (n == 0)
    {
        return a;
    }
    else
    {
        return factTR(n - 1, n * a);
    }

    int fact(unsigned int n);
    {
        return factTR(n, 1);
    }
}

int main(void)
{
    printf("hi\n");

    unsigned int a, n;

    printf("Enter a positive number : ");
    scanf("%u", &n);
    factTR(n, a);

    printf("The factorial of %u is %u", n, a);

    return 0;
}

Solution

  • You're passing an uninitialized value of a to factTR().

    factTR() is intended to be called from fact(), which provides the proper initial value in the recursion.

    Then in main() you should use the return value to get the result. C parameters are passed by value, so using a as an argument won't update its value.

    nt factTR(unsigned int n, unsigned int a)
    {
        if (n == 0)
        {
            return a;
        }
        else
        {
            return factTR(n - 1, n * a);
        }
    
    }
    
    int fact(unsigned int n);
    {
        return factTR(n, 1);
    }
    
    int main(void)
    {
        printf("hi\n");
    
        unsigned int a, n;
    
        printf("Enter a positive number : ");
        scanf("%u", &n);
        a = fact(n);
    
        printf("The factorial of %u is %u", n, a);
    
        return 0;
    }