Recursion Ready
main.c

                

Ready

Statements run 0 Lines printed 0
Ready

Keyboard: ← → step · Space play / pause · R reset · Esc exit classroom mode

How it works

The ideas behind the lab

Exactly what you watched happen, in plain steps.

Every recursive function has two parts

The base case answers the smallest version of the problem directly, without calling again — it is what stops the recursion. The recursive case reduces the problem (n becomes n − 1, n / 10, a shorter list …) and calls the same function on the smaller piece, trusting it to return the right answer. Each call gets its own stack frame, so every call has its own n.

long long fact(int n)
{
    if (n <= 1)                  // base case: the answer is known
        return 1;
    return n * fact(n - 1);      // recursive case: a smaller problem
}

// fact(4) = 4 * fact(3) = 4 * 3 * fact(2) = 4 * 3 * 2 * fact(1) = 24
Classic recursive definitions
Problem Base case Recursive case Example
Factorial fact(1) = 1 fact(n) = n × fact(n − 1) fact(5) = 120
Power power(b, 0) = 1 power(b, e) = b × power(b, e − 1) power(2, 10) = 1024
Sum of digits n < 10 → n n % 10 + sum(n / 10) sum(4096) = 19
Fibonacci fib(0) = 0, fib(1) = 1 fib(n − 1) + fib(n − 2) fib(10) = 55
GCD (Euclid) gcd(a, 0) = a gcd(b, a % b) gcd(48, 18) = 6
Tower of Hanoi 0 disks: do nothing move n − 1, move 1, move n − 1 2ⁿ − 1 moves

Winding and unwinding

  1. Every call pushes a new frame with its own parameters on the stack.
  2. The calls go deeper and deeper until the base case is reached.
  3. The base case returns a value without calling again.
  4. Then the frames return one by one, each finishing its own calculation.
  5. Code before the recursive call runs on the way down; code after it runs on the way back up.

Writing a recursive function

  1. Find the smallest case whose answer you know — write it first.
  2. Describe the answer for n using the answer for a smaller problem.
  3. Make sure every call gets closer to the base case.
  4. Trust the recursive call: assume it returns the right answer.
  5. Trace a small example (n = 3) on paper with the stack frames.

Recursion vs loops

  1. Anything written with recursion can also be written with a loop.
  2. Recursion is natural for problems that split into smaller copies (trees, Hanoi, sorting).
  3. Each call costs time and stack memory; loops are usually faster.
  4. Too deep a recursion (or a missing base case) overflows the stack and crashes.
  5. Naive fib(n) repeats work exponentially — the loop version is far quicker.
Walkthrough

Sum of digits, and a countdown on the way down

Every line, explained.

1 #include <stdio.h>
2
3 int sumDigits(int n)
4 {
5 if (n < 10) return n; Base case: a single digit is its own sum.
6 return n % 10 + sumDigits(n / 10); The last digit + the sum of the other digits.
7 }
8
9 void countdown(int n)
10 {
11 if (n == 0) { Base case.
12 printf("Go!\n");
13 return; A void function can stop with a plain return.
14 }
15 printf("%d ", n); Runs BEFORE the call, so on the way down.
16 countdown(n - 1); A smaller problem.
17 }
18
19 int main(void)
20 {
21 printf("%d\n", sumDigits(4096)); 6 + sum(409) = 6 + 9 + sum(40) = … prints 19
22 countdown(3); Prints 3 2 1 Go!
23 return 0;
24 }
Common mistakes

Spot the bug

Mistakes almost every beginner makes — and how to fix them.

No base case

✗ Wrong
int fact(int n)
{
    return n * fact(n - 1);
}
✓ Right
int fact(int n)
{
    if (n <= 1) return 1;
    return n * fact(n - 1);
}

Nothing stops the calls: the stack fills up and the program crashes with a stack overflow (segmentation fault).

Not getting closer to the base case

✗ Wrong
return n * fact(n);      // same n again
✓ Right
return n * fact(n - 1);  // smaller each time

Every recursive call must make the problem smaller, or the base case is never reached.

A base case that can be jumped over

✗ Wrong
if (n == 1) return 1;
…   // fact(0) never stops
✓ Right
if (n <= 1) return 1;

fact(0) skips n == 1 and goes to -1, -2 … Use a condition that catches every small value.

Forgetting to return the recursive result

✗ Wrong
if (n < 10) return n;
n % 10 + sumDigits(n / 10);   // result lost
✓ Right
if (n < 10) return n;
return n % 10 + sumDigits(n / 10);

The value of the recursive call must be passed back up with return, at every level.

Using naive recursion for big Fibonacci numbers

✗ Wrong
fib(45)   // about 3.6 billion calls
✓ Right
// loop: a = 0, b = 1, slide 45 times
// or remember results already found

fib(n) calls itself twice, so the work roughly doubles with each n. A loop needs only n rounds.

Practice

Check your understanding

Answer each question — you will see the explanation straight away.

0 / 5 correct
Question 1

What stops a recursive function from calling itself forever?

Question 2

int f(int n) { if (n == 0) return 0; return n + f(n - 1); } — f(4) is?

Question 3

While fact(1) runs (called from main as fact(4)), how many fact frames are on the stack?

Question 4

What happens to a recursive function with no base case?

Question 5

How many moves does the Tower of Hanoi need for 3 disks?

Assessment

Recursion quiz

Test yourself: 10 questions, 70% to pass. Create a free account to take the quiz, save your progress and work towards the certificate.