CoursesAIMathCodePhysicsAbout and FAQ

TwiddleLab / Code / Recursion: Functions That Call Themselves

A Function That Calls Itself

Lesson 1 of 11 · 5 min · Free, no account needed

What you will learn

  • Recursion is a function that calls itself on a smaller version of the job.
  • Each recursive call puts a new card on the call stack, with its own n.
  • A print before the call runs on the way down; a print after the call runs on the way back up.
  • A stopping line, like if n == 0, is what ends the chain.

Start the lesson

How the lesson goes

  1. A picture inside a picture inside a picture. Can code do that?

    Open the dolls. Each one hides the same job, only smaller.

  2. This function calls itself. How many countdown cards at the deepest point?

    countdown(3) calls countdown(2), which calls... Each call gets its own card on the stack, like in CS-2.9.

  3. Watch the stack grow and shrink.

    Step through it. Notice when each number is printed.

    countdown(3) can't finish until countdown(2) finishes, which waits for countdown(1), which waits for countdown(0). So all four cards are on the stack at once, then they come off in reverse order.

  4. Recursion.

    A function that calls itself is recursive. The call inside it is a recursive call.

    Every call gets a fresh card on the call stack, with its own n. The card stays until that call finishes.

    The trick is that each call works on a smaller job, and one line stops the chain: here, if n == 0.

  5. Next move: predict the stack.

    Before each move, tap what happens next. Two rounds. Build a streak.

  6. Build your own countdown.

    Put the lines in order so countdown(3) prints 3, 2, 1, Liftoff.

    The check for 0 must come before the call, or the chain never stops. Printing before the call makes the numbers come out on the way down: 3, 2, 1.

  7. Launch your countdown from 5. How many cards at the deepest point?

    Place the marker, then Check. If you're right, it launches.

    Each call waits for the smaller one, so at the moment countdown(0) runs, the cards for 5, 4, 3, 2, 1 and 0 are all on the stack: 6.

Next lesson: The Base Case · Part of the course: Recursion: Functions That Call Themselves

Lessons are interactive and need JavaScript. Turn it on to play them.

Loading TwiddleLab