Learn C
#include "functions/recursion.h"

Recursion in C

#concept

Recursion solves a problem with a function calling itself on smaller inputs: a base case answering directly, plus a recursive step shrinking toward it. Factorial, directory walks, and divide-and-conquer algorithms read almost as their definitions when written this way.

Every call consumes stack space for its frame, so depth is bounded and the base case is load-bearing — miss it and the program recurses until stack overflow. C compilers optimize tail calls in simple cases, but never rely on it; prefer iteration for deep linear problems.

#how it works
1

Base case first

fact(0) = 1 answers without recursing — the anchor every call chain must reach.

2

Shrink every step

fact(n) = n * fact(n-1) moves strictly toward the base — a step that doesn't shrink loops forever.

3

Trust the contract

Assume the recursive call solves the smaller instance correctly — verify base plus shrinkage, not the whole unfolding.

4

Mind the stack

Each live call holds a frame; hundreds of thousands of depth risk overflow — iterate deep linear recursions instead.

#example
#include <stdio.h>
 
int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
 
int main(void) {
printf("%d\n", fact(5));
return 0;
}
Output
120
1fact(5) misses the base case, returning 5 * fact(4) and stacking frames down to fact(1).
2fact(1) hits n <= 1 and returns 1 with no further calls — the unwind begins.
3Results multiply back up to 120, which prints.
#complexity
time O(n)
space O(n)

n calls each doing O(1) work, but n live stack frames at the deepest point.

#use cases
Tree and directory traversals where the data is itself recursive
Divide-and-conquer (mergesort, quicksort, binary search)
Backtracking searches that explore then undo each choice
Rewriting as iteration when depth threatens the stack

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.