Lesson 11 of 31

Recursion

Recursion

A recursive function is one that calls itself. Every recursive function needs a base case to stop the recursion.

Factorial

The classic example:

int factorial(int n) {
    if (n <= 1) return 1;       // base case
    return n * factorial(n - 1); // recursive case
}

How factorial(4) evaluates:

factorial(4) = 4 * factorial(3)
             = 4 * 3 * factorial(2)
             = 4 * 3 * 2 * factorial(1)
             = 4 * 3 * 2 * 1
             = 24

Q snapping his fingers and sending you into a nested reality within a reality within a reality. That's recursion -- just make sure you have a base case to escape.

Fibonacci

Another classic recursive function:

int fib(int n) {
    if (n <= 0) return 0;
    if (n == 1) return 1;
    return fib(n - 1) + fib(n - 2);
}

Assembly View

Check the Assembly tab after running to see how recursive calls translate to BL (branch with link) instructions and stack frame setup with STP/LDP.

Your Task

Write a function int factorial(int n) that computes the factorial of n. Print factorial(0), factorial(1), factorial(5), and factorial(10), each on a separate line.

TCC compiler loading...
Loading...
Click "Run" to execute your code.