C Language
5. Functions & RecursionIntermediate8 min read

Recursion in C: Call Stack & Base Conditions

Understand recursive functions, base conditions, call stack frame allocation, stack overflow dangers, and iterative alternatives.

Key Takeaways & Core Concepts
  • A recursive function calls itself to solve smaller sub-problems.
  • Every recursive function MUST have at least one base condition to terminate recursion.
  • Missing or flawed base conditions cause infinite recursion, exhausting stack memory (Stack Overflow).
  • Each recursive call creates a new stack frame holding its own local variables and return address.

How the Call Stack Executes Recursion

When a function calls itself, the CPU pushes a new stack frame onto the Call Stack. Each frame maintains its own independent set of arguments and local variables. Once the base condition is met, the stack unwinds back to the original caller.

Recursive Factorial & Fibonacci with Step Tracking
1#include <stdio.h>
2
3unsigned long long factorial(int n) {
4 // Base condition
5 if (n <= 1) return 1;
6 // Recursive call
7 return n * factorial(n - 1);
8}
9
10int fibonacci(int n) {
11 if (n <= 0) return 0;
12 if (n == 1) return 1;
13 return fibonacci(n - 1) + fibonacci(n - 2);
14}
15
16int main(void) {
17 int num = 6;
18 printf("Factorial of %d is: %llu\n", num, factorial(num));
19 printf("First 7 Fibonacci terms: ");
20 for (int i = 0; i < 7; i++) {
21 printf("%d ", fibonacci(i));
22 }
23 printf("\n");
24 return 0;
25}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
25 lines
Note: factorial(6) calls 6 * factorial(5)... down to factorial(1) = 1, then unwinds the stack.
Practice & AssessmentC Programming Complete Course

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 1 correct(0 attempted)

1

What happens if a recursive function does not define a valid base case?

Intermediate