C Programming Tutorial 0/65 lessons ~6 min read Lesson 20
Recursion
Recursion is when a function calls itself.
Course progress0%
Focus
9 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
Recursion is when a function calls itself. Every recursive function needs a base case to stop.
Understanding the topic
Base case Simplest input — return directly without recursing.
Recursive step Break problem into smaller subproblem.
Stack depth Too deep recursion can overflow the stack.
- Base case — Simplest input — return directly without recursing.
- Recursive step — Break problem into smaller subproblem.
- Stack depth — Too deep recursion can overflow the stack.
Step-by-step explanation
- Base case — Simplest input — return directly without recursing.
- Recursive step — Break problem into smaller subproblem.
- Stack depth — Too deep recursion can overflow the stack.
Informative example
Example program:
c
#include <stdio.h>int factorial(int n) {if (n <= 1) return 1;return n * factorial(n - 1);}int main(void) {printf("%d\n", factorial(5));return 0;}
Output
120
Execution workflow
1Recursion — step by step
1 / 3Base case
Simplest input — return directly without recursing.
Best practices
- Enable warnings: gcc -Wall -Wextra -std=c11 source.c -o app
- Give every variable a defined value before it is read.
- Stay inside array bounds — C will not stop you from over-running a buffer.
Common mistakes
- Reading uninitialized storage — behavior is undefined.
- Dismissing compiler warnings instead of fixing root causes.
- Ignoring NULL returns from malloc, fopen, and similar APIs.
Hands-on exercise
Practice problems:
- Fibonacci with recursion
- Sum 1..n recursively
Summary
Recursion in C — Self-calling functions and mandatory base cases.
Ready to mark this lesson complete?Track your journey across the entire course.