October 07 2017 0Comment

Fibonacci Series in C++

(Last Updated On: October 15, 2017)

Fibonacci Series in C++:

The series in which  next number is always the sum of previous two numbers for example 0, 1, 1, 2, 3, 5, 8, 13, 21 etc. Fabonacci series always start with 0,1 then we add later numbers so first two numbers of fabonacci series will be 0,1

Fibonacci program can be written with  and without recursion.

Fibonacci series without recursion in C++

  1. #include <iostream>
  2. using namespace std;
  3. int main() {
  4.   int a=0, b=1, c , i, input;
  5.  cout<<“Please Enter the Length of series “;
  6.  cin>>input;
  7.  cout<<a<<” “<<b<<” “//printing 0 and 1  
  8.  for(i=2;i<input;++i) //loop starts from 2 because 0 and 1 are already printed  
  9.  {
  10.  c=a+b;
  11.   cout<<c<<” “;
  12.   a=b;
  13.   b=c;
  14.  }
  15.    return 0;
  16.    }

 

Fibonnaci series using recursion in C++

 

  1. #include<iostream>
  2. using namespace std;
  3. void printFibonacci(int n){
  4. static int a=0, b=1, c;
  5. if(n>0){
  6. c = a + b;
  7. a = b;
  8. b = c;
  9. cout<<c<<” “;
  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. }

naveed120ciit_opecvcraze

Write a Reply or Comment