A recursive function solves a problem by calling itself on a smaller instance until a base case returns without another call.
Mental model: each call has its own automatic locals (a stack frame). C does not require tail-call elimination. A “tail recursive” function still typically uses one frame per call. A million-deep walk of a list should be a loop.
int factorial(int n) {
if (n < 0) {
return -1; /* or abort — invalid */
}
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
n - 1, a shorter string, node->next).factorial(13) already overflows 32-bit int. Recursion does not widen the type.| Recursion | Iteration | |
|---|---|---|
| Natural fit | Trees, divide-and-conquer, backtracking | Sequences, I/O, running totals |
| State | Frames | Your variables / an explicit stack |
| Risk | Stack blow-up, exponential time | Off-by-one |
int factorial_iter(int n) {
int acc = 1;
for (int i = 2; i <= n; i++) {
acc *= i;
}
return acc;
}
/* Exponential — do not ship */
long fib(int n) {
if (n < 2) {
return n;
}
return fib(n - 1) + fib(n - 2);
}
gcd(a, b) = gcd(b, a % b), base b == 0. Depth is small.int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
Public function takes the user’s arguments. A helper carries an index so you do not copy the array.
static int contains_from(const int *a, size_t n, int x, size_t i) {
if (i == n) {
return 0;
}
if (a[i] == x) {
return 1;
}
return contains_from(a, n, x, i + 1);
}
for to look clever.static helper.~ Good luck with your revision! ~