Recursion in C
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.
Base case first
fact(0) = 1 answers without recursing — the anchor every call chain must reach.
Shrink every step
fact(n) = n * fact(n-1) moves strictly toward the base — a step that doesn't shrink loops forever.
Trust the contract
Assume the recursive call solves the smaller instance correctly — verify base plus shrinkage, not the whole unfolding.
Mind the stack
Each live call holds a frame; hundreds of thousands of depth risk overflow — iterate deep linear recursions instead.
#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;}n calls each doing O(1) work, but n live stack frames at the deepest point.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.