Traversing 2D Arrays

  • When traversing through, or looping through 1D arrays, we only need to use one loop to access every element in the array.
  • This is different in 2D arrays, where we need to use a loop inside of a loop, otherwise known as a for loop
  • Java for loop structure review: ```java for(first execution; condition; executed after every loop) { //Action }

ex. for(i = 0; i < 5; i++) { System.out.println(i); }

Prints out 0 1 2 3 4

(Remember base 0)


- How can we use these to traverse through 1D arrays?


Lets say we have an array, Array1...


```java
// Set variable i to 0, while i is less than the length of Array1, print the value of Array1[i], add 1 to i
int[] Array1 = {1, 2, 3};
for(int i = 0; i < Array1.length; i++){
    System.out.println(myArray[i]);
}
  • What about 2D arrays?
    // Create an array of integers with 2 rows, 3 columns
    int[][] Array1 = {
      {1,2,3},
      {4,5,6}
    };
    // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
    for(int i = 0; i < Array1.length; i++){
    // Set variable i1 to 0, while i is less than the length of the array within Array1 at Array1[i], print the value of Array1[i][i1], add 1 to i1
      for(int i1 = 0; i1 < Array1[i].length; i1++){
          System.out.println(Array1[i][i1]);
      }
    }
    

Put in simpler terms?

For every row, loop through the row x number of times, x being the length of the array, print each individual value. So this code, without the loops, would be:

System.out.println(Array1[0][0])
System.out.println(Array1[0][1])
System.out.println(Array1[0][2])
// Keeping in mind base 0 system, and that Array1 has 3 columns for each row
// Move on to the next row
System.out.println(Array1[1][0])
System.out.println(Array1[1][1])
System.out.println(Array1[1][2])
// Again, keeping in mind that Array1 has 2 rows, and base 0 system, so "1st row" is actually 2nd put in plain english

Lets try!

public class Main {
    public static void main(String[] args) {
        int[][] Array1 = {
            {1,2,3},
            {4,5,6}
        };
        // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
        for(int i = 0; i < Array1.length; i++){
        System.out.println("Row " + (i+1) + ", or " + i);
        // Set variable i1 to 0, while i is less than the length of the array within Array1 at Array1[i], print the value of Array1[i][i1], add 1 to i1
            for(int i1 = 0; i1 < Array1[i].length; i1++){
                System.out.println(Array1[i][i1]);
            }
        }
    }
}


Main.main(null)

Row 1, or 0
1
2
3
Row 2, or 1
4
5
6

Popcorn Hack

Let’s say you have an array Numbers[][] defined as:

int Numbers[][] = {
    {1,2,3},
    {4,5,6},
    {7,8,9},
};

Loop through it until you reached a certain number of your choice, then print the value and position

public class Main {
    public static void main(String[] args) {
        int[][] Numbers = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };

        int target = 5;
    
       for(int i=0;i<Numbers.length;i++)
       {
        for(int j=0;j<Numbers[i].length;j++)
        {
            if(Numbers[i][j] == target)
            {
                System.out.println("Target Found");
                System.out.println(target);
                System.out.println("Position X: " + String.valueOf(j) + " Position Y: " + String.valueOf(i));
            }
        }
       }

    }
}


Main.main(null)

Target Found
5
Position X: 1 Position Y: 1

Example output: 9 is at row 3 column 3

What if you want to go column-first?

Introducing: Column Major Order, as an alternative to Row Major Order

Put simply, all you have to do is reverse the order of the loops, and keep the insides intact, and use the length of a row for the number of times to loop instead of the length of a column.

Why/how does this work?

Now instead of looping once for every row by taking the number of elements in the array, which defines how many rows there, we instead loop once for every element in each element in the array, (ex. an array with an element {1, 2, 3} would loop 3 times) which defines how many columns there are. Then, we print out the value from the chosen column, represented by i1, and then increment the row value, i, to finish out the rest of the column. Then, i1, the column value, is incremented, and the value repeats. We reverse the order of the loops so that the column is prioritized, and make the changes accordingly.

public class Main {
    public static void main(String[] args) {
        int[][] Array1 = {
            {1,2,3},
            {4,5,6}
        };
        // Set variable i to 0, while i is less than the length of Array1, proceed to the next for loop, add 1 to i
        for(int i1 = 0; i1 < Array1[0].length; i1++){
            System.out.println("Column " + (i1+1));
            for(int i = 0; i < Array1.length; i++){
                System.out.println(Array1[i][i1]);
            }
        }
    }
}


Main.main(null)
Column 1
1
4
Column 2
2
5
Column 3
3
6