Please help me understand this simple recursion. I’m very new to programming, so I’m wondering how exactly this happens step by step.
I’m trying to learn recursion, but I’m stuck with the addition of “+”
function foo($bar) {
if ($bar == 1) return 1;
elseif ($bar == 0) return 0;
else return foo($bar - 1) + foo($bar - 2);
}
When trying to understand recursion I find it helps a lot to write down each individual case for a specific parameter and then build your understanding from there.
So let’s take the example of
foo(3)foo(3) -> we don’t hit either base case, so our function now wants to return
First we need to get foo(2)
foo(2) -> Again no base case, so we return
foo(1) = 1 and foo(0) = 0 (these are our base cases) so we see that
Now our look at foo(3) is resolved to
foo(3) -> (1 + 0) + foo(1)
foo(1) = 1, so we can finally see that
foo(3) -> (1 + 0) + 1 = 2
You have to remember that recursion is basically building a “tree” of function calls – it’s going to go as far down the tree as possible, and then come up one level and see what else it has to do to continue. I’m not sure how clear this is but hopefully it helps.