go to previous page   go to home page   go to next page

Answer:

The complete method is seen below.


Complete Fib

public int fib( int n )
{
  if ( n == 1 ) 
    return 1;
    
  else if  ( n == 2 ) 
    return 1;
    
  else
    return fib( n-1 ) + fib( n-2 );
}

It may worry you that the code for fib(int n) calls itself twice, in fib(n-1) and fib(n-2). This is fine. Look at the math-like definition. Play with it until you understand it. The program says the same thing but uses a different language (Java) to say it.

It is the job of the Java system to make sure that you get the computation that you ask for. All you have to do is ask for it correctly.


QUESTION 19:

Could you think about fib(n) dynamically?


go to previous page   go to home page   go to next page