Recursion can be one of the hardest topics to wrap your head around. That's why in this guide, we are breaking it down for total beginners.
Imagine receiving a gift box. When you open it, instead of finding a gift, you find two smaller boxes inside. When you open the two smaller boxes, one has the gift, and the other has another smaller box inside.
In recursion, we encounter two types of boxes:
This translates to two key components of recursion:
Boxes that contain values directly. These are our stopping points.
Boxes that contain more boxes. These require further "unwrapping".
To calculate each fibonacci number, we need the previous two fibonacci numbers (like we needed to open the boxes before we got to the gift).
We can represent this with the below formula:
F(n) = F(n-1) + F(n-2)
F(1) = 1 and F(0) = 0 are our base cases. Without these, we can't do any calculations as there would be no stopping point (the gift would never be found).
In CS terms, this would lead to a stack overflow, because recursion uses the stack memory!
F(n) = F(n-1) + F(n-2)
This is the part where the function calls itself. Every subproblem is treated as its own problem. The recursive case persists until we hit the base case.
E.g. To calculate F(5), we need F(4) + F(3), but to calculate F(4), we need to calculate F(3) + F(2). This goes on until we hit the base cases, after which the answers for the subproblems are added up to give us the final answer of F(5), which is 5.