Codiqo

Learn C · lesson 49 of 60 · about 8 minutes

Functions 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

A countdown to the restart

After the bill, the server needs a restart, and the report counts down to it. The admin types how many seconds to wait, and the report prints Restart in 3..., Restart in 2..., Restart in 1..., then Restarting now. More than 10 seconds is too long a wait. A loop could count, but this unit is about another way: a function that calls itself. countdown_restart(3) prints its line and calls countdown_restart(2), and countdown_restart(0) is the restart itself.

A function inside itself

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

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

Counting down

#include <stdio.h>

void countdown(int n) {
    if (n == 0) {
        printf("Lift off!\n");
        return;
    }
    printf("%d\n", n);
    countdown(n - 1);
}

int main(void) {
    countdown(3);
    return 0;
}

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

#include <stdio.h>

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

int main(void) {
    printf("%ld\n", factorial(5));
    printf("%ld\n", factorial(10));
    return 0;
}

Output

120
3628800

A base case that catches the bottom

The countdown uses if (seconds <= 0) rather than if (seconds == 0). Counting down from 3 lands on 0 either way, but an admin who types 0 or a negative number would never land exactly on 0 with ==, and the calls would go on until the program crashed. <= 0 catches every number at the bottom, so the restart always happens.

Tip

Each call must get closer to the base case. If it never gets there, the calls fill up the stack and the program crashes with a segmentation fault.

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.