Skip to Content
Course content

31: Practice Exercise: Recursive Factorial and Fibonacci

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern when people first dive into recursion: they treat it as if it's just a "shorthand" for a for loop. They assume that because the code looks elegant and concise, the computer is handling it with the same linear efficiency as a loop. This is a dangerous assumption that leads to programs that crash or hang the moment you feed them a slightly larger number.

The "It's Just a Loop" Delusion

Take the Fibonacci sequence. You might write a recursive function that looks like this: return fib(n-1) + fib(n-2);. It feels intuitive. But here is where the misconception falls apart: recursion isn't a line; in this case, it's a tree. If you call fib(5), it calls fib(4) and fib(3). Then fib(4) calls fib(3) and fib(2). Notice that? We are calculating fib(3) twice. By the time you hit fib(40), your computer is performing millions of redundant calculations. A for loop would have done this in 40 steps; the recursive version is doing it in billions.

Defining the Floor with Base Cases

The most common way a recursive function fails—usually with a Segmentation Fault—is when it doesn't know how to stop. I call the base case your "exit strategy." Without it, you're just pushing frames onto the stack until the operating system tells you to stop wasting its memory.

For a factorial, the floor is simple: 0! is 1. For Fibonacci, you need two floors: if n is 0, return 0; if n is 1, return 1. I always tell my juniors to write the base case first. If you build the exit before you build the hallway, you can't get trapped in an infinite loop.

Linear vs. Branching Recursion

It's important to realize that not all recursion is created equal. Factorial is "linear recursion." Each call only spawns one more call. It's basically a loop with a higher memory cost. Fibonacci (in its naive form) is "branching recursion." This is where the exponential growth happens.

// Linear: One path down, one path back up.
int factorial(int n) {
    if (n <= 1) return 1; 
    return n * factorial(n - 1);
}

// Branching: A tree that explodes in size.
int fibonacci(int n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

When you're practicing these today, I want you to really think about the "stack." Every time factorial(5) calls factorial(4), the current state of factorial(5) is frozen in memory. It's waiting. It can't finish the multiplication until the call below it returns a value. When you hit the base case, the tower finally collapses back upward, resolving each multiplication one by one.




📋 Practical Task

Implement a Recursive Math Suite for Factorials and Fibonacci

Your task is to create a C program that allows a user to choose between calculating a factorial or a Fibonacci number using recursive functions. To ensure you've mastered the concepts, your program must meet these specific requirements:

  • Implement long long recursive_factorial(int n) to handle larger results without overflowing as quickly.
  • Implement long long recursive_fibonacci(int n).
  • Include a "sanity check" in main(): If the user enters a number greater than 40 for Fibonacci, print a warning that the program may hang due to exponential time complexity before attempting the calculation.
  • Ensure both functions have explicit base cases to prevent stack overflow.
  • Use a switch statement in main() to let the user select the operation.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.