Fibonacci in C: solved exercise
Fibonacci in C: solved exercise
If you searched for a solved Fibonacci exercise in C, here are three implementations with complexity analysis: the classic recursive version (O(2^n)), the iterative version (O(n)), and the memoized recursive version (O(n)).
The Fibonacci sequence is the canonical example for understanding the difference between a naive recursive solution and a dynamic one: without a cache, the same subproblem is solved exponentially more times.
Problem statement
Implement three functions that return the n-th Fibonacci number (F(0)=0, F(1)=1):
fib_recursive(n): recursive version without cache.fib_iterative(n): iterative version with O(1) space.fib_memo(n): recursive version with a memoization table.
Print the first 10 terms using each version.
C solution
Expected output
Common mistakes
- Not defining the base case: without
if (n <= 1) return nthe recursion is infinite and causes a stack overflow. - Using
intfor largen: F(47) exceeds the range ofint(2,147,483,647); uselong longto safely reach F(92). - Forgetting to zero-initialize the memo table:
staticgives zero-initialized memory, but a stack-allocated array requires an explicitmemset. - Benchmarking the recursive version for
n > 40: the runtime grows exponentially and can freeze the program for several seconds.
Practical use
Fibonacci appears in the analysis of divide-and-conquer algorithms, in computing the worst-case complexity of quicksort, and in data structures like Fibonacci heaps. Memoization is the first step toward dynamic programming.
Recommended next exercise
- Recursion in C: solved exercises
- Factorial in C: solved exercise
- Sieve of Eratosthenes in C: solved exercise
- All C exercises
Guided practice and full book
If you want a complete path with progressive difficulty:
FAQ
Why is the recursive version so slow for large values?
Because it recomputes the same subproblems multiple times. To compute F(5), it calls F(3) twice and F(2) three times. The complexity is O(2^n): for F(40), over one billion recursive calls are made.
When should I use the iterative version versus the memoized version?
Use the iterative version when you only need the n-th term: it uses O(1) space. The memoized version is useful when you need multiple terms at different times (separate calls), since it reuses the cache across them.
Is there a direct formula to compute F(n)?
Yes: Binet’s formula, F(n) = (φ^n − ψ^n) / √5 where φ = (1+√5)/2. However, it uses double and accumulates rounding errors for n > 70, so in C the iterative version with 64-bit integers is preferred.