CS205

Recursion

Learn how functions can call themselves to solve problems by breaking them into smaller pieces.

What is Recursion?

Recursion is when a function calls itself to solve a problem. It's like solving a puzzle by breaking it into smaller, identical puzzles.

"To understand recursion, you must first understand recursion."

Every recursive function has two essential parts:

1. Base Case

The condition that stops the recursion. Without it, the function would call itself forever!

2. Recursive Case

The function calls itself with a smaller/simpler version of the problem, moving toward the base case.

Structure of a Recursive Function
returnType recursiveFunction(parameters) {
    // BASE CASE: When to stop
    if (baseCondition) {
        return baseValue;
    }

    // RECURSIVE CASE: Call itself with smaller problem
    return recursiveFunction(smallerProblem);
}

Key Insight

The recursive case must make progress toward the base case. If it doesn't, the recursion will never end!

Visual Analogy: Russian Nesting Dolls

Think of recursion like Russian nesting dolls (matryoshka):

Open
Open
Open
Done!
  • Each doll contains a smaller doll (recursive case)
  • The smallest doll has nothing inside (base case)
  • You must open each doll to reach the smallest one
  • Then you close them in reverse order (returning values)
How the Call Stack Works

When a recursive function calls itself, each call is added to the call stack:

Going Down (Calling)

factorial(4)
factorial(3)
factorial(2)
factorial(1) ← base case!

Coming Back Up (Returning)

returns 1
returns 2 × 1 = 2
returns 3 × 2 = 6
returns 4 × 6 = 24

Each call waits for its recursive call to return before it can complete. The stack grows until we hit the base case, then unwinds as values are returned.

When to Use Recursion

Good for Recursion

  • • Problems with recursive structure (trees, graphs)
  • • Divide and conquer algorithms
  • • When the problem naturally breaks into smaller same-type problems
  • • When code clarity matters more than performance

Consider Iteration Instead

  • • Simple loops or counting
  • • When performance is critical
  • • Very deep recursion (risk of stack overflow)
  • • When iterative solution is just as clear