First your method won’t print the good fibonnaci numbers, and to print it you need to instanciate a FibonacciSequence
Object
since the method is not static
:
public int fibonacci(int numArray[]) {
for (int i = 1; i < numArray.length - 1; i++) {
System.out.print(numArray[i] + numArray[i - 1] + " ");
}
return numArray[10];
}
public static void main(String[] args) {
FibonacciSequence fbs = new FibonacciSequence();
fbs.fibonacci(new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
}
Prints : 1 3 5 7 9 11 13 15 17
If you don’t want to use recursion, you can do like this (and see how to print easily an array):
public int[] fibonacci(int size) {
int[] res = new int[size];
res[0] = 0;
res[1] = 1;
for (int i = 2; i < size; i++) {
res[i] = res[i - 1] + res[i - 2];
}
return res;
}
public static void main(String[] args) {
FibonacciSequence fbs = new FibonacciSequence();
int[] arrayREs = fbs.fibonacci(10);
System.out.println(Arrays.toString(arrayREs));
}
Prints : [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]