java - writing a method for fibonacci sequence -


i'm trying write loop calls method fibonacci , prints first 25 numbers in fibonacci sequence. problem i'm little confused how correctly.

i'm little confused when loop in run method calls fibonacci method values inside fibonacci method reset after reach pass of loop? example during first pass of loop = 0 , values int , int b change inside the fibonacci method. values inside fibonacci method reset on next pass of loop?

import acm.program.*;  public class fibonacci extends consoleprogram{ private void run(){    for(int = 0; <= 25; i++){     fibonacci(i);     println(fibonacci(i));    }   }  private int fibonacci(int n){    int n = 0;     int = 0;     int b = 1;     while (n < 25);     int c = + b;    = b;    b = c;       }    return(a);  } 

you're looping in two different places - run() , fibonacci(). 1 of these places should care loop, , other should care computing fibonacci(n).

what can remove loop fibonacci, , rely on loop on outside. also, we're going remove statement int n = 0, since shadows parameter you're passing in.

lastly, we're going create 2 new static variables a , b, values of preserved instance. if don't that, you'd have rely on either recursion or other methodology provide appropriate values of a , b.

i'm not entirely sure why need extend consoleprogram, i'll leave in now.

so, here's should like.

public class fibonacci extends consoleprogram {     static int = 0;     static int b = 1;      public void run() {         for(int = 0; <= 25; i++) {             // print call fibonacci(i) every iteration.         }     }      private int fibonacci(int n) {         int c = + b;         = b;         b = c;         return c;     } } 

Comments