Home > Back-end >  how do I print my array using enhanced loops
how do I print my array using enhanced loops

Time:10-11

So as my program runs, it does some calculations for the Fibonacci sequence. I can easily print these 20 Fibonacci sequences out in the for loop, but I just want to do the calculations to fill the Fib array up and do the printing out in an enhanced loop. How can I do this with an enhanced for loop?

public static void main(String[] args) {
                
        int[] Fib = new int[20];
        Fib[0] = 0;
        Fib[1] = 1;
        System.out.printf("%d %d", Fib[0], Fib[1]);
        for (int i = 2; i < Fib.length; i  ) {

            Fib[2] = Fib[0]   Fib[1];
            
            Fib[0] = Fib[1];
            Fib[1] = Fib[2];
            System.out.print(" " Fib[2]); 

            for (int x : Fib) {
                 x = Fib[2];
                System.out.print(" " x);;
            }

        }

    }

CodePudding user response:

Use your index i to calculate and print the elemnts of your array:

public static void main(String[] args) {
    int[] Fib = new int[20];
    Fib[0] = 0;
    Fib[1] = 1;
    for (int i = 2; i < Fib.length; i  ) {
        Fib[i] = Fib[i-1]   Fib[i-2];
    }

    for (int i : Fib) {
        System.out.print(i   " ");
    }
}

CodePudding user response:

Your code contains a few mistakes, and major are:

Fib[2] = Fib[0] Fib[1]; this should be Fib[i] = Fib[i - 1] Fib[i - 2];
Another mistake is nesting for loops. The enhanced for loop should be after the loop with index i.

int[] Fib = new int[20];
Fib[0] = 0;
Fib[1] = 1;

for (int i = 2; i < Fib.length; i  ) {
    Fib[i] = Fib[i - 1]   Fib[i - 2];
}

for (int number : Fib) {
    System.out.print(" "   number);
}

You can use Arrays.toString(Fib) instead of using a loop for printing the array.

  • Related