Introduction
The Fibonacci series is a series with a name based on an Italian scientist, and his name was Fibonacci. Series starts with zero(0) and one(1). Later series contains the sum of the previous two numbers in series. For example 0 1 1 2 3 5 8 …
Since the Fibonacci series contains two elements as 0 and 1 and then the sum of the previous two consecutive up to which the user wants. So printing can be accomplished by using loops.
In this blog, we will learn different ways to print the Fibonacci series in the c++ programming language.
Program to print upto nth terms
Using for loop
#include <iostream>
using namespace std;
int main()
{
cout<<"Fibonacci series upto 10 terms :- "<<endl;
int a = 0, b = 1;
int next;
for(int i=0; i<10; i++)
{
if(i==0) {
cout<<a<<" ";
continue;
}
else if(i==1)
{
cout<<b<<" ";
continue;
}
next = a + b;
a=b;
b=next;
cout<<next<<" ";
}
return 0;
}
Output:
Fibonacci series upto 10 terms :-
0 1 1 2 3 5 8 13 21 34
Time complexity of the above code is O(n) and space complexity is O(1).
The program will start from the main() function in the above code. Inside it first, the program asks the number of terms the user wants to enter. After taking the input in the 'num' variable, there are two variables, 'a' and 'b', which the first store initial value 0 and 1. The 'next' variable stores the sum of the previous two, i.e., values stored in variables a and b. For loop is used to move up to nth position and print values inside it.
The first and second iteration prints the value of a and b. The third iteration will assign the value of the 'next' variable, print it, and update the values of a and b, respectively.
Using while loop
#include <iostream>
using namespace std;
int main() {
int num=10,next,a=-1,b=1;
cout<<"Fibonacci series upto 10 terms :- "<<endl;
while(num>0)
{
next=a+b;
a=b;
b=next;
cout<<" "<<next;
num--;
}
}
Output:
Fibonacci series upto 10 terms :-
0 1 1 2 3 5 8 13 21 34
It is the same program as the previous program whose task is to print Fibonacci series instead of using for loop, while loop is used.
You practice by yourself with the help of online c++ compiler.