In this C++ tutorial, you will learn how to write a C++ program to generate Fibonacci series, and print them. We will cover programs to generate Fibonacci series using While loop, Do-while loop, and For loop.
C++ Fibonacci Series
Fibonacci Series is a series in which the current element is equal to the sum of two immediate previous elements. Fibonacci series start with 0 and 1, and progresses.
Algorithm to Generate Fibonacci Series
You can use following algorithm to generate a Fibonacci Series using looping technique.
- Start.
- Take a variable
n
. We have to generaten
items of Fibonacci series. - Create an Array
fibo[]
with the size ofn
. - Take
index
with initial value of zero. - Check if
index
is less thann
. If false go to step 11. - If index is
0
, assign fib[index] with0
. Go to step 9. - If index is
1
, assign fib[index] with1
. Go to step 9. - Assign
fibo[index]
with the sum of previous two elementsfibo[index-1]
andfibo[index-2]
. - Increment
index
. Go to step 5. - Print
fibo[]
. - Stop.
Fibonacci Series 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
Fibonacci Series 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
Fibonacci Series 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
Conclusion
In this C++ Tutorial, we learned how to generate a Fibonacci series using looping techniques in C++.