The Fibonacci operation using recursive function C++ program example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: The Fibonacci operation using recursive function C++ program example

To show: The recursive function, the function that call itself demonstrated through the Fibonacci operation in C++ programming

// demonstrates the recursive Fibonacci function the formula, fibonacci(n) = fibonacci(n-1)+fibonacci(n-2)

#include <iostream>

using namespace std;

// function prototype, required by standard

long fibonacci(long);

int main(void)

{

int p;

cout<<"A simple fibonacci using recursive function"<<endl;

cout<<" Calling itself lor!!!"<<endl;

cout<<"-----------------------------------------\n"<<endl;

// looping for 20 numbers. If you increase the iteration number, you may see the

// 'burden' that your computer faces to compute numbers

for(p = 0; p<40; p=p+2)

cout<<"Fibonacci("<<p<<") = "<<fibonacci(p)<<"\n";

return 0;

}

// recursive fibonacci function definition

long fibonacci(long number)

{

// for starting number 0, 1, fibonacci = number

if(number == 0 || number == 1)

return number;

// other number

else

// return and call itself

return (fibonacci(number-1) + fibonacci(number-2));

}

Output example:

A simple fibonacci using recursive function

Calling itself lor!!!

-----------------------------------------

Fibonacci(0) = 0

Fibonacci(2) = 1

Fibonacci(4) = 3

Fibonacci(6) = 8

Fibonacci(8) = 21

Fibonacci(10) = 55

Fibonacci(12) = 144

Fibonacci(14) = 377

Fibonacci(16) = 987

Fibonacci(18) = 2584

Fibonacci(20) = 6765

Fibonacci(22) = 17711

Fibonacci(24) = 46368

Fibonacci(26) = 121393

Fibonacci(28) = 317811

Fibonacci(30) = 832040

Fibonacci(32) = 2178309

Fibonacci(34) = 5702887

Fibonacci(36) = 14930352

Fibonacci(38) = 39088169

Press any key to continue . . .