Switch to full style
C++ code examples
Post a reply

solving fibonacci sequence recursively

Wed Jan 23, 2013 4:30 pm

solving fibonacci sequence recursively using C++ implementation
cpp code
#include <iostream>
#include <iomanip>
using namespace std;

//function declaration
double fibonacci(unsigned int n);

int main()
{
int n;

cout << "Enter a number: ";
cin >> n;

//An 'If' condition to prevent the user from entering -ve integers
if (n<0)
cout << "Please Enter a positive integer!" << endl;
else
cout << "The fibonacci number is " << fibonacci(n) << endl;

cout << "The fibonacci sequence is as follows:" << endl;

//Print Table Heading
cout << setw(10) << "n" << setw(10) << " | " << setw(10) << "F(n)" << endl;
cout << "-----------------------------------------" << endl;

//A Loop to print fibonacci numbers until 'n' in a tabular form
for(int i=0;i<=n;i++)
cout << setw(10) << i << setw(10) << " | " << setw(10) << fibonacci(i) << endl;

return 0;
}

//function definition
double fibonacci(unsigned int n)
{
//See what 'n' is
switch(n)
{
//If n=0 F(n)=0
case 0:
return 0;
break;

//if n=1 F(n)=1
case 1:
return 1;
break;

//Otherwise solve recursively
default:
return fibonacci(n-1)+fibonacci(n-2);
break;
}
}




Post a reply
  Related Posts  to : solving fibonacci sequence recursively
 Implementing fibonacci sequence problem using iterations     -  
 Merge two or more arrays recursively     -  
 recursively calculating factorial     -  
 Fibonacci vs factorial     -  
 Fibonacci iterative     -  
 Solving the Tower of Hanoi problem using C++     -  
 Sequence Generator JPA     -  
 add sequence of decimal numbers     -  
 solving dojox/mobile/Heading moveTo function bug issue     -  
 simple Ajax library solving back button and bookmarks     -