Your function is actually wrong, have a quick look at the actual Fibonacci sequence and you'll notice:
http://en.wikipedia.org/wiki/Fibonacci_number
The sequence is: 0, 1, 1, 2, 3, 5, 8 etc...
But since the topic is recursion and not necessarily this particular sequence I'll use your function, you should just know that it's incorrect.
The first part should be obvious:
1 2 3 4 5 6 7 8 9
|
if(terms == 1)
{
return 1;
}
else if (terms==2)
{
return 2;
}
|
If the argument is 1, return the first term, in your case 1.
if the argument is 2, return the second term which in your case is 2.
The last part is the interesting part, the actual recursion:
1 2 3 4
|
else
{
return fibanocci(terms-1)+fibanocci(terms-2);
}
|
Here you start calculating the term that was originally given as an argument to the function. This term is made out of its previous two terms, thus you call the function that calculates a specific term(i.d. your function) with argument that are one term before the original, and two terms before the original. What actually happens is it calls fibonacci(terms-1), this gets an argument that is one lower than the original(at first call). It will then try to calculate that term, exactly the same way you are calculating the original term. It keeps repeating this process untill it has reached either term==1 or term==2, so it return either 1 or 2. Then it has an actual value to work with and it can calculate fibonacci(term-1) + fibonacci(term-2) and return that value, filling up the entire chain.
I hope this makes some sense, I am by no means a teacher, just trying to explain my thought process.
What may help you understand this, is by taking a term, say 5, and just write out everything that happens in your function.