Skip to the page

Programming basics · core

Recursion and tracing code

A recursive function needs a base case and must move toward it. Trace the calls on paper, down and back up.

The notes

What you must know

  • Example: fun(n) prints n, calls fun(n - 1), then prints n again. For n = 3 it prints 3 2 1 1 2 3.
  • Each call has its own frame on the stack. At the deepest point there are frames for fun(3), fun(2), fun(1), fun(0) on top of main.
  • Code before the recursive call runs on the way down. Code after it runs on the way back up.
  • Every recursion needs a base case and must move toward it. Without a base case the stack runs out: stack overflow, which often shows as a segmentation fault.
  • Recursion reads well for trees and divide-and-conquer. A loop uses constant stack, so it is safer for deep counts.
  • Factorial overflows quickly: 13! does not fit in a 32-bit int, and 21! does not fit in 64 bits.
  • To trace: write each call and its output in a table, with the frame depth.
  • A recursive call as deep as n can crash on a big test even if it passes the small samples.

The red pen

Common traps: mistake → fix

  • Mistake: It prints 3 2 1 only

    Fix: the second print runs after each call returns.

  • Mistake: The second printf never runs

    Fix: it runs as each call returns.

  • Mistake: Recursion needs no base case if n is small

    Fix: there is always a base case.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does this recursive function print for n = 3?
  2. What happens with no base case?
  3. When do you choose a loop instead of recursion?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview