Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

8.2: 2D Array Traversal

A row-major traversal finishes one row before moving to the next. Bounds must match the dimension indexed by each loop variable.

College Board Unit 4

How it works

Row-major traversal puts the row loop outside and the column loop inside, visiting an entire row before moving down. Swapping the loops gives column-major order, which visits one column top to bottom before moving right. The enhanced form nests a loop over each row array inside a loop over the grid. Per-row work such as a row sum requires resetting the accumulator at the top of each outer iteration.

Name which loop controls rows before tracing, then count visits as the product of the bounds.

Common error

Swapping the indexes, which either transposes the result or throws when the array is not square.

Worked example

Java

int[][] grid = {{1,2},{3,4}};
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) System.out.print(grid[r][c]);
}
System.out.println();

Output

1234

The inner loop moves across columns inside the current row.

Exercises

8.2.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int[][] grid = {{1,2},{3,4}};
for (int c = 0; c < grid[0].length; c++) {
    for (int r = 0; r < grid.length; r++) System.out.print(grid[r][c]);
}
System.out.println();
Show solution

Output

1324

The outer column loop makes this column-major order.

8.2.2 · Write code

Write public static int rowSum(int[][] grid, int row), assuming row is valid. Sum that row without changing the grid.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public static int rowSum(int[][] grid, int row) {
    int sum = 0;
    for (int c = 0; c < grid[row].length; c++) sum += grid[row][c];
    return sum;
}

Check your code

Java

int[][] grid = {{2,3,4},{7,8,9}};
System.out.println(rowSum(grid,0));
System.out.println(rowSum(grid,1));

Expected output

9
24
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic