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

Updated 27 Nov 20266 min read
Recursion in C Tutorial: Base Cases, Call Stacks, and 4 Runnable Examples

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.

c
#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

Factorial calls descend from 4 to 1, then unwind through 2, 6, and 24.
c
#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:

  1. factorial(1) = 1

  2. factorial(2) = 2 * 1 = 2

  3. factorial(3) = 3 * 2 = 6

  4. factorial(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.

c
#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

S(0)

base case

0

S(1)

0 + 4

4

S(2)

4 + (-2)

2

S(3)

2 + 7

9

S(4)

9 + 1

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].

Array-sum diagram for 4, -2, 7, 1: the active prefix shrinks from S(4) to S(0) while unwind subtotals rise 0, 4, 2, 9, 10.

Recursion in C with Euclid's algorithm: GCD of 48 and 18

Euclid's algorithm replaces a positive pair with its divisor and remainder.

c
#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 call gcd(18, 12).

  • gcd(18, 12): 18 % 12 = 6, so call gcd(12, 6).

  • gcd(12, 6): 12 % 6 = 0, so call gcd(6, 0).

  • gcd(6, 0) returns 6.

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

factorial(n)

O(n)

O(n)

O(n)

O(1)

Sum n array values

O(n)

O(n)

O(n)

O(1)

Euclid's GCD

O(log(min(a,b)))

O(log(min(a,b)))

O(log(min(a,b)))

O(1)

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 == 1 in factorial means a call with n equal to 0 never matches, and because n is unsigned, n - 1 wraps to a very large value, so the recursion continues until the call stack is exhausted. Test n <= 1, so both 0 and 1 terminate directly.

  • No progress: calling sum(a, n) instead of sum(a, n - 1) gives the next call the same prefix length, so the base case n == 0 is never reached. Recurse with sum(a, n - 1) so the active prefix shrinks by one element per call.

  • Off-by-one access: a[n] lies outside the active prefix. Test n == 0 first, then use a[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 check ULLONG_MAX from <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:

  1. Write power(3, 4) with exponent == 0 as the base case, and confirm 81. Hint: multiply by the base after solving the problem for exponent - 1.

  2. Recursively sum the digits of 5072, and confirm 14. Hint: add n % 10 to the result for n / 10.

  3. Recursively search sorted {2, 5, 9, 14, 20} for 14 and confirm zero-based index 3, then search for 7 and 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:

  1. Define the smallest directly solvable input.

  2. Return directly at that base case.

  3. Make every recursive argument smaller by a clear measure.

  4. Trace calls down, then calculate returned values up.

  5. 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.