C++ Program to display Fibonacci Series
In this example, we will learn to print fibonacci series in C++ programming (up to nth term, and up to a certain number).
To understand this example, you should have the knowledge of the following C++ programming topics:
Fibonacci Series
The Fibonacci sequence is a series where the next term is the sum of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21
Example 1: Program to Display Fibonacci Series up to n number of terms.
// Prints the fibonacci-series using if statement inside for loop.
#include <iostream>
using namespace std;
int main()
{
int i, num, n1 = 0, n2 = 1, nextTerm;
// user enter how many terms he want's to diaplay
cout << "Enter the number of elements: ";
cin >> num;
cout << "Fibonacci Series: ";
cout << n1 <<" " << n2 <<" ";// prints 0 and 1
for (int i = 2; i < num; ++i)// loop starts from 2
{
// Prints the first two terms.
nextTerm = n1 + n2;
cout << nextTerm <<" ";
n1 = n2;
n2 = nextTerm;
}
return 0;
}
Output
Enter the number of terms: 5 Fibonacci Series: 0 1 1 2 3
Example 2: Program to Generate Fibonacci Sequence Up to a Certain Number
#include <iostream>
using namespace std;
int main()
{
int n1 = 0, n2 = 1, nextTerm = 0, num;
cout << "Enter a positive number: ";
cin >> num;
// displays the first two terms which is always 0 and 1
cout << "Fibonacci Series: " << n1 << ", " << n2 << ", ";
nextTerm = n1 + n2;
while(nextTerm <= num)
{
cout << nextTerm << " ";
n1 = n2;
n2 = nextTerm;
nextTerm = n1 + n2;
}
return 0;
}
Output
Enter a positive integer: 10 Fibonacci Series: 0 1 1 2 3 5 8
Next Example
We hope that this Example helped you develop better understanding of the concept of "Display Fibonacci Sequence" in C++.
Keep Learning : )
In the next Example, we will learn about C++ Program to Find GCD
.