Skip to content

9618 · 19.2

Recursion

Recursion is a programming technique where a function solves a problem by calling itself with a slightly smaller version of the same problem. This process repeats until it reaches a simple 'base case' that can be solved directly.

Need to know

What you need to know

  • **Base Case:** This is the condition that stops the recursion. It represents the simplest version of the problem that can be solved directly without making another recursive call. Every chain of recursive calls must eventually reach a base case.
  • **Recursive Step:** This is where the magic happens. The function calls itself, but with arguments that are modified to bring the problem closer to the base case. For example, if you're working with a number `n`, the recursive call might be for `n-1`.

Explanation

The Russian Doll of Code

  1. Define the Base Case: Identify the simplest version of the problem that can be solved directly, without another function call. This is your exit condition.
  2. Define the Recursive Step: Formulate how to solve a larger problem by breaking it down into a smaller, similar sub-problem and calling the same function on it.
  3. Write the Function: Combine the base case and recursive step. Ensure the recursive call's arguments move it closer to the base case.
  4. Trace the Execution: Follow the call stack as the function calls itself, reaches the base case, and then 'unwinds', returning values back up the chain of calls.