Nearby lessons

52 of 72

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

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