Recursion

Understand recursive thinking through visual call stacks, step-by-step tracing, and interactive examples.

Category: Algorithms · v1.0.0
Step 1 of 6

Step 1: What is Recursion?

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs two parts:

  • Base case — the condition that stops the recursion (prevents infinite loops)
  • Recursive case — where the function calls itself with a simpler input

Think of Russian nesting dolls: you open a doll and find a smaller one inside. You keep opening until you reach the tiniest doll (the base case). Then you close them back up, one by one (the return values flowing back).

Or imagine standing between two mirrors — you see a reflection inside a reflection inside a reflection. Each reflection is a recursive call, and the mirrors' edges are the base case.

Here is a simple countdown example:

function countdown(n):
    if n <= 0:           // Base case
        print("Done!")
        return
    print(n)
    countdown(n - 1)    // Recursive case

Calling countdown(3) prints: 3, 2, 1, Done!

Try it: Countdown from

About This Lab

Recursion is a fundamental programming concept where a function calls itself. In this lab, you'll visualize how the call stack grows and shrinks, trace through classic recursive algorithms step by step, understand base cases and recursive cases, and build intuition for when recursion is the right tool.

How It Works

  1. Read each step's explanation of recursion concepts
  2. Step through recursive calls visually
  3. Experiment with different inputs
  4. Watch the call stack animate
  5. Complete the quiz to test your understanding