Codele / Algorithms
Recursion
A Russian doll hides a smaller doll, which hides a smaller one. A function can do the same: solve a big problem by asking itself to solve a smaller one.
- Recursion means a function uses itself to solve a smaller version of its own problem.
- The base case is the smallest version. It answers straight away, without asking again. Every recursive function needs one.
- Each call waits on a stack of calls. The newest call is on top and finishes first.
- Calls go down to the base case. Then the answers travel back up, one call at a time.
- Without a base case the calls never stop and the computer runs out of room (a stack overflow).
Loading the playable lesson…