typestar

Recursion in C

A base case and a smaller problem, on the stack rather than in a loop.

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

int sum_digits(int n) {
    if (n < 10) {
        return n;
    }
    return n % 10 + sum_digits(n / 10);
}

int ackermann_lite(int m, int n) {
    if (m == 0) {
        return n + 1;
    }
    return ackermann_lite(m - 1, 1);
}

How it works

  1. The base case is what stops the recursion.
  2. Each call gets its own copy of the locals.
  3. Deep recursion costs stack, so C often prefers the loop.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
269
Tokens
96
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 64 seconds.

Type this snippet

Step 6 of 7 in Functions, step 20 of 35 in Language basics.

← Previous Next →

Recursion in other languages