Order of execution of a nested for loop in Java

1.3k Views Asked by At

With a working solution found, I am trying to understand why my solution does not work. I have added the minimal working example (MWE), at first I show the working solution, then I show an attempted solution at 1. and at 2. I am printing all elements of the array manually, and then again in the for loop.

From that I conclude that the outer for loop (with counter i) is evaluated first and then after that the inner for loop (with counter q) is evaluated. I am confused and was wondering whether my understanding of the evaluation order of Java's for loops is incorrect, or whether I have a syntax/different error that I am missing.

Question: Could anyone suggest a reason for the order of evaluation of for loops?

public class LearnMultiDimensionalArrayLength {

    public static void main(String[] args) {
        // Generate array
        double[][] a = {{1.5, -10.3, 0}, {-2.5, 8, 1.3}};
        // call method that loops through the array
        forloops(a);
    }

    public static void forloops(double[][] a) {
        // Working solution:
        //loops through all elements of the array and prints their values.
        for (double[] x : a)
        {
           for (double y : x)
           {
                System.out.print(y + " ");
           }
           System.out.println();
        }

        // Now I tried my own solution:
        System.out.println("The first dimension length: "+ a.length + 
            " The second dim. length: " + a[1].length);
        System.out.println("first dim-1 ="+  (a.length -1));
        System.out.println("Second dim-1 ="+  (a[1].length -1));

        // Question to self: Why is the following for loop wrong?
        // for (int i=0;i <= a.length;i++){
        //   for (int q=0;q <= a[1].length;i++){
        //     System.out.println("["+i+"]"+"["+q+"]"+"="+a[i][q]);
        //   }
        // }

        // 1. Attempted Answer: Because the lengths are the nr of rows 
        // and nr of columns in the matrix. so with n = 2, there are only the elements
        // 0 and 1 in the first []
        // Test hypotheses by looping through the array a with length-1:

        // for (int i=0;i <= a.length-1;i++){
        //   for (int q=0;q <= a[1].length-1;i++){
        //     System.out.println("["+i+"]"+"["+q+"]"+"="+a[i][q]);
        //   }
        // }

        // Conclusion, that did solve the problem. 
        // 2. Attempt: Print all elements and their values, then compare
        // with what the for loop does:

        System.out.println("a[0][0]="+a[0][0]);
        System.out.println("a[0][1]="+a[0][1]);
        System.out.println("a[0][2]="+a[0][2]);
        System.out.println("a[1][0]="+a[1][0]);
        System.out.println("a[1][1]="+a[1][1]);
        System.out.println("a[1][2]="+a[1][2]);
        // System.out.println("a[2][0]="+a[2][0]);
        // System.out.println("a[2][1]="+a[2][1]);
        // System.out.println("a[2][2]="+a[2][2]);

        // 2.a Troubleshooting: verify the upper bound of the for loops
        // are not producing an error due to differences in types:
        System.out.println(((Object)1).getClass().getName());
        System.out.println(((Object)a[1].length).getClass().getName());
        System.out.println(((Object)(a[1].length-1)).getClass().getName());

       // All expressions are evaluated as integer, both i and q are integers
       // hence the different types should not result in a false negative.

        // The actual problematic for loop:
        System.out.println("Boolean evaluation:" + (1 == (a.length-1)));
        for (int i=0; (i <= (a.length-1));i++){
            for (int q=0; (q <= (a[1].length-1));i++){
                //System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]);
                System.out.println("This is the wrong order of for loops" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]);
            }
        }
    }
}
2

There are 2 best solutions below

1
On BEST ANSWER

Why don't you run this piece of code and try to understand how it works... Once you do, play around (change the values) and see what happens

public static void main(String arg[]) {
  for(int i=0;i<10;i++) {
    System.out.println("Inside the Fist loop "+i);
    for(int j=0;j<10;j++) {
      System.out.println("Inside the second loop "+j);
    }
  }
}
0
On

Thank you for the quick responses, as @azurefrog pointed out, I had a copy-paste error in the counter of q, therefore, it kept increasing i for the inner loop, yielding an out of bounds error on the row/column that the outer loop should be iterating through.

This contains the corrected code (with the out of bounds error in the second for-loop since the rows and columns have different lengths and are reversed as in the original question). I apologize.

public class SolvedMultiDimensionalArrayLength {

    public static void main(String[] args) {
        // Generate array
        double[][] a = {{1.5, -10.3, 0}, {-2.5, 8, 1.3}};
        // call method that loops through the array
        forloops(a);
    }

    public static void forloops(double[][] a) {     
        // Reversed with the intended order:
        for (int i=0; (i <= (a.length-1));i++){
            for (int q=0; (q <= (a[1].length-1));q++){
                System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]);
                //System.out.println("This is the wrong order of for loops" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]);
            }
        }
        // The actual solution for loop:
        for (int i=0; (i <= (a.length-1));i++){
            for (int q=0; (q <= (a[1].length-1));q++){
                //System.out.println("retry" + "[i="+i+"]"+"[q="+q+"]"+"="+a[i][q]);
                System.out.println("This was the reversed order, with corrected counter" + "[q="+q+"]"+"[i="+i+"]"+"="+a[q][i]); 
                //error here, since a.length is shorter than a[1].length, and the columns and rows are reversed.

            }
        }

    }
}