Skip to content

Module 4 · Functions, Recursion and Storage Classes — topic 2 of 3

Recursion

A recursive function calls itself on a smaller version of the problem until it reaches a base case. Learn to design recursive functions, trace the call stack, and know when iteration is better.

Beginner 16 min read·Lesson 17 of 37 in C Programming

Learning objectives

  • Write recursive functions with correct base and recursive cases
  • Trace recursive calls using the call stack
  • Compare recursion and iteration in clarity, memory and speed

Definition

Recursion is a technique in which a function calls itself, directly or indirectly. A correct recursive function has at least one base case that returns without recursing and a recursive case that moves the input strictly closer to a base case.

Introduction

Some problems are naturally defined in terms of themselves: the factorial of n is n times the factorial of n − 1; a folder's size is its files plus the sizes of its sub-folders. Recursion lets the code mirror that definition directly.

Each call gets its own copy of parameters and local variables, stored in a stack frame. When the base case is reached, the calls return one by one, combining their results.

Why it matters

Recursion is essential for trees, graphs, divide-and-conquer algorithms (merge sort, quick sort, binary search) and backtracking — all core DSA topics.

Tracing recursion by hand is a common written-exam question, and missing base cases are a common cause of crashes.

Detailed explanation

Design in two steps: 1. Base case — the smallest input you can answer directly (e.g. 0! = 1). 2. Recursive case — express the answer using a smaller input (e.g. n! = n × (n−1)!).

Every call pushes a frame on the call stack. Deep recursion (hundreds of thousands of calls) can exhaust the stack — a *stack overflow* — which usually crashes the program. Typical default stacks are 1–8 MB.

Some recursive solutions recompute the same subproblems many times. Naive Fibonacci makes about 1.6ⁿ calls; an iterative loop or memoisation reduces that to n steps.

A call is tail recursive when the recursive call is the last action. Compilers *may* optimise tail calls into loops at higher optimisation levels, but the C standard does not require it.

CallReturns
fact(4)4 × fact(3) = 24
fact(3)3 × fact(2) = 6
fact(2)2 × fact(1) = 2
fact(1)1 × fact(0) = 1
fact(0)1 (base case)

Syntax

C
return_type solve(problem) {
if (problem is small enough) /* base case */
return direct_answer;
return combine(solve(smaller problem)); /* recursive case */
}
  • Check the base case before recursing.
  • Each recursive call must move toward the base case.
  • Return the recursive result; don't just call the function.

Code examples

Factorial

C
#include <stdio.h>
unsigned long long fact(int n) {
if (n <= 1) return 1; /* base case */
return n * fact(n - 1); /* recursive case */
}
int main(void) {
for (int n = 0; n <= 5; n++)
printf("%d! = %llu\n", n, fact(n));
printf("20! = %llu\n", fact(20));
return 0;
}
Output
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
20! = 2432902008176640000

20! is the largest factorial that fits in an unsigned 64-bit integer.

Sum of digits

C
#include <stdio.h>
int digit_sum(int n) {
if (n < 10) return n;
return n % 10 + digit_sum(n / 10);
}
int main(void) {
printf("%d\n", digit_sum(98765));
return 0;
}
Output
35

More examples

Tower of Hanoi and recursive binary search

C
#include <stdio.h>
int moves = 0;
void hanoi(int n, char from, char to, char via) {
if (n == 0) return;
hanoi(n - 1, from, via, to);
printf("Move disk %d from %c to %c\n", n, from, to);
moves++;
hanoi(n - 1, via, to, from);
}
int bsearch_rec(const int a[], int lo, int hi, int key) {
if (lo > hi) return -1;
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) return mid;
if (a[mid] < key) return bsearch_rec(a, mid + 1, hi, key);
return bsearch_rec(a, lo, mid - 1, key);
}
int main(void) {
hanoi(3, 'A', 'C', 'B');
printf("%d moves\n", moves);
int sorted[] = {3, 8, 15, 21, 42, 57, 90};
printf("42 at index %d\n", bsearch_rec(sorted, 0, 6, 42));
printf("10 at index %d\n", bsearch_rec(sorted, 0, 6, 10));
return 0;
}
Output
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
7 moves
42 at index 4
10 at index -1

Step-by-step explanation

  • To move n disks from A to C, first move n − 1 disks out of the way to B (first recursive call).
  • Then move the largest disk directly to C and count the move.
  • Finally move the n − 1 disks from B onto C (second recursive call). n disks need 2ⁿ − 1 moves: 7 for n = 3.
  • bsearch_rec halves the search range each call; lo > hi is the base case meaning “not found”.
  • lo + (hi - lo) / 2 computes the midpoint without the overflow risk of (lo + hi) / 2.

Expected output

Running “Tower of Hanoi and recursive binary search” prints exactly:

TextOutput
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
7 moves
42 at index 4
10 at index -1

Practical applications

  • File managers compute folder sizes by recursing into sub-folders.
  • Compilers parse nested expressions with recursive-descent parsers.
  • Sorting libraries use recursive quick sort and merge sort.

Best practices

  • Write and test the base case first.
  • Prefer iteration when recursion depth could be large or the loop is just as clear.
  • Use memoisation or a loop when subproblems repeat (Fibonacci).

Common mistakes

No base case

Avoid

int f(int n) {
return n * f(n - 1);
}

Prefer

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

Without a base case the recursion never stops and the stack overflows.

Ignoring the recursive result

Avoid

int sum(int n) {
if (n == 0) return 0;
sum(n - 1);
return n;
}

Prefer

int sum(int n) {
if (n == 0) return 0;
return n + sum(n - 1);
}

The result of the recursive call must be used to build the answer.

Important notes

  • Recursion depth for a balanced divide-and-conquer algorithm is about log₂ n — fine even for huge n. Linear recursion depth (one call per element) can overflow for large inputs.
  • Signed integer overflow inside a recursive computation (e.g. int factorial beyond 12!) is undefined behaviour; use wider unsigned types.

Key takeaways

  • Recursion = base case + recursive case that shrinks the problem.
  • Each call has its own stack frame; too many frames overflow the stack.
  • Naive recursion can repeat work exponentially; iterate or memoise.

Try it yourself

  1. 1
    Write a recursive function to compute xⁿ using x^(n/2) for even n (fast exponentiation).
  2. 2
    Write recursive and iterative Fibonacci functions and count how many calls the recursive one makes for n = 25.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat happens if a recursive function has no base case?
  • ModerateWhat is printed?
Practise this topic