A Fibbonacci sequence is one that sums the result of a number when added to the previous result starting with 1.
so.. 1 + 1 = 2
2 + 3 = 5
3 + 5 = 8
5 + 8 = 13
8 + 13 = 21
Once we understand what Fibbonacci is, we can begin to break down the code.
public int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
The first if statment checks for a base case, where the loop can break out. The else if statement below that is doing the same, but it could be re-written like so...
public int fibonacci(int n) {
if(n < 2)
return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
Now that a base case is establish we have to understand the call stack.Your first call to "fibonacci" will be the last to resolve on the stack (sequence of calls) as they resolve in the reverse order from which they were called. The last method called resolves first, then the last to be called before that one and so on...
So, all the calls are made first before anything is "calculated" with those results. With an input of 8 we expect an output of 21 (see table above).
fibonacci(n - 1) keeps being called until it reaches the base case, then fibonacci(n - 2) is called until it reaches the base case. When the stack starts summing the result in reverse order, the result will be like so...
1 + 1 = 1 ---- last call of the stack (hits a base case).
2 + 1 = 3 ---- Next level of the stack (resolving backwards).
2 + 3 = 5 ---- Next level of the stack (continuing to resolve).
They keep bubbling (resolving backwards) up until the correct sum is returned to the first call in the stack and that's how you get your answer.
Having said that, this algorithm is very inefficient because it calculates the same result for each branch the code splits into. A much better approach is a "bottom up" one where no Memoization (caching) or recursion (deep call stack) is required.
Like so...
static int BottomUpFib(int current)
{
if (current < 2) return current;
int fib = 1;
int last = 1;
for (int i = 2; i < current; i++)
{
int temp = fib;
fib += last;
last = temp;
}
return fib;
}