Source Code - 1 year ago 74
C Question

# Understanding recursion function call

Where will the value of

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

``````#include<stdio.h>

int factorial(int n)
{
if(n<=1)
return 1;
else
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
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download