New to Rust? Grab our free Rust for Beginners eBook Get it free →
Fibonacci Series with Dynamic Programming in C++

A C++ program that calculates Fibonacci terms can repeat work when it uses direct recursion. Dynamic programming builds each term from the two before it and keeps earlier results available for later calculations.
I’ll show how to calculate the sequence in C++ and explain how the starting values set its term numbers.
TL;DR
Store solved terms in a table when later steps need them, or keep the dependency pair when only the final term is needed.
- Use F(0) = 0 and F(1) = 1 for zero-based indexing.
- A table uses O(n) time and O(n) space for F(n).
- Keep two rolling values when earlier terms are not needed later. The extra storage stays O(1).
What Is the Fibonacci Series?
Each Fibonacci term after the first two is the sum of its two predecessors. In zero-based notation, F(n) = F(n – 1) + F(n – 2) for n at least 2.
The first terms are 0, 1, 1, 2, 3, 5, 8, 13, 21 and 34. This index convention lets an array position represent the matching n directly.
A request for F(n) asks for one value at an index. A request for the first k terms asks for a list whose length is k.
Calculating F(6) requires F(5) and F(4), which is why the recurrence forms overlapping subproblems.
The simple recursive version follows the formula directly, but branches into repeated work. For example, calculating F(5) asks for F(3) through both F(4) and F(3), so the same value can be recalculated.
Dynamic programming handles repeated dependencies in two common ways: memoization stores results during recursive calls, while tabulation fills a table from base values in increasing order.
For a different problem, memoization can skip states that the requested result never reaches.
How to Build a Fibonacci Series in C++ Step by Step
The table starts with the two base values, and before iteration i, every earlier entry contains its correct term so the two inputs are ready. After storing their sum, entries zero through i are correct, proving the loop returns F(n) at the requested index.
The program below prints F(0) through F(10). It uses std::vector for indexed storage and uint64_t for each result.
The sequence also has a connection to the golden ratio, often written as phi and approximately 1.618033988749895. Ratios of consecutive Fibonacci numbers approach that value as the indices grow. This relationship is useful in number theory and analysis, but it does not change the integer recurrence used by the C++ program.
Some references present long Fibonacci lists, including tables with hundreds of entries or factorizations of individual terms. That reference data helps with lookups, while a program’s requested index and output shape determine what it calculates. Factorising large values is a separate and more expensive task.
Step 1: Set the index convention and base values
The vector uses positions zero through n for F(n), so it needs n + 1 elements. A length of n would omit the requested final position.
With n equal to zero, the vector has one slot, the assignment to dp[1] is skipped, and the loop does not run. With n equal to one, the function sets dp[1] and again skips the loop, so both base cases return directly from initialized table entries.
Step 2: Fill each value from its two dependencies
For i starting at 2, calculate dp[i] as dp[i – 1] + dp[i – 2].
The guard compares one addend with the maximum value minus the other, then throws overflow_error when their sum would exceed uint64_t’s range. A wider fixed-width type moves that limit, while a big-integer library supports larger exact terms when the application sets a practical input limit.
Step 3: Compile and run the C++ program
The function rejects negative n before converting it to an unsigned vector size, and an application should cap large positive requests before allocating.
Vector construction happens before the loop checks for overflow, so a very large request can exhaust memory first. Catch invalid_argument at the caller boundary and report the accepted range.
Save the code as fibonacci_dp.cpp. It uses standard headers and compiles as C++17. The compiler command enables additional warnings, while the output sample checks the base values and early loop updates.
I compiled and ran this exact file with warnings enabled, and it printed the values shown after the code.
#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <vector>
std::uint64_t fibonacci(int n) {
if (n < 0) {
throw std::invalid_argument("n must be non-negative");
}
std::vector<std::uint64_t> dp(static_cast<std::size_t>(n) + 1);
if (n >= 1) {
dp[1] = 1;
}
for (int i = 2; i <= n; ++i) {
if (dp[i - 1] > std::numeric_limits<std::uint64_t>::max() - dp[i - 2]) {
throw std::overflow_error("Fibonacci value exceeds uint64_t");
}
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
int main() {
for (int n = 0; n <= 10; ++n) {
std::cout << "F(" << n << ") = " << fibonacci(n) << '\n';
}
}
Run the compile-and-execute command shown in the terminal capture. The output is F(0) = 0, F(1) = 1, F(2) = 1, F(3) = 2, F(4) = 3, F(5) = 5, F(6) = 8, F(7) = 13, F(8) = 21, F(9) = 34 and F(10) = 55. The line for F(0) confirms the base case, and the following values show each term using the two immediately preceding terms.

The screenshot belongs to the actual compilation and execution represented by the displayed output. The source and command use a relative file name, so the same sequence works from the directory where you saved fibonacci_dp.cpp and the compiler is available.
Step 4: Choose the storage that matches the next task
The storage cost depends on which values the caller needs after each calculation.
| Approach | Use it when | Stored state |
|---|---|---|
| Vector table | Later output or repeated queries need earlier terms | O(n) values |
| Rolling pair | The caller needs only F(n) | O(1) extra values |
| Memoization | A larger problem reaches only some possible states | Cached values for reached states |
A call for F(n) fills n + 1 entries, taking O(n) time and O(n) storage. The example calls the function separately for every index in its printed prefix, so it rebuilds earlier entries on each call. For an upper index n, that repeated loop does O(n squared) total work.
A prefix generator that fills one table once takes O(n) time. A rolling pair uses O(1) extra storage when the caller needs only the final term.
The example uses an unsigned 64-bit result and checks before addition. If a task requires larger exact terms, use a big-integer type and still check the input and memory requirements.
What Can Go Wrong With Fibonacci in C++?
Check the index convention, vector bounds, input domain and integer range before relying on a Fibonacci implementation. The table maps common symptoms to the correction that fits this program.
| Case | Symptom | Fix |
|---|---|---|
| Index convention | Returned value is shifted by one | Use F(0)=0, F(1)=1 and allocate through index n |
| n equals 0 or 1 | Base case reads a missing vector element | Return the seeded base value without reading later positions |
| Negative n | Unsigned allocation size becomes very large | Reject n before converting it to a vector size |
| Integer overflow | Computed value wraps or signed arithmetic is undefined | Check addition or use an arbitrary-precision integer |
| Large recursive input | Call stack grows with n | Use bottom-up iteration |
| Uninitialized cache | Valid zero is treated as not computed | Use a separate computed flag or fill bottom-up |
| Unbounded table request | Allocation fails before calculation completes | Set an input bound based on the program’s memory budget |
A memoized implementation can keep an array of values and a separate flag array, so zero remains a valid result instead of also serving as the uncomputed marker.
Memoization retains recursive calls down to the base case, so deep requests can exhaust the call stack. A loop avoids recursion and preserves linear time.
For a related example of a recurrence solved with a table, see the Robot Paths problem in C++. The Friends Pairing problem in C++ is another dynamic-programming problem where the state definition and base cases control the result.
Conclusion: Choose the Smallest State You Need
The demo fixes the last index in main(). A reusable command-line version can accept that bound as an argument and print the values through the requested index. Validate the bound before creating the table.
FAQ
These answers cover common questions about the recurrence and its C++ implementation.
What is the Fibonacci recurrence?
F(0) = 0 and F(1) = 1. For n at least 2, F(n) = F(n – 1) + F(n – 2).
Is memoization faster than plain recursion for Fibonacci?
Memoization stores each solved index, reducing repeated Fibonacci work from exponential recursion to O(n) computed states. A loop also takes O(n) time and avoids recursive calls.
Why does a Fibonacci program need n + 1 table entries?
With zero-based indexing, calculating F(n) accesses positions 0 through n inclusive, which is n + 1 entries.
How much space does dynamic programming use for Fibonacci?
A full table uses O(n) extra space. Keeping only the previous two values uses O(1) extra space when earlier terms are not needed.




