Each recursive call gets its own stack frame with its own parameters and local variables. When a base case returns, calls unwind in reverse order. Tracing that stack is the fastest way to understand recursion.
Some recursive functions repeat the same subproblems. Fibonacci is the classic example. Memoization stores answers so the function does not recompute the same value again and again.
Backtracking uses recursion to choose, explore, and undo. It appears in combinations, permutations, maze solving, and constraint problems. The undo step keeps the next branch clean.
A recursive C function needs two proofs: a base case handles the smallest valid input, and every recursive branch moves strictly toward it. Trace a call by writing each argument and pending operation as a stack frame. If the same argument can reappear before a result returns, termination is not established.
Depth is also a resource boundary. Tail position does not guarantee optimization in portable C, so an input-sized call chain can exhaust the process stack. Use iteration or an explicit stack when the supported input can create deep or cyclic traversal.
#include <stdio.h>
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("%d\n", factorial(5));
}
#include <stdio.h>
int sum(int values[], int n) {
if (n == 0) {
return 0;
}
return values[n - 1] + sum(values, n - 1);
}
int main() {
int values[] = {4, 7, 2};
printf("%d\n", sum(values, 3));
}
#include <stdio.h>
int fib(int n, int memo[]) {
if (n <= 1) return n;
if (memo[n] != -1) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
int main() {
int memo[10];
for (int i = 0; i < 10; i++) memo[i] = -1;
printf("%d\n", fib(8, memo));
}
#include <stdio.h>
void countdown(int n) {
if (n == 0) {
printf("Go!\n");
return;
}
printf("%d\n", n);
countdown(n - 1);
}
int main() {
countdown(3);
}
Every recursive call consumes stack space for return state and local variables. Input-dependent depth can overflow the limited thread stack even when the algorithm is logically correct. Estimate the maximum depth, avoid large local arrays in recursive functions, and use an iterative stack when untrusted or very deep input is possible.
A base case is useless if some branch never approaches it.
Practice, interview questions, and compiler links for C Language.
Finish the concept here, then reinforce it with hands-on coding, interview prep, or a tool that matches the topic.
Explore 500+ free tutorials across 20+ languages and frameworks.
Fresh tutorials, interview guides, and coding practice in your inbox.