Pages

Thursday 17 December 2015

Fibonacci series using C++



Fibonacci series:

The Fibonacci number series has first two numbers equal to $1$ and $0$. and next onwards each number is the addition of previous two numbers.

1st number = $0$
2nd number = $1$
3rd number = $0+1=1$
4th number = $1+1=2$
5th number = $1+2=3$
6th number = $2+3=5$
cont...

The fibonacci sequence is : $0,1,2,3,5,8,13,21, ...$





Algorithm:

  1. Start the program
  2. Read the range of sequence
  3. Initialize start to $0$ and next to $1$
  4. Get fibonacci number by adding the start with next
  5. Assign next to start
  6. Assign next to fibonacci 
  7. Stop the program when reach the desired range

#include "iostream"
    using namespace std;

    int main()
    {
     int range, start = 0, next = 1, fibonacci=0;
     cout<<"Enter the range for fibonacci sequence: ";
     cin >> range;
     cout<<"Fibonacci series upto "<<range<<"terms:"<<endl;
     for ( int c = 0 ; c < range ; c++ )
       {
          if ( c <= 1 )
             fibonacci = c;
          else
          {
             fibonacci = start + next;
             start = next;
             next = fibonacci;
          }
          cout<<fibonacci<<" ";
       }
       return 0;
    }


INPUT :      Enter the range for fibonacci sequence: 15
OUTPUT :  Fibonacci series upto 15 terms:
                    0 1 1 2 3 5 8 13 21 34 55 89 144 233 377


No comments:

Post a Comment