Marios Ath
Marios Ath

Reputation: 638

Fibonacci program not working?

I'm trying to write a very simple Fibonacci sequence program.

import acm.program.*;
public class Fibonacci extends Program{
    public void run(){
        int i; 
        int fib1=1; 
        int fib2=0;
        int currentFib=0;
        int count = readInt("Until which Fibonacci number do you want to print? ");
        if(count>=0) println(0);
        if(count>=1) println(1);
        if (count>=2) {
            for (i=2; i<count; i++){
                currentFib = fib1+fib2;
                println(currentFib);
                fib1=fib2;
                fib2=currentFib;
            }
        }
    }
}

However,for some reason when I write a number in cmd the only results are 0 and 1. Is there something I'm doing wrong? I can't really tell, since I started learning java a few days ago.

Upvotes: 1

Views: 125

Answers (2)

Karthik Rocky
Karthik Rocky

Reputation: 176

Welcome to java world:-)

I see in your code, the value 0 and 1 is repeatedly assigned to fib1 and fib2.

Moreover where have you used your temp variable "I".

Better try doing these changes.

  1. Replace the variable "i" with "fib2" in forloop.

  2. Remove "currentfib" variable assignment. fib2 in forloop will be our "currentfib"

  3. Print the addition of "fib1+fib2" directly.
  4. Remove reassignment of "fib2" as well.

Upvotes: 0

Eran
Eran

Reputation: 393771

Change

    int fib1=1; 
    int fib2=0;

to

    int fib1=0; 
    int fib2=1;

Since fib1 should be initialized to fib(0) and fib2 should be initialized to fib(1).

Upvotes: 3

Related Questions