In this C++ tutorial, you will learn how to generate and print the Fibonacci series using while, do-while, and for loops. You will also see function-based, recursive, and memory-efficient approaches, along with the recurrence relation that defines Fibonacci numbers.
How the Fibonacci Series Works in C++
In the Fibonacci series, each number after the first two is the sum of the two numbers immediately before it. In this tutorial, we use the common programming convention that starts the sequence with 0 and 1.
0 1 1 2 3 5 8 13 21 34 55 89 144
The first 13 terms shown above are obtained by repeatedly adding the previous two terms. For example, 0 + 1 = 1, then 1 + 1 = 2, then 1 + 2 = 3.
Using Fibonacci notation, the sequence can be defined as F(0) = 0, F(1) = 1, and for later terms:
F(n) = F(n - 1) + F(n - 2), for n >= 2
Algorithm to Generate Fibonacci Series
You can use following algorithm to generate a Fibonacci Series using looping technique.
- Choose the number of Fibonacci terms to generate and store it in
n. - Start the sequence with
0and1. - For each later position, add the two preceding Fibonacci values.
- Store or print the new value, depending on whether the complete sequence is needed later.
- Repeat until
nterms have been generated.
The same idea can also be implemented without storing the entire series. If only the next Fibonacci number is needed, keeping the previous two values is enough.
Fibonacci Series in C++ Using While Loop
In the following program, we shall use C++ While Loop to generate Fibonacci Series.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 10;
int fibo[n];
//generate fibonacci series
int index = 0;
while (index < n) {
if (index == 0)
fibo[index] = 0;
else if (index == 1)
fibo[index] = 1;
else
fibo[index] = fibo[index - 1] + fibo[index - 2];
index++;
}
//print fibonacci series
for (int i = 0; i < n; i++)
cout << fibo[i] << " ";
}
Output
0 1 1 2 3 5 8 13 21 34
The loop starts with index = 0. The first two array elements are assigned 0 and 1. Every later element is calculated from the two preceding elements.
Fibonacci Series in C++ Using Do-while Loop
In the following program, we shall use C++ Do-while Loop to generate Fibonacci Series.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 15;
int fibo[n];
//generate fibonacci series
int index = 0;
do {
if (index == 0)
fibo[index] = 0;
else if (index == 1)
fibo[index] = 1;
else
fibo[index] = fibo[index - 1] + fibo[index - 2];
index++;
} while (index < n);
//print fibonacci series
for (int i = 0; i < n; i++)
cout << fibo[i] << " ";
}
Output
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
A do-while loop executes its body before checking its condition. In this example, n is positive, so the loop generates all 15 requested terms. When adapting this pattern to user input, validate that the requested number of terms is greater than zero before entering a do-while loop.
Fibonacci Series in C++ Using For Loop
In the following program, we shall use C++ For Loop to generate Fibonacci Series.
C++ Program
#include <iostream>
using namespace std;
int main() {
int n = 10;
int fibo[n];
//generate fibonacci series
for (int index = 0; index < n; index++) {
if (index == 0)
fibo[index] = 0;
else if (index == 1)
fibo[index] = 1;
else
fibo[index] = fibo[index - 1] + fibo[index - 2];
}
//print fibonacci series
for (int i = 0; i < n; i++)
cout << fibo[i] << " ";
}
Output
0 1 1 2 3 5 8 13 21 34
A for loop is a compact choice when the number of terms is already known. The initialization, condition, and increment for the index are kept in one place.
Fibonacci Series in Standard C++ Using std::vector
The earlier examples use an array whose size is given by n. Variable-length built-in arrays are not part of standard C++. For portable C++ code when the size is known only at run time, use a container such as std::vector.
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n = 10;
vector<long long> fibo(n);
if (n > 0)
fibo[0] = 0;
if (n > 1)
fibo[1] = 1;
for (int i = 2; i < n; i++)
fibo[i] = fibo[i - 1] + fibo[i - 2];
for (long long value : fibo)
cout << value << " ";
}
Output
0 1 1 2 3 5 8 13 21 34
This version also handles n = 1 correctly because it checks the vector size before assigning the second starting value.
Fibonacci Series in C++ Without Recursion or an Array
If the goal is only to print the series, there is no need to store every Fibonacci number. Keep two variables for the previous terms, calculate the next term, and update the pair on each iteration.
#include <iostream>
using namespace std;
int main() {
int n = 10;
long long first = 0;
long long second = 1;
for (int i = 0; i < n; i++) {
cout << first << " ";
long long next = first + second;
first = second;
second = next;
}
}
Output
0 1 1 2 3 5 8 13 21 34
This iterative approach uses constant extra space because the program keeps only first, second, and next, rather than an array containing all generated terms.
Fibonacci Series in C++ Using a Function
When Fibonacci generation is needed from more than one place in a program, the loop can be placed in a function. The function below prints the requested number of terms without recursion.
#include <iostream>
using namespace std;
void printFibonacci(int n) {
long long first = 0;
long long second = 1;
for (int i = 0; i < n; i++) {
cout << first << " ";
long long next = first + second;
first = second;
second = next;
}
}
int main() {
printFibonacci(10);
}
Output
0 1 1 2 3 5 8 13 21 34
Fibonacci Number in C++ Using Recursion
The recurrence relation can be translated directly into a recursive function. The base cases return 0 for n = 0 and 1 for n = 1. Every later call returns the sum of the two preceding Fibonacci numbers.
#include <iostream>
using namespace std;
long long fibonacci(int n) {
if (n == 0)
return 0;
if (n == 1)
return 1;
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
for (int i = 0; i < 10; i++)
cout << fibonacci(i) << " ";
}
Output
0 1 1 2 3 5 8 13 21 34
This recursive version closely matches the mathematical definition, but it recalculates the same smaller Fibonacci numbers many times. For generating a sequence of many terms, the iterative loop is generally more efficient.
Fibonacci in C++ with Dynamic Programming
A dynamic-programming approach stores previously calculated Fibonacci values so that each term is computed once. The std::vector example above is a bottom-up form of dynamic programming: it begins with the base values and builds later values from them.
For generating n terms, both the vector-based method and the two-variable iterative method perform a linear number of additions. The vector keeps all terms for later access, while the two-variable version uses less extra memory when earlier terms do not need to be retained.
Common C++ Fibonacci Series Mistakes
- Using the wrong starting values: this tutorial uses
0, 1, so the next value must be1. - Updating variables in the wrong order: calculate
next = first + secondbefore replacingfirstandsecond. - Accessing array positions before they exist: assign the base values before using
fibo[i - 1]andfibo[i - 2]. - Ignoring small input values: code that stores the sequence should handle
n = 0andn = 1before writing two starting elements. - Using a run-time-sized built-in array as portable C++: use
std::vectorwhen the size is determined at run time. - Expecting a fixed-width integer type to hold unlimited Fibonacci numbers: Fibonacci values grow quickly, so sufficiently large terms can overflow ordinary integer types.
Choosing a C++ Fibonacci Approach
| Approach | Useful when | Extra storage |
|---|---|---|
| While / for loop with array or vector | You need to keep all generated terms | Grows with the number of terms |
| Two-variable iterative loop | You only need to print terms or keep the latest values | Constant |
| Function with iteration | You want reusable Fibonacci-generation logic | Constant when no sequence container is stored |
| Simple recursion | You are demonstrating the recurrence relation | Uses recursive call stack and repeats calculations |
| Dynamic programming | You want to reuse previously computed terms | Depends on whether all terms are stored |
C++ Fibonacci Series Summary
A Fibonacci sequence starting with 0 and 1 generates each later term by adding the previous two. In C++, this can be implemented with while, do-while, or for loops, with a reusable function, or with recursion. For portable code with a run-time sequence size, std::vector is preferable to a variable-length built-in array. When the full sequence does not need to be stored, two variables are enough to generate the terms iteratively.
In this C++ Tutorial, we learned how to generate a Fibonacci series using looping techniques in C++.
TutorialKart.com