Monday, 9 September 2013

Simple Java Fibonacci code issue

Simple Java Fibonacci code issue

import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
int count;
Scanner in = new Scanner(System.in);
System.out.println("Please enter number");
count = in.nextInt();
int[] fib = new int [count];
fib[0] = 1;
fib[1] = 1;
for (int i=2; i < count; i++){
fib[i] = fib[i-1] + fib[i-2];
}
for(int i=0; i < count; i++){
System.out.print(fib[i] + " ");
}
}
}
This is my very simple Fib program, what i cant figure out is why it
always stops one number short. For example:
run: Please enter number 6 1 1 2 3 5 8 BUILD SUCCESSFUL (total time: 5
seconds)
run: Please enter number 7 1 1 2 3 5 8 13 BUILD SUCCESSFUL (total time: 5
seconds)
I thought in my FOR loops it should be "(int i=2; i <= count;"
but when i put in greater than or equal to in both, or either FOR loop it
gives me an error
Any suggestions? i know its something easy i'm overlooking

No comments:

Post a Comment