Reputation: 9
Please explain how the output value of:
def f(x):
if x == 0:
return 0
return x + f(x -1)
f(3)
is 6.
Upvotes: 0
Views: 47
Reputation: 11120
Let's depict how do your recursive calls look like:
f(3) = 3 + f(2)
f(2) = 2 + f(1)
f(1) = 1 + f(0)
f(0) = 0
Now, let's poll the call stack from the top to down, starting with the base case (last) call:
So, the final value returned by f(3)
is 6
.
Note, that each f(n) call is pushed on top of the stack, until recursion hits the base case n==0
, from which, calls are unwound from top to down.
Upvotes: 3