public int mystery(int b)
{
if (b == 0) // checks if 0 == 0, which is true
return 0; // stops and returns 0
if (b % 2 == 0)
return mystery(b - 1) + 3; // call 1
else
return mystery(b - 1) + 2; // call 2
}
Call stack
m(0) returns 0
m(1)2
m(2)1
m(3)2
m(4)1
m(5)2
Explanation
m(0)
stops and returns 0
. returns
is added to the call stack next to m(0)
to indicate that the method call has returned (ended). In this case, m(0)
returns a value, so 0
is added after returns
.
In a real call stack, m(0)
would be removed. m(0)
is left on this stack since it is difficult to remove on paper and the return value is needed for future reference.