liveBook · Manning

Fibonacci sequence

As explained in Modern C

The Fibonacci sequence is the integer sequence in which each term after the first two is the sum of the preceding two terms.

The Fibonacci sequence begins 1, 1, 2, 3, 5, 8, 13, and continues with each term equal to the sum of the preceding two. Its growth is exponential. section 7.3

A direct recursive definition in C

size_t fib(size_t n) { if (n < 3) return 1; return fib(n-1) + fib(n-2); } The condition n < 3 supplies the first two values; otherwise the function evaluates two smaller calls and adds their results. A call such as fib(4) creates a branching tree of calls with three terminating leaf calls. In general, fib(n) induces Fₙ leaf calls. The direct translation is therefore easy to read but slow because the same values are recomputed. section 7.3

TAKEAWAY: improve the computation without changing the sequence.

  • Cache previously computed values so recursive calls reuse results. section 7.3
  • Track only two values in a small buffer and update them while recursing. section 7.3

How Modern C covers it

How deep it goes
Defines the recurrence, traces fib(4), counts leaf calls, and contrasts direct recursion with caching and reduced state.
Examples
Demonstrates the sequence values, a C fib function, the fib(4) call tree, leaf-call counting, and cached computation.
What you can do after
Builds Fibonacci computation in C and diagnose why direct recursion becomes slow.
How it connects
Connects Fibonacci numbers to recursion, exponential growth, execution time, caching, and the golden ratio.

Also explained in

Compare how 6 books explain Fibonacci sequence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.