Lesson 13 / 36

Recursion

A function that calls itself to solve smaller sub-problems.

Russian dolls

Recursion is like opening a matryoshka doll: each doll contains a smaller version of itself, until you hit the smallest one that doesn't open further — the base case.

Factorial

Every recursive function needs a base case (stops recursion) and a recursive case (calls itself with a smaller input).

int factorial(int n) {
    if (n <= 1) return 1;        // base case
    return n * factorial(n - 1); // recursive case
}

// factorial(4) -> 4*3*2*1 = 24

Output:

24

Watch the stack

Each call adds a frame to the call stack. No base case (or a wrong one) causes infinite recursion and a stack overflow crash.