Program to print Fibonacci series in C++

 Program to print Fibonacci series in C++:

#include<iostream>
using namespace std;
int main()
{
int n,fib2;
int fib0=0,fib1=1;

cout<<"enter how many terms of Fibonacci you want : ";
cin>>n;
for(int i=0;i<=n;i++)
{
fib2=fib1+fib0;
fib0=fib1;
fib1=fib2;
cout<<fib2<<" ";
}
return 0;
}

output:

enter how many terms of Fibonacci you want : 8

1 2 3 5 8 13 21 34 55


or using WHILE LOOP :

#include<iostream>
using namespace std;
int main()
{
int t1=0,t2=1,nextterm,num,i=1;
cout<<"enter number of terms of fibonacci series to be displayed";
cin>>num;
while(nextterm<=num)
{
nextterm=t1+t2;
t1=t2;
t2=nextterm;
cout<<nextterm<<" ";
}
}

output:

enter how many terms of Fibonacci you want : 8

1 2 3 5 8 13 21 34 55

Comments