Search Your Topic

config
Thursday, 22 June 2017 12:41

Fibonacci Series in C++

Written by
Rate this item
(0 votes)

Fibonacci Series in C++: In case of fibonacci series, next number is the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. The first two numbers of fibonacci series are 0 and 1.

There are two ways to write the fibonacci series program:

  • Fibonacci Series without recursion
  • Fibonacci Series using recursion

Fibonaccci Series in C++ without Recursion

Let's see the fibonacci series program in C++ without recursion.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. int main() {  
  4.   int n1=0,n2=1,n3,i,number;    
  5.  cout<<"Enter the number of elements: ";    
  6.  cin>>number;    
  7.  cout<<n1<<" "<<n2<<" "//printing 0 and 1    
  8.  for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed    
  9.  {    
  10.   n3=n1+n2;    
  11.   cout<<n3<<" ";    
  12.   n1=n2;    
  13.   n2=n3;    
  14.  }    
  15.    return 0;  
  16.    }  

Output:Enter the number of elements: 10

0 1 1 2 3 5 8 13 21 34 

Fibonnaci series using recursion in C++

Let's see the fibonacci series program in C++ using recursion.

 
  1. #include<iostream>    
  2. using namespace std;      
  3. void printFibonacci(int n){    
  4.     static int n1=0, n2=1, n3;    
  5.     if(n>0){    
  6.          n3 = n1 + n2;    
  7.          n1 = n2;    
  8.          n2 = n3;    
  9.  cout<<n3<<" ";    
  10.          printFibonacci(n-1);    
  11.     }    
  12. }    
  13. int main(){    
  14.     int n;    
  15.     cout<<"Enter the number of elements: ";    
  16.     cin>>n;    
  17.     cout<<"Fibonacci Series: ";    
  18.     cout<<"0 "<<"1 ";  
  19.     printFibonacci(n-2);  //n-2 because 2 numbers are already printed    
  20.      return 0;  
  21. }  

Output:

Enter the number of elements: 15 
 Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Read 185 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.