How does the recursion here work?

Posted by David on Stack Overflow See other posts from Stack Overflow or by David
Published on 2010-03-09T05:14:43Z Indexed on 2010/03/09 5:21 UTC
Read the original article Hit count: 572

Filed under:
|
|
|

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 n>0 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? `

© Stack Overflow or respective owner

Related posts about recursion

Related posts about help