Recursion in C

Our program demonstrates recursive functions in C. Here’s the full source code:

#include <stdio.h>

// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
int fact(int n) {
    if (n == 0) {
        return 1;
    }
    return n * fact(n - 1);
}

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

int main() {
    printf("%d\n", fact(7));
    printf("%d\n", fib(7));
    return 0;
}

The fact function is a classic example of recursion, calculating the factorial of a number.

In C, we don’t have closures like in some other languages. Instead, we’ve defined fib as a regular function to calculate Fibonacci numbers recursively.

To compile and run the program:

$ gcc -o recursion recursion.c
$ ./recursion
5040
13

The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).

In C, recursive functions work similarly to other languages. Each function call creates a new stack frame, which allows the function to call itself with different arguments. The base case (when n is 0 for factorial, or less than 2 for Fibonacci) prevents infinite recursion.

While recursion can be elegant for certain problems, it’s important to be aware of potential stack overflow issues with deep recursion in C. For larger numbers, iterative solutions or tail-recursion optimizations might be more appropriate.