CPP Fibonacci
CPP Fibonacci
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.
In this tutorial, we shall write C++ programs to generate Fibonacci series, and print them. We can use while
loop, do-while loop, and for loop to generate a Fibonacci Series.
You can use following algorithm to generate a Fibonacci Series using looping technique.
1. Start.
2. Take a variable n . We have to generate n items of Fibonacci series.
3. Create an Array fibo[] with the size of n .
4. Take index with initial value of zero.
5. Check if index is less than n . If false go to step 11.
6. If index is 0 , assign fib[index] with 0 . Go to step 9.
7. If index is 1 , assign fib[index] with 1 . Go to step 9.
8. Assign fibo[index] with the sum of previous two elements fibo[index-1] and fibo[index-
2] .
9. Increment index . Go to step 5.
10. Print fibo[] .
11. Stop.
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++;
}
Output
0 1 1 2 3 5 8 13 21 34
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];
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);
Output
Output
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];
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++.
C++ Tutorials
✦ C++ Tutorial
✦ C++ If Else
✦ C++ Switch
✦ C++ ForEach
✦ C++ Continue
✦ C++ Break
✦ C++ Comments
✦ C++ Recursion
✦ C++ Class
✦ C++ Programs