Theory

A function that calls itself

Since lesson 3 you know a function can call another function. What if a function calls itself?

The classic — factorial: 4! = 4 × 3 × 2 × 1 = 24. Notice the property: 4! = 4 × 3! — the big task is a smaller task of the same kind plus one step. That is exactly the shape recursion is made for.

Every recursive function has TWO parts:

  • The base case — when to STOP: 1! = 1. Without it the calls would never end.
  • The recursive case — how to SHRINK: n! = n × (n-1)!. Every call must move closer to the base case.

Trace factorial(4) on paper:

factorial(4) → waits for 4 × factorial(3)
  factorial(3) → waits for 3 × factorial(2)
    factorial(2) → waits for 2 × factorial(1)
      factorial(1) → base case! returns 1
    factorial(2) = 2 × 1 = 2
  factorial(3) = 3 × 2 = 6
factorial(4) = 4 × 6 = 24

Each call waits for the inner answer — they stack up on the call stack, and once the base case is reached the stack unwinds back. The same stack you have seen in crash messages — now you know what lives in it.

Tip. Honestly: a loop computes the same factorial more simply, with no growing stack. Recursion wins where the data is self-similar — a folder holding folders, a family tree, a game's move tree. Your book shelf is a flat list; a loop is all it needs. Hence the rule: we taste, then go back to loops.