Fibonacci series through recursion
fibonacciRecursive() calculates the fibonacci number of
the given number recursively.
For example,
If
the number is 0 then it will return 0,
If
the number is 1 then it will return 1,
If
the number is 2 then it will return 1,
If
the number is 3 then it will return 2,
If
the number is 4 then it will return 3,
If
the number is 5 then it will return 5,
If
the number is 6 then it will return 8,
If
the number is 7 then it will return 13,
If
the number is 8 then it will return 21,
If
the number is 9 then it will return 34.
Code of fibonacciRecursive()
unsigned long fibonacciRecursive( unsigned long number )
{
if ( number == 0 || number ==1 )
return number;
else
return fibonacciRecursive( number - 1 ) + fibonacciRecursive(
number - 2 );
}
Summary of fibonacciRecursive()
fibonacciRecursive() is a
recursive function with 2 parts;
first part is the base case –
if the number is equal to 0 or 1, then this function will return 1.
fibonacciRecursive(
0 ) = 1
fibonacciRecursive(
1 ) = 1
Second part consists of recursive
calls as mentioned below:
fibonacciRecursive(
number - 1 ) + fibonacciRecursive( number - 2 )
Example (C++)
#include "stdafx.h"
#include "iostream"
#include "iomanip"
#include "conio.h"
using namespace std;
unsigned long fibonacciRecursive( unsigned long number )
{
if ( number == 0 || number ==1 )
return number;
else
return fibonacciRecursive( number - 1 ) + fibonacciRecursive(
number - 2 );
}
int main()
{
for( unsigned long i = 0; i
< 10; i++ )
cout << fibonacciRecursive( i
) << setw(4) ;
cout << endl;
_getche();
return 0;
}
Output
0 1
1 2 3
5 8 13
21 34
0 comments:
Post a Comment