Wednesday, June 19, 2013

Implementing fibonacci series algorithm C++

Code below gives the recursive implementation of Fibonacci series algorithm.
The method Fibonacci finds the Fibonacci for the given number and we have printed out the Fibonacci series for the given number using the for loop in main method.


//Print the Fibonacci series

#include <iostream>
using namespace std;

int Fibonacci( int num )
{
    if (num <= 0 )
    {
        return 0;
    }

    if (num == 1 )
    {
        return 1;
    }

    return
(Fibonacci(num - 1) + Fibonacci(num - 2));
}

int _tmain(int argc, _TCHAR* argv[])
{
    int num = 10;
    //cin >> num;
    for(  int i = 0; i <= num; i++ )
    {
        cout << " " <<
Fibonacci(i) ;
    }
    cout << endl;
    return 0;

The out put of above method will be as below for  10 as input value. 


 0 1 1 2 3 5 8 13 21 34 55

No comments:

Post a Comment