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;
}
When you reach your base-case, you
returnimmediately rather than printing.So you see a
printffor cases: 5, 4, 3, 2, and when the function is passed 1, the value isn’t printed: youreturninstead.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: