Course contentsShow
← C
Lesson 356 of 1,2195. FunctionsFree lesson

Tracing a simple recursive call

Tracing a simple recursive call

What you'll learn: How a recursive function pauses itself to create a chain of pending tasks that eventually resolve in reverse order.

The Russian Nesting Doll analogy

Imagine you have a set of Russian nesting dolls. You want to find a tiny gold coin hidden inside the smallest, innermost doll. To do this, you perform a repetitive action: open the current doll and look inside. If there is another doll, you repeat the process.

Crucially, you don't "finish" opening the first doll until you’ve dealt with all the smaller dolls inside it. You are essentially putting the first doll's completion on hold while you dive deeper. This is exactly how the computer handles recursion.

How the computer "pauses"

In C, when a function calls itself, it doesn't restart or loop. Instead, the computer takes a snapshot of the current function's state (its variables and where it left off) and places it on a "stack." It then starts a brand new version of that same function.

Think of it like a stack of plates. You can't wash the bottom plate until you’ve cleared all the plates stacked on top of it.

Tracing the code

Let’s look at a function that counts down from a number.

#include <stdio.h>

void count(int n) {
    if (n <= 0) {
        printf("Blastoff!\n");
        return; // The "Base Case" - stops the recursion
    }
    
    printf("%d... ", n);
    count(n - 1); // The "Recursive Call" - pauses here
    printf("(Done with %d) ", n);
}

int main() {
    count(3);
    return 0;
}

If we call count(3), here is the trace:

  1. Level 1: n is 3. Prints "3...". It calls count(2) and waits.
  2. Level 2: n is 2. Prints "2...". It calls count(1) and waits.
  3. Level 3: n is 1. Prints "1...". It calls count(0) and waits.
  4. Level 4: n is 0. This hits the Base Case. It prints "Blastoff!" and returns.

Now, the "stack" starts to clear. The computer goes back to Level 3 to finish the last line of code, printing "(Done with 1)". Then it returns to Level 2 to print "(Done with 2)", and finally back to Level 1 to print "(Done with 3)".

Recursion is a two-way journey: you go deep into the calls until you hit a limit, then you work your way back out to finish the paused work.

Key takeaway

A recursive call acts like a "pause" button; the computer saves the current function's progress and only resumes it once the new inner call has completely finished.