Copyright © Programs ++
Design by Dzignine
Tuesday 6 March 2012

Fibonacci Series in C++

The Fibonacci series is a very popular series and has many applications in many fields from mathematics to biology.
The series is as follows : 1 1 2 3 5 8 13.....  There are also negafibonacci number series which are have negative value.
Now, observe carefully, we see that each number in the Fibonacci series is the sum of the preceding two number and here
lies the method to generate them using C++. Simply add the two preceeding numbers and store them inside an array.
for e.g to generate 1 1 2 3 5, simply,
add 1,1 --> 1+1 = 2, and store it.
then again add 2,1 --> 2+1 = 3 ,and store it.
and, finally add 3,2 --> 3+1 = 5 ,and store it.
The following program demonstrates the concept.
// Program to print a sequence of fibonacci series
#include <iostream>

int main()
{
     int max,i=0,j=0;
     int temp;
     int arr[50];
     // prompts the user to enter the limit
     std::cout<<" Numbers to generate (max 50) ? : ";
     std::cin>>max;
     // initializes first two indexes with 1
     arr[0] = 1;
     arr[1] = 1;
     for (i=0; i<max; i++)
     {
          temp = arr[i] + arr[i+1];
          j = i+2;
          arr[j] = temp;
     }
     std::cout<<std::endl;
     // to display the fibonacci series
     for (i=0; i<max; i++)
     {
          std::cout<<" "<<arr[i];
     }
     return 0;
} // end of main











There are a numbers of ways to generate Fibonacci series, for more information please visit
http://en.wikipedia.org/wiki/Fibonacci_number

Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better. 

1 comments:

Comment Here....