0

I'm trying to generate a code that will display the Fibonacci sequence using an array I did generate a code that has the right solution but I think it's too long since the instructor told us it's gonna be a maximum of 5 lines of code So here is the method :

public static void fibonacci_array_calc(int[] array) {
    int result;
    System.out.println("Fibonacci Series of " + array.length + " numbers: ");
    if (array.length == 0 || array.length == 1) {
        for(int i = 0;i < array.length; i++)
            System.out.print(array[i] + " ");
    } else {
        for (int i = 0; i <= 1; i++) {
            result = array[i] = i;
            System.out.print(result + " ");
            if (array[i] >= 1) {
                for (int j = 2; j < array.length; i++, j++) {
                    result = (array[j] = (array[i] + array[i - 1]));
                    System.out.print(result + " ");
                }
            }
        }
    }
}

the output is

Fibonacci Series of 10 numbers: 
0 1 1 2 3 5 8 13 21 34

it's not allowed to use the recursion technique is there any way to shorten this code?

2
  • You don't need the inner loop. You don't even need the array, actually, just the two previous results. Commented Oct 22, 2020 at 0:26
  • No, I need to use the array since it's required, but thanks anyway Commented Oct 22, 2020 at 2:43

1 Answer 1

1

You can greatly simplify your code by using a conditional assignment to array[i]. This assignment can then be used regardless of the length of the input array:

public static void fibonacci_array_calc(int[] array) {
    System.out.println("Fibonacci Series of " + array.length + " numbers: ");
    for (int i = 0; i < array.length; i++) {
        array[i] = i <= 1 ? i : array[i-2] + array[i-1];
        System.out.print(array[i] + " ");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.