Teja
Teja

Reputation: 13534

Debugging Factorial Recursion

I am new to the C programming language and I am trying to learn recursion for computing the factorial of a given number. My question is the debugging printf statement is printing 2,6,24,120 if I input '5'. How does it print 4 times if the function calls are replaced with the corresponding values and computes the factorial at a time?

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

int factorial(int n);

int main()
{
        int num;
        int fact_val;
        printf("Enter the number for which you are going to compute the factorial:");
        scanf("%d",&num);

        fact_val=factorial(num);

        printf("The factorial of the given number is %d\n",fact_val);

        return 0;
}

int factorial(int n)
{
        int factorial_val;
        if(n==1)
        return 1;
        else
        {
                factorial_val=factorial(n-1)*n;
                printf("Debugger-%d\n",factorial_val);
        }
        return factorial_val;
}

Upvotes: 0

Views: 945

Answers (1)

pb2q
pb2q

Reputation: 59617

When you reach your base-case, you return immediately rather than printing.

So you see a printf for cases: 5, 4, 3, 2, and when the function is passed 1, the value isn't printed: you return instead.

Furthermore you recurse before you print, so the cases are printed in order, least-first: the first print happens only after you've recursed all the way down to 2. Hence you see: 2, 6, 24, 120. Only when you've returned from the current recursion is the intermediate value printed.

Write down the recursion to make it clearer:

5 -> recurse with 4:
    4 -> recurse with 3:
        3 -> recurse with 2:
            2 -> recurse with 1:
                1 -> base case, just return...
            printf (1 * 2) = 2;
        printf (2 * 3) = 6;
    printf (6 * 4) = 24;
printf (24 * 5) = 120;

Upvotes: 4

Related Questions