Home coding C++ program to Display a Fibonacci Series in C++ .

C++ program to Display a Fibonacci Series in C++ .

0
131

Given a number we have to print fibonacci series of a number.

so what is fibonacci series?

In fibonacci series,next number is the sum of two previous number.

for example-0,1,1,2,3,5,8.

there are two way to print fibonacci series –

1-with recursion

2-without recursion.

Approach 1: With recursion

#include<iostream>
using namespace std;
int fibonacci(int n)
{
if(n == 0 || n == 1)
return n;
else
return(fibonacci(n-1) + fibonacci(n-2));
}
int main()
{
int n, m= 0, i;
cout<<"enter the terms"<<endl;
cin>>n;
cout<<"fibonnaci series are "<<endl;
for(i = 1; i <= n; i++)
{
cout<<fibonacci(m)<<" ";
m++;
}
return 0;
}

Output:

enter the terms:5
fibonnaci series are 
0 1 1 2 3 

2nd Approach (Without recursion)

#include<iostream>
using namespace std;
int main()    
{    
 int first=0,second=1,third;
 int num;
cout<<"enter the term "<<endl;
cin>>num;
cout<<first<<" "<<second<<" ";
 for(int i=2;i<num;++i) 
 {    
  third=first+second;    
 cout<<third<<" " ;  
  first =second;   
  second=third;
 }  
  return 0;  
 }  
enter the term : 5
0 1 1 2 3 

Time Complexity:0(n)

space Complexity:O(1)

NO COMMENTS

LEAVE A REPLY

Please enter your comment!
Please enter your name here