Codiqo

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

Methods That Call Themselves

Solve a problem by solving a smaller copy of the same problem.

What you'll learn

  • Write a base case that stops the recursion
  • Write a recursive case that moves towards it
  • Return values from recursive calls

Resting by the fire

The blacksmith's work is done, and before the dragon the hero rests by the forge's fire. Each rest gives 20 HP, and the hero rests until they're back to full strength at 100: Resting by the fire: 47 HP, Resting by the fire: 67 HP, Resting by the fire: 87 HP, then Back to full strength: 100 HP. A loop could do it, but this unit is about another way: a method that calls itself. RestUp(47) prints its line and calls RestUp(67), and a call with 100 HP or more ends the rest.

A method inside itself

A recursive method calls itself. Each call works on a smaller piece of the problem, until the piece is so small the answer is obvious.

Every recursive method needs two parts:
- A base case that returns without calling itself
- A recursive case that calls itself on something smaller

Counting down

Countdown(3);

static void Countdown(int n)
{
    if (n == 0)
    {
        Console.WriteLine("Lift off!");
        return;
    }
    Console.WriteLine(n);
    Countdown(n - 1);
}

Output

3
2
1
Lift off!

Returning an answer

The factorial of 5 is 5 × 4 × 3 × 2 × 1, which is the same as 5 × (the factorial of 4). So Factorial(n) can return n * Factorial(n - 1), with Factorial(1) returning 1.

Factorial

Console.WriteLine(Factorial(5));
Console.WriteLine(Factorial(15));

static long Factorial(int n)
{
    if (n <= 1) return 1;
    return n * Factorial(n - 1);
}

Output

120
1307674368000

A base case that catches the top

RestUp uses if (hp >= 100) rather than if (hp == 100). Resting from 80 lands on 100 either way, but from 47 the hero goes 67, 87, 107 and never lands exactly on 100, so with == the calls would go on until the stack overflowed. >= 100 catches every number at the top, so the rest always ends. Here the problem gets smaller as the HP goes up: each call is 20 HP closer to the base case.

Tip

Each call must get closer to the base case. If it never gets there, the program crashes with a stack overflow, which C# can't catch.

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.