How does the recursion here work?
- by David
code 1:
public static int fibonacci (int n){
if (n == 0 || n == 1) {
return 1;
} else {
return fibonacci (n-1) + fibonacci (n-2);
}
}
how can you use fibonacci if you haven't gotten done explaining what it is yet? I've been able to understand using recursion in other cases like this:
code two:
class two
{
public static void two (int n)
{
if (n>0)
{
System.out.println (n) ;
two (n-1) ;
}
else
{
return ;
}
}
public static void main (String[] arg)
{
two (12) ;
}
}
In the case of code 2 though n will eventualy reach a point at which it doesnt satisfy n0 and the method will stop calling itself recursivly. in the case of code 2 though i don't see how it would be able to get itself from 1 if n=1 was the starting point to 2 and 3 and 5 and so on. Also i don't see how the line `return fibonacci (n-1) + fibonacci (n-2) would work since fibbonacci n-2 has to contain in some sense fibonacci n-1 in order to wrok but it isn't there yet.
I know my question is worded poorly but looking at this is making my mind explode. the book i'm looking at says it will work.
how does it work? `