Andrea La Grotteria - 10 months ago 56

Java Question

I'm currently learning Java and I've just beginned so my knowledge of it is not very good.

I have a problem with a program I wrote that calculates the first 100 values of the Fibonacci sequence. The point is that it just outputs the 2 and no other number.

This is the code of my program:

`class MyClass1 {`

public static void main(String[ ] args) {

int[] fib = new int[102];

fib[0] = 1;

fib[1] = 1;

int counter = 0;

int n1, n2, fibSum;

while(counter < (fib.length - 2)){

n1 = fib[counter];

System.out.println(fib[counter]);

counter++;

n2 = fib[counter];

System.out.println(n2);

counter++;

fibSum = n1 + n2;

System.out.println(fibSum);

fib[counter] = fibSum;

}

}

}

Thank you for your help.

Answer Source

There are some logical errors in your code.

First loop:-

Initially n1=fib[0]=1 and n2=fib[1]=1 and you print both. fib[2] is the sum and so it is 2. So far so good.

Second loop:-

n1 = fib[2] = 2. n2 = fib[3] = 0 and hence fib[4] = 2. This is where the problem happens. Hence you will always see 2 0 2 in the output from second loop onwards.

For Fibonacci sequence, you need to add the previous 2 values but you are only considering the previous value in your code. Here's a corrected version of your code:-

```
public static void main(String[ ] args) {
double[] fib = new double[100];
fib[0] = 1;
fib[1] = 1;
int counter = 2;
double n1, n2, fibSum;
System.out.println(fib[0]);
System.out.println(fib[1]);
while(counter < fib.length){
n1 = fib[counter-1];
n2 = fib[counter-2];
fibSum = n1 + n2;
System.out.println(fibSum);
fib[counter] = fibSum;
counter++;
}
}
```

Note that I am using type double because type int or even long is not enough for going upto the 100th term in this sequence.