Source Code Source Code - 6 months ago 32
C Question

Understanding recursion function call

Where will the value of

be stored after first call to factorial()?
then return
is sent, why doesn't
becomes equal to
in main function?


int factorial(int n)
return 1;
return n*factorial(n-1);

int main()

int res =factorial(3);
printf("%d",res) ;


The run-time stack will have four functions in total: main(), factorial(3), factorial(2), and factorial(1). Each of these gets its own variable space. There are three instances of the variable n, one for each call to factorial.

When factorial(1) returns 1, that value isn't returned to main(), because main() is not what called it: factorial(2) called it. That instance performs the operation 2*1 and returns 2. The caller of that instance is factorial(3), which receives the 2, performs the operation 3*2, and returns a value of 6 to its caller, main().

Does that help clear it up? If not, I have two suggestions:

(1) Search this topic on StackOverflow and the internet in general; there are plenty of detailed walk-through examples of factorial.

(2) Insert print statements to trace the flow of data and execution. Within factorial, separate the computation and the return, so you can put a print in between:

catch = factorial(n-1)
result = n * catch
print n, catch, result
return result