How do recursive functions work?
Last updated
Last updated
To understand how recursion works, we need to look at the behaviour of the run time stack as we make the function calls.
Suppose we have the following program:
Lets trace what happens to it with respect to the run time stack:
Program begins, main() function is placed on stack along with local variable x.
factorial(4) is called, so we push factorial(4) onto the stack along with local variables n and rc.
n is 4, and thus the if statement in line 3 is true, thus we need to call factorial(3) to complete line 4.
Now, the n is 3 which makes the if statement true. Thus, we make a call to factorial(2).
Once again, the if statement is true, and thus, we need to call factorial(1).
Once we make this call though, our if statment is false. Thus, we return rc popping the stack
Once it is returned we can complete our calculation for rc = 2. This is returned, popping the stack
Once it is returned we can complete our calculation for rc = 6. This is returned, popping the stack
Once it is returned we can complete our calculation for rc = 24. This is returned, popping the stack