Nearby lessons

83 of 124

C - Recursion

Recursion is one of the foundational topics in C programming. This lesson explains Recursion — A Function Calling Itself and Fibonacci with Recursion with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Recursion — A Function Calling Itself

Recursion is when a function calls itself to solve a smaller version of the same problem. Every recursive function needs two parts: a base case (when to stop) and the recursive call (calling itself).

In simple words: recursion is like Russian dolls — a function opens a smaller copy of itself, which opens a smaller one, until the tiniest doll (the base case) is reached, and then the answer passes back up, growing at every step.

How it works: factorial(5) asks factorial(4), which asks factorial(3)... down to factorial(1) = 1, then the answers come back up: 1, 2, 6, 24, 120.

Trainer's Note: Recursion vs loop: anything you do with recursion can be done with a loop too. Recursion makes the code shorter and more elegant for problems like factorial, Fibonacci, and tree structures — but it uses more memory. For beginners, master factorial and Fibonacci with recursion.
Example01
CCode Cell
1#include <stdio.h>
2 
3int factorial(int n) // n! = n * (n-1)!
4{
5 if (n <= 1) return 1; // base case - stop here
6 return n * factorial(n - 1); // recursive call
7}
8 
9void main()
10{
11 printf("%d\n", factorial(5)); // 5*4*3*2*1 = 120
12}
Output
120

Fibonacci with Recursion

Example02
CCode Cell
1#include <stdio.h>
2 
3int fib(int n) // nth Fibonacci number
4{
5 if (n <= 1) return n; // base case: fib(0)=0, fib(1)=1
6 return fib(n - 1) + fib(n - 2);
7}
8 
9void main()
10{
11 int i;
12 for (i = 0; i < 8; i++) {
13 printf("%d ", fib(i));
14 }
15}
Output

0 1 1 2 3 5 8 13 
      
📝 Key Takeaways
  • Functions split code into reusable, readable tasks.
  • Three parts: declaration, definition, call.
  • Four combinations of arguments and return values.
  • C uses call by value — functions get a copy, originals stay unchanged.
  • return gives a value back and ends the function.
  • Recursion = a function calling itself, with a base case to stop.
  • Classic recursion: factorial and Fibonacci.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3