⚙️ C programming basics · Class 10 · Lesson 11 of 18 · Free
Recursion in C – Functions That Call Themselves
⏱ About 35 minutes · ▶ run real C here — nothing to install · no sign-in
In this lesson you will
- Write a recursive function with a clear base case and recursive case
- Trace how calls pile up on the call stack and come back
- Decide when a loop is better than recursion, using Fibonacci as the example
Stand between two mirrors and you see a mirror inside a mirror inside a mirror. Recursion is the same idea in code: a function that calls itself on a smaller problem, until the problem is so small the answer is obvious.
What is recursion in C?
Recursion means a function calls itself. Each call works on a smaller piece of the problem.
Every recursive function needs two parts. The base case is the small problem you answer directly, with no more calls. The recursive case does a little work and calls the function again on a smaller input.
Here the countdown before a cricket match stops at 0. That is the base case. Try it: start the countdown from 10.
3... 2... 1... Play!
How does factorial work with recursion in C?
Factorial of n (written n!) is 1 × 2 × … × n. Notice that 5! = 5 × 4!. So factorial can use itself on a smaller number.
The base case is 0! = 1. This program prints each call with spaces in front, so you can see the calls go deeper and then come back with answers.
We use long long (8 bytes) because factorials grow fast. 20! still fits; 21! does not. Try it: call fact(6, 0).
fact(4) called
fact(3) called
fact(2) called
fact(1) called
fact(0) called
fact(1) = 1
fact(2) = 2
fact(3) = 6
fact(4) = 24
4! = 24
💡 `%*s` with "" prints depth*2 spaces: a neat trick for drawing the call tree.
What is the call stack in recursion?
Each call gets its own copy of n and its own local variables. They are kept in a memory area called the call stack, like a pile of plates.
A new call puts a plate on top. When a call returns, its plate is removed and the call below continues from where it stopped.
That is why code AFTER the recursive call runs in reverse order. Look at the output: the lines "entering" go 1, 2, 3 and the lines "leaving" go 3, 2, 1.
entering floor 1 entering floor 2 entering floor 3 (top reached) leaving floor 3 leaving floor 2 leaving floor 1
💡 The stack has a fixed size. Too many calls without stopping crash the program: a "stack overflow".
How do you use recursion with arrays and strings in C?
Arrays split nicely: the sum of n marks is the last mark plus the sum of the first n − 1 marks. The base case is an empty array, whose sum is 0.
Strings split too. A word is a palindrome if its first and last letters match and the middle part is also a palindrome.
Try it: add a word like "malayalam" or "nitin" and run again.
Total marks: 390 madam palindrome rotor palindrome cricket not a palindrome
Why is recursive Fibonacci slow in C?
Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8 … Each is the sum of the two before it. The recursive version looks short and neat.
But it calls itself twice each time, and it works out the same values again and again. This program counts the calls.
A simple loop needs only n steps. Try it: change 25 to 30 and watch the call count jump. Recursion is great when it makes the code clearer, but a loop is often faster.
Recursive: fib(25) = 75025 using 242785 calls Loop: fib(25) = 75025 using 25 steps
🤔 Predict the output
Think like C: read the code and choose what it prints. You get the reason straight away.
Question 1. The printf comes AFTER the recursive call. What does this print?
#include <stdio.h>
void show(int n) {
if (n == 0) return;
show(n - 1);
printf("%d ", n);
}
int main(void) {
show(3);
printf("\n");
return 0;
}
Question 2. What does this print?
#include <stdio.h>
int total(int n) {
if (n == 1) return 1;
return n + total(n - 1);
}
int main(void) {
printf("%d\n", total(4));
return 0;
}
Question 3. How many times is fib called in total for fib(4)?
#include <stdio.h>
int calls = 0;
int fib(int n) {
calls++;
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
int main(void) {
fib(4);
printf("%d\n", calls);
return 0;
}
🧩 Your challenge
Write a recursive function `int digit_sum(int n)` that adds the digits of a number. Read a roll number and print the sum of its digits. Use no loops. Hint for the idea: digit_sum(4052) = 2 + digit_sum(405). Example for input 40527: Digit sum: 18
Enter roll number: 40527 Digit sum: 18
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <stdio.h>
void countdown(int n) {
if (n == 0) {
printf("Go!\n");
return;
}
printf("%d ", n);
countdown(n - 2);
}
int main(void) {
countdown(5);
return 0;
}
Your program crashed: it used memory it does not own — a bad pointer, an index past the end of an array, or a function that keeps calling itself without stoppi…
✅ Right
#include <stdio.h>
void countdown(int n) {
if (n <= 0) {
printf("Go!\n");
return;
}
printf("%d ", n);
countdown(n - 2);
}
int main(void) {
countdown(5);
return 0;
}
Counting 5, 3, 1, -1 … jumps over 0, so the base case is never reached. The calls pile up until the stack is full and the program crashes. Make sure every path reaches the base case.
❌ Wrong
#include <stdio.h>
int power(int base, int exp) {
if (exp == 0) return 0;
return base * power(base, exp - 1);
}
int main(void) {
printf("2 to the power 5 = %d\n", power(2, 5));
return 0;
}
Compiles and runs, but prints: 2 to the power 5 = 0 ⏎
✅ Right
#include <stdio.h>
int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
int main(void) {
printf("2 to the power 5 = %d\n", power(2, 5));
return 0;
}
Any number to the power 0 is 1, not 0. A wrong base case value spreads to every answer: here everything is multiplied by 0.
❌ Wrong
#include <stdio.h>
int sum_to(int n) {
if (n == 0) return 0;
n + sum_to(n - 1);
}
int main(void) {
printf("%d\n", sum_to(5));
return 0;
}
Line 5: warning: expression result unused [-Wunused-value]
✅ Right
#include <stdio.h>
int sum_to(int n) {
if (n == 0) return 0;
return n + sum_to(n - 1);
}
int main(void) {
printf("%d\n", sum_to(5));
return 0;
}
The recursive case works out the answer but never returns it, so the caller gets garbage. Clang warns about this. Every path of a non-void function needs a return.
📌 Remember
- A recursive function calls itself on a smaller problem.
- It needs a base case (answer directly) and a recursive case (smaller call).
- Each call has its own variables on the call stack; code after the call runs in reverse order.
- If the base case is never reached, the stack fills up and the program crashes.
- Some recursion repeats work (like Fibonacci); a loop can be much faster.
Finished the quiz and the challenge?
Questions students ask
What is a base case in recursion?
It is the simplest input, where the function returns an answer without calling itself. Without it, or if it is never reached, the calls never stop.
Is recursion better than loops in C?
Not always. Anything you can do with recursion you can also do with a loop. Recursion is clearer for problems that split into smaller copies, like trees or Tower of Hanoi. Loops use less memory and are often faster.
What is a stack overflow?
Every call uses some stack memory until it returns. The stack has a fixed size. Too many calls at once, usually from a missing base case, use it all up and the program crashes.
Can main call itself in C?
Yes, C allows it, but it is rarely a good idea. Write a separate recursive function and call it from main.