CHAPTER 24 / 26
C Recursion
Learn how a function can call itself to solve a problem.
01 — Syntax
return condition ? value : n * function(n - 1);
02 — Example
#include <stdio.h>
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
printf("%d", factorial(5));
return 0;
}03 — Important Points
- Every recursive function needs a base case.
- Recursion should move toward that base case.
04 — Common Mistakes
- Missing the base case.
- Recursion that never reaches the base case.
05 — Real-World Use
Recursion is useful for tree traversal, divide-and-conquer and mathematical problems.
06 — Practice
Create a small program that demonstrates the main idea of C Recursion.