Codiqo

Learn C# · lesson 52 of 61 · about 8 minutes

Tracing and Fixing Recursion

Follow every call step by step, and spot recursion that never stops.

What you'll learn

  • Trace the order of recursive calls
  • Explain what the call stack is
  • Fix a missing or unreachable base case

Packing for the lair

Before the hero sets off for the dragon's lair, everything in the bag goes into the pack, and at the lair it all comes out again. A pack works like the call stack: the last thing in is the first thing out. Pack prints Packing the bread before its recursive call, on the way down, and Unpacking the bread after it, on the way back up, so the things come out in the reverse of the order they went in. In between, the base case says At the dragon's lair!.

The call stack

Every call gets its own copy of its parameters and local variables, in a stack frame. When a method calls itself, the first call waits while the new one runs.

When the base case returns, the calls finish one by one, newest first. Code after the recursive call runs on the way back out.

In and out

Dive(2);

static void Dive(int n)
{
    if (n == 0)
    {
        Console.WriteLine("bottom");
        return;
    }
    Console.WriteLine($"going down {n}");
    Dive(n - 1);
    Console.WriteLine($"coming up {n}");
}

Output

going down 2
going down 1
bottom
coming up 1
coming up 2

Each frame remembers its own thing

Pack takes the index i of the thing it's packing. When it calls itself with i + 1, its own i stays the same in its own frame, so the Unpacking line after the call prints the thing it packed, not the next one.

When it never stops

If the base case is missing, or the calls never reach it, frames pile up until the stack runs out. In C# a stack overflow ends the program at once; not even try/catch can save it. So check that every path makes the problem smaller and that the base case catches the smallest one.

Fibonacci: two calls each time

for (int i = 0; i < 8; i++) Console.Write($"{Fib(i)} ");
Console.WriteLine();

static int Fib(int n)
{
    if (n < 2) return n;
    return Fib(n - 1) + Fib(n - 2);
}

Output

0 1 1 2 3 5 8 13

Tip

Fib calls itself twice, so the number of calls doubles quickly: Fib(40) makes hundreds of millions of calls. A loop is far faster for that one.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.