Recursion in C Tutorial: Base Cases, Call Stacks, and 4 Runnable Examples
Learn a repeatable way to trace recursive C functions through four complete programs: digit printing, factorial, array sum, and Euclid's GCD.
KnowledgeGate Team
Exam prep & CS education

Recursive code is often short, but it feels mysterious when several unfinished calls are waiting on the call stack. A reliable method is to identify the base case, prove that every call moves towards it, trace calls downward, then compute returns upward. Each active call keeps its own frame until the base case starts the unwind.
Use Recursion in C: Stack Frames, a Hand-Tracing Method and Solved GATE Questions for exam-style traces and past-paper problems. Runnable programs answer a different need: implementing digit printing, factorial, array summation, and GCD, then checking each output, cost, and failure mode.
Recursion in C: the function, base case, and smaller subproblem
Direct recursion means that a function calls itself. With indirect recursion, one function calls another that eventually calls the first. A terminating recursive solution also needs a base case and a progress measure that moves every call towards it.
The complete model has five parts:
A base case returns without another self-call.
A recursive case reduces the problem and calls the function again.
A progress measure shows that calls must approach the base case.
A call frame stores one call's parameters, local variables, and return location.
Unwinding begins when the base case returns and suspended calls finish in reverse order.
#include <stdio.h>
void printDigits(unsigned int n) {
if (n < 10) {
printf("%u ", n);
return;
}
printDigits(n / 10);
printf("%u ", n % 10);
}
int main(void) {
printDigits(407);
return 0;
}Output: 4 0 7
Here, n < 10 is the base case, n / 10 is the progress step, and printDigits(n / 10) is the recursive case. Each call owns a separate n, so the active frames hold 407, 40, and 4. The base call prints the leading digit 4, then each suspended frame prints its own n % 10 as the calls unwind, which is why the digits appear left to right. Revise functions, parameters, and control flow with the C Language Course: Concepts, MCQs & Coding if needed.
Recursion in C call-stack tracing: factorial of 4

#include <stdio.h>
unsigned long long factorial(unsigned int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
printf("%llu\n", factorial(4));
return 0;
}Output: 24
The calls descend as factorial(4) -> factorial(3) -> factorial(2) -> factorial(1). The condition n <= 1 makes both 0! and 1! evaluate to 1.
Returns then unwind without skipping any arithmetic:
factorial(1) = 1factorial(2) = 2 * 1 = 2factorial(3) = 3 * 2 = 6factorial(4) = 4 * 6 = 24
Recursion in C with arrays: sum four signed values
For a prefix of length n, sum the shorter prefix, then add its final element.
#include <stddef.h>
#include <stdio.h>
int sum(const int a[], size_t n) {
if (n == 0) {
return 0;
}
return sum(a, n - 1) + a[n - 1];
}
int main(void) {
const int values[] = {4, -2, 7, 1};
printf("%d\n", sum(values, 4));
return 0;
}Output: 10
Calls descend as S(4) -> S(3) -> S(2) -> S(1) -> S(0). Unwind with the actual values:
Return | Calculation | Subtotal |
|---|---|---|
| base case | 0 |
|
| 4 |
|
| 2 |
|
| 9 |
|
| 10 |
The parameter n is both the shrinking problem size and the safe index boundary. When n > 0, the last valid element in that prefix is a[n - 1].

Recursion in C with Euclid's algorithm: GCD of 48 and 18
Euclid's algorithm replaces a positive pair with its divisor and remainder.
#include <stdio.h>
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main(void) {
printf("%d\n", gcd(48, 18));
return 0;
}Output: 6
gcd(48, 18):48 % 18 = 12, so callgcd(18, 12).gcd(18, 12):18 % 12 = 6, so callgcd(12, 6).gcd(12, 6):12 % 6 = 0, so callgcd(6, 0).gcd(6, 0)returns6.
For positive inputs, b is the progress measure because the new remainder is smaller than the previous positive divisor. Factorial multiplies while calls unwind. This gcd function has no pending arithmetic after its recursive call. Some compilers may optimise such calls, but C does not guarantee tail-call optimisation.
Recursion in C: time cost, stack space, and iteration
Problem | Recursive time | Recursive auxiliary space | Loop time | Loop auxiliary space |
|---|---|---|---|---|
|
|
|
|
|
Sum |
|
|
|
|
Euclid's GCD |
|
|
|
|
The call stack is last in, first out, so the most recent frame returns first. Use Time Complexity & Asymptotic Notation: Big-O to interpret the growth rates.
Prefer recursion when a problem is naturally self-similar and its expected depth is controlled. Prefer iteration for a simple linear scan or when the input depth may be large. Ordinary C provides no portable promise of unlimited recursion depth.
Recursion in C errors: why they fail and how to fix them
Missing or unreachable base case: testing
n == 1infactorialmeans a call withnequal to0never matches, and becausenis unsigned,n - 1wraps to a very large value, so the recursion continues until the call stack is exhausted. Testn <= 1, so both 0 and 1 terminate directly.No progress: calling
sum(a, n)instead ofsum(a, n - 1)gives the next call the same prefix length, so the base casen == 0is never reached. Recurse withsum(a, n - 1)so the active prefix shrinks by one element per call.Off-by-one access:
a[n]lies outside the active prefix. Testn == 0first, then usea[n - 1].Hidden resource limits: deep recursion can exhaust the call stack. Factorial can also exceed its integer type even when its logic is correct. Keep
factorial(4)as the teaching input, then checkULLONG_MAXfrom<limits.h>and choose an appropriate representation before scaling it.
Recursion in C practice: trace, repair, and write
Assessments commonly ask you to predict output, draw frames, repair a base case, analyse time and auxiliary space, or turn a recurrence into code. Use this four-line template before running a program:
Call | Base/progress check | Pending work | Return value |
|---|---|---|---|
1. ___ | ___ | ___ | ___ |
2. ___ | ___ | ___ | ___ |
3. ___ | ___ | ___ | ___ |
4. ___ | ___ | ___ | ___ |
Try these precisely specified exercises:
Write
power(3, 4)withexponent == 0as the base case, and confirm81. Hint: multiply by the base after solving the problem forexponent - 1.Recursively sum the digits of
5072, and confirm14. Hint: addn % 10to the result forn / 10.Recursively search sorted
{2, 5, 9, 14, 20}for14and confirm zero-based index3, then search for7and confirm-1. Hint: compare with the middle value and recurse only into the possible half.
Use the Coding & DSA Courses for Placements category to progress from small traces to larger problems.
Recursion in C: the short version and next step
Keep this checklist beside your first traces:
Define the smallest directly solvable input.
Return directly at that base case.
Make every recursive argument smaller by a clear measure.
Trace calls down, then calculate returned values up.
Calculate both time complexity and call-stack space.
The four outputs are 4 0 7, 24, 10, and 6. Change one input in each program, trace it by hand, and only then run it. For a structured continuation through functions, arrays, pointers, and problem solving, follow the C Programming Course.
Keep learning
Basic Recursion in C: Call Stack, Worked Traces and Exam Patterns
Learn how recursive C functions descend, stop and unwind. Trace factorial and printed output, count Fibonacci calls, and compare recursion with iteration.
this Keyword in JavaScript: Call-Site Rules with Worked Examples
Trace JavaScript receivers through ordinary functions, arrows, callbacks, constructors, call, and bind. Worked examples turn this from a guess into a call-site rule.
JavaScript Runtime Explained: Call Stack, Memory and Event Loop
Build a practical mental model of JavaScript execution. Trace values, object identity, function calls, promise microtasks and zero-delay timers through runnable examples.
Stacks and queues: operations, applications and the exam angle
Stacks and queues explained: LIFO vs FIFO, array and linked implementations, a worked postfix evaluation, and the circular-queue full and empty conditions.





