Recursion Help (I don't get this)

I feel so stupid. I just can't understand recursion.

publicstaticint fib(int n)

{

int result;

if (n <=2)

{

result = 1;

}

else

{

result = fib(n-1) + fib(n-2);

}

return result;

}

The above is the famous Fibonacci method. But I DON'T GET IT. How the heck does this work? I don't understand how the recursive case works (result = fib(n-1) + fib(n-2)).

The way I understand it:

If we were to call call fib(5)...

recursive case:

result = fib(n-1) + fib(n-2); -> 4 + 3

The result would be 7, and then we would be done because we've reached the base case (n <=2). The correct answer is 5, so I'm obviously wrong. I just can't grasp this key concept. I'm feeling very noobish. :(

[1229 byte] By [Lava_Javaa] at [2007-11-26 18:11:45]
# 1
fib(5) = fib(n-1) + fib(n-2) //where n is 5= fib(4)+ fib(3)= (fib(m-1) + fib(m-2)) + (fib(p-1) + fib(p-2)) //where m is 4 and p is 3= (fib(3) + fib(2)) + (fib(2) + fib(1))= ((fib(2)+fib(1)) + 1) + (1 + 1)= ((1 + 1) + 1) + (1 + 1)= 5
DrLaszloJamfa at 2007-7-9 5:44:24 > top of Java-index,Java Essentials,New To Java...
# 2

I should add that recursion is related to [url=http://en.wikipedia.org/wiki/Mathematical_induction]mathematical induction[/url], a powerful tool in mathematics.

And once you get used to thinking about recursion, you should see that in many ways recursive solutions are simpler and clearer than non-recursive approaches.

DrLaszloJamfa at 2007-7-9 5:44:24 > top of Java-index,Java Essentials,New To Java...
# 3
THANKS! That really helps me! :)
Lava_Javaa at 2007-7-9 5:44:25 > top of Java-index,Java Essentials,New To Java...
# 4

> I should add that recursion is related to

> [url=http://en.wikipedia.org/wiki/Mathematical_induction]mathematical induction[/url], a powerful tool in

> mathematics.

>

> And once you get used to thinking about recursion,

> you should see that in many ways recursive solutions

> are simpler and clearer than non-recursive approaches.

Ever so true but an efficient recursive solution should use a stack of

depth log(n), where n is the problem size, at most. It should also not

recompute what has been computed before.

The naive recursive fibonacci function doesn't fit that bill: it uses a stack

of size n for the calculation of fib(n) and it recalculates what has been

calculated before many times.

kind regards,

Jos

JosAHa at 2007-7-9 5:44:25 > top of Java-index,Java Essentials,New To Java...
# 5
Jos,So true. But the OP is just learning to program. One thing at a time!
DrLaszloJamfa at 2007-7-9 5:44:25 > top of Java-index,Java Essentials,New To Java...
# 6
> Jos,> > So true. But the OP is just learning to program. One thing at a time!Sorry Squire, 't won't happen again; I'll leave now and go flog myself ;-)kind regards,Jos
JosAHa at 2007-7-9 5:44:25 > top of Java-index,Java Essentials,New To Java...