- What the Fibonacci sequence is and how it's defined
- How to write a recursive Fibonacci function (the textbook version)
- Why the naive recursive version is terribly slow for larger n
- How to rewrite it iteratively in O(n) time
- How to trace a recursive call to see the duplicate work
What is the Fibonacci series?
The Fibonacci sequence is one of the most famous sequences in mathematics: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, and so on. Each term is the sum of the two terms before it. The first two terms are fixed — 0 and 1 — and everything after comes from the rule. If you list the sequence with indices (starting at 0), it looks like this:
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| fib(n) | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
The definition is deceptively simple: fib(0) = 0, fib(1) = 1, and fib(n) = fib(n-1) + fib(n-2) for n ≥ 2. That definition translates directly into a recursive function — and that's why the Fibonacci problem is the classic first example of recursion in every C textbook. But the translation is also a trap, because the naive recursive version is catastrophically slow for larger n. We'll look at both versions and see why.
💡 In one line: write a function fib(n) that returns the nth term. Use the base cases fib(0) = 0 and fib(1) = 1. For larger n, either recurse (fib(n-1) + fib(n-2)) or iterate (two variables that walk forward through the sequence).
Two approaches: recursion vs iteration
Both approaches compute the same values. The difference is how.
| Aspect | Recursive | Iterative |
|---|---|---|
| Code length | 3 lines (elegant) | 8–10 lines |
| Time complexity | O(2ⁿ) — exponential | O(n) — linear |
| Time for fib(40) | ~1 second | microseconds |
| Time for fib(50) | ~1 minute | microseconds |
| Stack depth | O(n) — deep for large n | O(1) — flat |
| Stack overflow risk | Yes, for large n | No |
The recursive version is beautiful on paper but slow in practice. The iterative version is less elegant but runs in linear time. For this assignment, both are worth seeing — the recursive one to understand the definition and to see the cost of naive recursion, the iterative one because it's what you'd actually use in real code.
🎯 Rule of thumb: recursion is great when the problem naturally breaks into smaller subproblems that don't overlap. Fibonacci is the wrong kind of problem for naive recursion — every call recomputes values that were already computed, and that's where the exponential blowup comes from.
Recursive Program (textbook version)
Program: recursive fib function
#include <stdio.h>
/* Function prototype */
long fib(int n);
int main(void) {
int n;
printf("Enter n: ");
scanf("%d", &n);
printf("Fibonacci term %d is %ld\n", n, fib(n));
return 0;
}
/* Recursive definition */
long fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
Short, clean, and correct — but only for small n. Ask for fib(40) and you'll notice a pause. Ask for fib(45) and you'll wait a while. Ask for fib(50) and you'll think the program hung. It didn't — it's just doing ~2⁵⁰ additions, which is more than a quadrillion operations.
Iterative Program (recommended)
Program: iterative fib function
#include <stdio.h>
/* Function prototype */
long fib(int n);
int main(void) {
int n;
printf("Enter n: ");
scanf("%d", &n);
printf("Fibonacci term %d is %ld\n", n, fib(n));
return 0;
}
/* Iterative definition */
long fib(int n) {
if (n == 0) return 0;
if (n == 1) return 1;
long prev = 0; /* fib(0) */
long curr = 1; /* fib(1) */
for (int i = 2; i <= n; i++) {
long next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
This version uses two variables to walk through the sequence, updating them each iteration. It takes O(n) time and O(1) space — no recursion, no stack growth, no exponential blowup. Ask for fib(50) and it returns instantly. This is the version you should ship.
Here's a version that prints the whole series up to n, useful for verification:
Variant: print the first n Fibonacci terms
#include <stdio.h>
int main(void) {
int n;
printf("How many terms? ");
scanf("%d", &n);
long prev = 0, curr = 1;
printf("Fibonacci series: ");
for (int i = 0; i < n; i++) {
printf("%ld ", prev);
long next = prev + curr;
prev = curr;
curr = next;
}
printf("\n");
return 0;
}
This version is even simpler — no function needed, because you're just printing the sequence, not returning the nth term. But for the assignment "find the nth term using a function," the previous version (with fib) is the right shape. The print-the-series version is included so you can eyeball the output against a known list.
Program Output
For the recursive version, small n:
Enter n: 10
Fibonacci term 10 is 55
For the iterative version, same input:
Enter n: 10
Fibonacci term 10 is 55
For the iterative version, larger n:
Enter n: 40
Fibonacci term 40 is 102334155
Try the same input with the recursive version. Wait about a second. It will finish — but the delay is noticeable and gets exponentially worse. For fib(50), the recursive version takes roughly 60 seconds on a typical machine. The iterative version takes less than a millisecond. Both print the same number: 12586269025.
For the print-the-series variant:
How many terms? 15
Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
That's the correct sequence — the values match the table above, extended a bit further.
Step-by-Step Explanation
Let's start with the recursive version, since that's the direct translation of the definition, and then look at why the iterative version is better.
1. The recursive definition
The function body is three lines:
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
The first two are the base cases — the smallest values, defined directly without recursion. The third line says: "for any other n, recurse on n-1 and n-2, and add the results." If you read it as a description of the sequence, it's literally the definition word for word: "each term is the sum of the two before it."
2. Tracing fib(5)
Let's expand the calls. Here's the tree:
fib(5)
├── fib(4)
│ ├── fib(3)
│ │ ├── fib(2)
│ │ │ ├── fib(1) = 1
│ │ │ └── fib(0) = 0
│ │ └── fib(1) = 1
│ └── fib(2)
│ ├── fib(1) = 1
│ └── fib(0) = 0
└── fib(3)
├── fib(2)
│ ├── fib(1) = 1
│ └── fib(0) = 0
└── fib(1) = 1
Count the calls: fib(3) is computed twice, fib(2) three times, fib(1) five times, fib(0) three times. Total: 15 calls just to compute fib(5). For fib(10), it's 177 calls. For fib(20), it's 21,891. For fib(40), it's over 200 million. That's the exponential blowup — each new n roughly doubles the work, because each call spawns two more.
3. Why the iterative version is O(n)
The iterative version keeps only two variables — prev and curr — and walks forward through the sequence once:
long prev = 0; /* fib(0) */
long curr = 1; /* fib(1) */
for (int i = 2; i <= n; i++) {
long next = prev + curr;
prev = curr;
curr = next;
}
return curr;
Trace it for n = 5:
- Start: prev = 0, curr = 1. (These represent fib(0) and fib(1).)
- i = 2: next = 0 + 1 = 1. prev = 1, curr = 1. (Now prev = fib(1), curr = fib(2).)
- i = 3: next = 1 + 1 = 2. prev = 1, curr = 2. (prev = fib(2), curr = fib(3).)
- i = 4: next = 1 + 2 = 3. prev = 2, curr = 3. (prev = fib(3), curr = fib(4).)
- i = 5: next = 2 + 3 = 5. prev = 3, curr = 5. (prev = fib(4), curr = fib(5).)
- Loop ends. Return curr = 5. ✓
Five iterations for n = 5. For n = 50, fifty iterations. For n = 1,000,000, a million iterations — a second or two at most. No exponential tree, no repeated work, no stack growth.
4. Why long instead of int?
Fibonacci numbers grow fast. fib(46) is 1,836,311,903 — still fits in a 32-bit int. But fib(47) is 2,971,215,073 — that overflows a signed 32-bit int (which maxes at 2,147,483,647). Switching to long extends the useful range to about fib(92) on a 64-bit system. Beyond that, you'd need unsigned long long or arbitrary-precision arithmetic. For this problem, long is the reasonable default — it covers the sizes you'd test in practice without overflow.
5. The base cases are non-negotiable
Without if (n == 0) return 0; and if (n == 1) return 1;, the recursion would never terminate — fib(5) would recurse to fib(4) to fib(3) to fib(2) to fib(1) to fib(0) to fib(-1) ... and crash with a stack overflow. The base cases are what stop the recursion. Every recursive function needs them, and getting them right is half the work.
6. Why the recursive version is still useful
Even though it's slow, the recursive version teaches important lessons: how recursion terminates via base cases, how call trees grow, and how a direct translation of a mathematical definition into code can be beautiful but inefficient. Recognizing the O(2ⁿ) pattern in a recursive function is a valuable skill — you'll see it in many interview problems, and knowing when to memoize or convert to iteration is the next step. This assignment is the gateway to those ideas.
🔍 Try this: run both versions with n = 35, 40, and 45. Time them with time ./program on the command line. You'll see the recursive version slow down dramatically while the iterative version stays instant. That difference is the difference between O(2ⁿ) and O(n), and it's one of the most striking demonstrations of algorithmic complexity you can see in a single program.
Frequently Asked Questions
1. Should I use the recursive or iterative version?
For real code: iterative, always. It's faster by orders of magnitude for larger n, uses less stack, and can't blow up on you. For learning recursion: the recursive version is essential — it's the clearest first example of a recursive function. Write it once to see it work, then replace it with the iterative version in anything that matters.
2. Is fib(0) 0 or 1?
Depends on convention. Some textbooks start the sequence with fib(0) = 0, fib(1) = 1 — that's the version used here, and it's the most common in computer science. Some start with fib(1) = 1, fib(2) = 1, which shifts all indices by one. Either convention is valid; the key is to be consistent. If you're implementing for a specific problem or interview question, check which convention the problem assumes.
3. Why does fib(50) take so long with recursion?
Because the recursive version recomputes the same values over and over. fib(48) is computed twice (once for fib(50) via fib(49) and once for fib(50) via fib(48)), fib(47) four times, fib(46) eight times, and so on. The number of calls approximately doubles for each step up in n. For n = 50, that's about 2⁵⁰ calls — roughly a quadrillion. Even at a billion calls per second, that's weeks of computation.
4. What's memoization and would it help?
Memoization is caching the results of function calls so repeated calls return immediately. For Fibonacci, you'd store each computed fib(k) in an array and check the array before recursing. That reduces the time from O(2ⁿ) to O(n) — the same as the iterative version — while keeping the recursive structure. It's a powerful technique for other problems (dynamic programming), but for Fibonacci specifically, the iterative version is simpler and just as fast. Memoization shines when you have overlapping subproblems that are harder to express iteratively.
5. How large can n be before overflow?
With long (64-bit on most systems), the largest Fibonacci number that fits is fib(92) = 7,540,113,804,746,346,429. fib(93) overflows a signed 64-bit integer. With unsigned long long, you'd get to fib(93) but not fib(94). Beyond that, you'd need arbitrary-precision arithmetic (a bignum library). For most teaching purposes, long is plenty.
6. Can I use matrix exponentiation to compute fib faster?
Yes — there's a well-known matrix identity that lets you compute fib(n) in O(log n) time using fast matrix exponentiation. It's an elegant trick and a common interview follow-up. For typical n, the iterative O(n) version is fast enough, so matrix exponentiation is overkill. But if you're curious, it's a great exercise in linear algebra and recursion.
💡 Tip: Once you understand this, try Binet's formula — a closed-form expression for fib(n) using the golden ratio. It's beautiful mathematically but imprecise on computers because of floating-point error. Running both side by side is a great exercise in understanding what "exact" and "approximate" mean in programming.