C ยท Chapter 28 of 45

C Recursion

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs a base case that stops the recursion, or it will call itself forever.

Recursion is elegant for problems like factorials, Fibonacci numbers, and tree traversal, but each call uses stack memory, so very deep recursion can cause a stack overflow.

Syntax
int func(int n) {
  if (baseCase) return value;
  return func(smaller n);
}

Base case and recursive case

The base case is the simplest scenario that returns directly without recursing. The recursive case breaks the problem down and calls the function again with a smaller input, moving toward the base case.

Recursion vs iteration

Anything recursion can do, a loop can also do, and often with better performance since loops avoid function call overhead. Recursion is chosen when it makes the solution's logic clearer.

Example 1 (c)
#include <stdio.h>

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

int main() {
  printf("%d\n", factorial(5));
  return 0;
}
Output
120

factorial(5) calls factorial(4), and so on, until reaching the base case n <= 1.

Example 2 (c)
#include <stdio.h>

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

int main() {
  printf("%d\n", fib(6));
  return 0;
}
Output
8

fib(6) recursively sums the two preceding Fibonacci numbers until reaching base cases.

Key points

  • Every recursive function needs at least one base case.
  • Recursion breaks problems into smaller subproblems of the same type.
  • Deep recursion can cause a stack overflow.
  • Any recursive solution can usually be rewritten as an iterative loop.
๐Ÿ’ก Note: Always double-check your base case โ€” a missing or wrong base case is the most common recursion bug.

๐Ÿ“ Quick Quiz

1. What stops a recursive function from calling itself forever?

2. What resource does deep recursion consume that can run out?

3. Can every recursive function be rewritten as a loop?