I have a task where I should create fibonacci iterative using loop and array. How can I check negative values for fibonacciNumberInOrder? My tutor told me that I don't need allocate N elements in array. I can reduce it to 3element array. And I should point this array to last three numbers of fibonacci. Now I receive an error that: Index 3 out of bounds for length 3. I guess it's because I've change this:
long [] fibonacci = new long [fibonacciNumberInOrder];
to:
long [] fibonacci = new long [] {1,1,2};
What should I do to make it work and keep my tutor's requirements?
public class FibonacciIterative {
public static void main(String[] args) {
int fibonacciNumberInOrder = 5;
fibonacci(fibonacciNumberInOrder);
}
public static long[] fibonacci(int fibonacciNumberInOrder) {
long [] fibonacci = new long [] {1,1,2};
for (int i = 2; i < fibonacciNumberInOrder; i++) {
fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
System.out.print(Arrays.toString(fibonacci) + ", ");
}
return fibonacci;
}
}