Skip to content
Advertisement

Java how to return an array with fibonacci values starting at 1?

I’m writing a void function fibFill which fills an array with Fibonacci numbers. It doesn’t have to return anything.

Here’s what I have so far:

void fibFill(int[] fibo) {
    fibo[0] = 1;
    fibo[1] = 1;
    for (int i = 2; i < fibo.length; i++) {
        fibo[i] = fibo[i - 1] + fibo[i - 2];
    }
    int pos(int position) {
        return fibo[pos];
    }
}

For example, if I pass an array of length 5 to the method, it will override the contents of the passed array like this: [1, 1, 2, 3, 5]

Advertisement

Answer

Your fibFill method shouldn’t have a pos method embedded in it; and I would make it static (so it can be called without an instance), like

static void fibFill(int[] fibo) {
    fibo[0] = 1;
    fibo[1] = 1;
    for (int i = 2; i < fibo.length; i++) {
        fibo[i] = fibo[i - 1] + fibo[i - 2];
    }
}

Then you can test it with something like

public static void main(String[] args) {
    int[] fib = new int[10];
    fibFill(fib);
    System.out.println(Arrays.toString(fib));
}

Which outputs (as requested) the fibonacci values starting at 1

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement