EDIT: @Putnam: your one will infinite loop if n < 0, so you need to either check for that or check "n<=0" instead of "n==0".
Also, because of branch prediction you should always put the most likely option at the top of your "if-else" or repeated "if" statements. This is because the compiler can't possibly know the "use-cases", i.e. the likely input values you plan to pump into your function. Maybe 99% of the inputs are zero, or maybe they're all very large numbers. Only the human designer can work that out. So it can't optimize for the order to do the tests.
Since processing a large positive number is the worst-case scenario for fibonacci, then the check for >1 should be first. This will minimize the number of CPU cycles needed to get your value. For fibonacci(1000000), the checks for n==0 and n==1 would happen for each of those, leading to 2 million comparisons, vs 1 million if you did an n>1 check first.
Tried messing with recursion in C++ after reading about it in a book about AI stuff. Tried making a program that used a recursive function call to calculate to a certain point in the fibonacci sequence before printing the resulting number. Couldn't work it out, but on the bright side I know a bit on how vectors work now.
Anyone more experienced willing to provide an example of how they'd program this?
Write out the desired function first:
f(n) = f(n-1) + f(n-2)
set some special rules for edge cases
f(0) = 1
f(1) = 1
this is the information you need to build your recursive function:
int fibonacci(int n)
{
if(n>1)
return fibonacci(n-1) + fibonacci(n-2);
else if(n==1)
return n;
else
return 0;
}
Done, and done.