Thuta Learning
IntermediateProgrammingbeginner

Recursion

Relax. We'll talk through this in plain words — no textbook voice.

Recursion is when a function calls itself. It's handy whenever you can break a problem down into smaller versions of the same problem — think factorials, tree traversal, or walking through directories.

c
#include <stdio.h>

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

int main() {
  printf("%d", sum(5));
  return 0;
}

sum(5) becomes 5 + sum(4), and it keeps calling itself from there. n == 0 is when it hits the base case and the recursion stops.

You should see
15

Info

Without a base case, recursion never stops calling itself — and that can blow the stack (stack overflow).

Easy traps

  • Having a base case isn't enough if the recursive call never actually moves toward it — that still causes infinite recursion. For example, if sum(n) just keeps calling itself with the same n.