Welcome to the Grid: Mastering 2D Array Traversals

In the previous chapter, 2D Array Creation and Access, you learned that a 2D array is essentially an "array of arrays." Now, we are going to learn how to travel through those arrays to find, change, or analyze data. This process is called traversal.

Think of a 2D array like a movie theater. If you want to check every seat for lost popcorn, you could go row by row, checking every seat in the first row before moving to the second. Or, you could go aisle by aisle (column by column). In AP Computer Science A, you need to know exactly how to write the code for these different "paths."

The Nested Loop: Your Best Friend

To visit every element in a 2D array, we almost always use nested loops (one loop inside another). Because a 2D array has two dimensions—rows and columns—we need two loop variables to keep track of our "coordinates."

1. Row-Major Traversal

Row-major order is the most common way to traverse a 2D array. It means you visit every element in the first row (from left to right), then every element in the second row, and so on.

Here is the standard "recipe" for a row-major traversal using a rectangular 2D array named \( matrix \):

for (int r = 0; r < matrix.length; r++) {
    for (int c = 0; c < matrix[r].length; c++) {
        // Do something with matrix[r][c]
    }
}

Why this works:
• The outer loop variable \( r \) represents the row index. It goes from \( 0 \) up to \( matrix.length - 1 \).
• The inner loop variable \( c \) represents the column index. It goes from \( 0 \) up to \( matrix[r].length - 1 \).
• Because the row loop is on the outside, we finish an entire row of columns before the outer loop moves to the next row.

Quick Review: Remember that \( matrix.length \) gives you the number of rows, while \( matrix[0].length \) (or \( matrix[r].length \)) gives you the number of columns in that row.

2. Column-Major Traversal

Sometimes, you might want to process data column-major order. This means you go down the first column, then down the second column, and so on. This is useful for things like calculating the total score of a specific player if each column represents a different person.

To do this, we simply swap the loops:

for (int c = 0; c < matrix[0].length; c++) {
    for (int r = 0; r < matrix.length; r++) {
        // Do something with matrix[r][c]
    }
}

Don't worry if this seems tricky at first! Just remember: whichever loop is on the outside is the one that stays the same while the inside loop does all its work. If the column loop is outside, you are staying in "Column 0" while the row index \( r \) visits every floor of that column.

The Enhanced For-Loop (For-Each)

Just like with 1D arrays and ArrayLists, you can use the enhanced for-loop to traverse a 2D array. However, because a 2D array is an "array of arrays," the syntax looks a little different.

Imagine you have a 2D array of integers called \( grid \):

for (int[] row : grid) {
    for (int val : row) {
        System.out.print(val + " ");
    }
}

How to read this:
1. The outer loop says: "For every 1D array (which we'll call \( row \)) inside the 2D array \( grid \)..."
2. The inner loop says: "For every single integer (which we'll call \( val \)) inside that specific \( row \)..."

Important Note: Enhanced for-loops are great for accessing or searching data, but they cannot be used to modify (change) the primitive values in the array or to track specific index positions.

Common Mistakes to Avoid

The "Index Out Of Bounds" Trap:
Always double-check your loop boundaries. If your array has \( 3 \) rows, the indices are \( 0, 1, 2 \). If your loop tries to go to index \( 3 \), Java will throw an \( ArrayIndexOutOfBoundsException \). Always use \( < \) rather than \( <= \) when using \( .length \).

The Row/Column Flip:
In the expression \( matrix[r][c] \), the first bracket is always the row and the second bracket is always the column. A common mistake is writing \( matrix[c][r] \) by accident during a column-major traversal. Even if you change the order of the loops, the row index must still stay in the row bracket!

Summary and Key Takeaways

Key Takeaway 1: Row-major traversal (outer loop = rows, inner loop = columns) is the standard way to read 2D arrays in Java.

Key Takeaway 2: To visit every element, you need nested loops. The outer loop runs once for every row, and the inner loop runs for every column within that row.

Key Takeaway 3: An enhanced for-loop for a 2D array requires the outer loop to use an array type (e.g., \( int[] \)) because it is pulling out one "row" at a time.

Did you know?

Digital images are actually 2D arrays! Each "cell" in the array stores the color information for one pixel. When a program brightens a photo, it is performing a row-major traversal to visit every pixel and increase its brightness value.

Next Chapter: Implementing 2D Array Algorithms. We will take these traversal skills and use them to solve specific problems like finding the average of a grid or searching for a specific value!