Two-Dimensional Arrays

AP Computer Science A · Unit 4 — Data Collections

An array of arrays

In Java a 2D array is really an array whose elements are arrays. For int[][] g = new int[3][4];:

g.length        →  3    number of ROWS
g[0].length     →  4    number of COLUMNS in row 0
g[r][c]         →  element at row r, column c

The first index is always the row. On the AP exam all 2D arrays are rectangular, so every row has the same length and g[0].length is a safe column count — but writing g[r].length in the inner loop is always correct and costs nothing.

Row-major traversal

for (int r = 0; r < g.length; r++) {
    for (int c = 0; c < g[r].length; c++) {
        System.out.print(g[r][c]);
    }
}

for (int[] row : g) {          // each row is an int[]
    for (int v : row) {        // each v is an int
        System.out.print(v);
    }
}

Swapping the two loop headers gives column-major order, which visits the same cells in a different order — the difference matters as soon as you print, or stop early.

int[][] g = new int[3][4]; g.length = 3 g[0].length = 4 hàng col 0 col 1 col 2 col 3 g[0][0] g[0][1] g[0][2] g[0][3] g[1][0] g[1][1] g[1][2] g[1][3] g[2][0] g[2][1] g[2][2] g[2][3] 0 1 2 row-major traversal: outer loop over rows, inner loop over columns g[row][col] — the FIRST index is the row, always
Reading the cell labels is enough to avoid mix-ups. All cells in the same row have the same first index; all cells in the same column have the same second index. When the question asks for “the sum of column 2”, the loop must run the row variable and keep the number 2 in the second position: g[r][2]. Writing g[2][c] by mistake adds up row 2 — both results are valid numbers, so nothing tells us we took the wrong one.

Worked example: sum of each column

Write a method that returns a one-dimensional array containing the sum of each column of the rectangular two-dimensional array int[][] g.

Solution

public static int[] tongCot(int[][] g) {
    int[] kq = new int[g[0].length];      // length equals the NUMBER OF COLUMNS
    for (int c = 0; c < g[0].length; c++) {
        for (int r = 0; r < g.length; r++) {
            kq[c] += g[r][c];
        }
    }
    return kq;
}

Three places to go wrong, handled one by one. One: the length of the result array is the number of columns g[0].length, not the number of rows — there are as many sums as there are columns. Two: inside, it must be g[r][c], keeping the row-column order even though the outer loop is running over columns. Three: a newly created kq is already filled with 0, so accumulating straight into it is safe, with no initializing assignment needed.

With {{1,2,3},{4,5,6},{7,8,9}} the method returns {12, 15, 18}.

Common mistake

The deadly trap of two-dimensional arrays is swapping the two indexes: writing g[c][r] instead of g[r][c]. With a square array it runs smoothly and returns a number that looks perfectly reasonable, so no one notices until grading. How to prevent it: name the loop variables r and c rather than using i and j — your eye will see g[c][r] as wrong immediately, but not g[j][i]. The second trap: using g.length as the number of columns. Remember one sentence — g.length counts rows; you need one more pair of square brackets to get the columns.

Key takeaway

The first index is the row, g.length is the number of rows, g[0].length is the number of columns. Row-major traversal is the default; swapping the two loops changes the order of visiting, not the set of cells visited.

← ArrayList and Safe Removal · All AP Computer Science A lessons · Practice AP Computer Science A questions (free, instant scoring) · Standard Algorithms: Searching, Sorting, Recursion →