01 / 21

Implementing
2D Array Algorithms

Master row-major traversal, nested loops, and common patterns for processing two-dimensional arrays in Java.

AP Computer Science A

What Is a 2D Array?

A 2D array in Java is an array of arrays: each element of the outer array is itself an array. You can think of it as a grid with rows and columns, where every cell holds a single value.

col 0 col 1 col 2 col 3 row 0 row 1 row 2 3 7 1 9 4 2 8 5 6 0 3 7

Declaring & Initializing

Java provides two common ways to create a 2D array: specifying dimensions only (filled with defaults), or providing an initializer list with explicit values.

// Method 1: Dimensions only (3 rows, 4 cols of 0s)
int[][] grid = new int[3][4];

// Method 2: Initializer list
int[][] grid = {
    {3, 7, 1, 9},
    {4, 2, 8, 5},
    {6, 0, 3, 7}
};

Why 2D Arrays Matter

Two-dimensional arrays model countless real-world structures. Understanding them is essential for the AP CSA exam and for building real software.

Game Boards
Chess, tic-tac-toe, minesweeper: every cell maps to a grid position.
Images
Pixel data is stored as rows and columns of color values.
Spreadsheets
Tables of data, gradebooks, and matrices are naturally 2D.

The Row-Major Traversal Pattern

Row-major order visits every element by going across each row from left to right, top to bottom. This is the standard traversal on the AP exam.

for (int r = 0; r < arr.length; r++) {
    for (int c = 0; c < arr[r].length; c++) {
        // process arr[r][c]
    }
}
1 2 3 4 5 6 7 8 9 10 11 12 Row-major order Numbers show visit order

Column-Major Traversal

In column-major order, the outer loop iterates over columns and the inner loop iterates over rows: you visit every element in column 0 first, then column 1, and so on.

for (int c = 0; c < arr[0].length; c++) {
    for (int r = 0; r < arr.length; r++) {
        // process arr[r][c]
    }
}

Row-Major vs Column-Major

Row-Major Column-Major
Outer loop rows (r) columns (c)
Inner loop columns (c) rows (r)
Visit pattern Left to right, top to bottom Top to bottom, left to right
AP default? ✓ Yes Sometimes tested
Use case Summing all elements, printing Column averages, transposing

Enhanced For-Each Loop

When you only need to read values (no index needed), the enhanced for loop is cleaner. The outer loop iterates over rows (each an int[]), and the inner loop iterates over values in that row.

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

Step-by-Step Algorithm Design

1
Identify what you need: Are you summing, searching, counting, or modifying? This determines your accumulator variable.
2
Choose traversal order: Row-major for general processing; column-major if you need column-wise results.
3
Set loop bounds carefully: Outer uses arr.length (rows), inner uses arr[r].length (cols). Never hard-code sizes.
4
Process each cell: Apply your logic inside the inner loop using arr[r][c].
5
Return or output: After the loops complete, return your accumulated result.

A restorer repairs a luminous pixel mosaic

A restorer lifts a tile from a luminous rectangular mosaic.Grid algorithms turn a visual pattern into explicit row and column operations. Bounds checks determine which neighboring cells can be accessed.

Check neighboring cells

A 3-by-4 grid marks corner, edge and interior neighbors and shows row-before-column bounds checks.In this rectangular grid, an interior cell has four orthogonal neighbors, a noncorner edge cell has three, and a corner has two. Validate the target row before accessing that row’s length.

Example 1: Sum All Elements

Write a method that returns the sum of every element in a 2D integer array.

public static int totalSum(int[][] arr) {
    int sum = 0;
    for (int r = 0; r < arr.length; r++) {
        for (int c = 0; c < arr[r].length; c++) {
            sum += arr[r][c];
        }
    }
    return sum;
}

Example 2: Count Matches

Count how many times a target value appears in the 2D array.

public static int countOccurrences(int[][] arr, int target) {
    int count = 0;
    for (int[] row : arr) {
        for (int val : row) {
            if (val == target) {
                count++;
            }
        }
    }
    return count;
}

Example 3: Row Sums Array

Return a 1D array where each element is the sum of the corresponding row.

public static int[] rowSums(int[][] arr) {
    int[] sums = new int[arr.length];
    for (int r = 0; r < arr.length; r++) {
        for (int c = 0; c < arr[r].length; c++) {
            sums[r] += arr[r][c];
        }
    }
    return sums;
}
3 7 1 9 = 20 4 2 8 5 = 19 6 0 3 7 = 16 sums[0] sums[1] sums[2]

Example 4: Find the Maximum

Locate the largest value in a 2D array. Initialize the max with the first element, then compare every other cell.

public static int findMax(int[][] arr) {
    int max = arr[0][0];
    for (int r = 0; r < arr.length; r++) {
        for (int c = 0; c < arr[r].length; c++) {
            if (arr[r][c] > max) {
                max = arr[r][c];
            }
        }
    }
    return max;
}

Example 5: Modify In Place

Replace every negative value in the array with 0. This requires the standard indexed loop because we need to write to the array.

public static void replaceNegatives(int[][] arr) {
    for (int r = 0; r < arr.length; r++) {
        for (int c = 0; c < arr[r].length; c++) {
            if (arr[r][c] < 0) {
                arr[r][c] = 0;
            }
        }
    }
}

Common Mistakes

✕ Swapped Indices
Using arr[c][r] instead of arr[r][c] causes an ArrayIndexOutOfBoundsException when rows and columns differ.
✕ Hard-coded Bounds
Writing c < 4 instead of c < arr[r].length breaks when the array size changes.
✕ Modifying with For-Each
Assigning val = 0 in an enhanced for loop changes only the local copy, not the array itself.

Algorithm Summary

Algorithm Pattern Loop Type
Sum all elements Accumulator += each cell Either
Count matches if (val == target) count++ Either
Row/column sums Reset accumulator per row/col Indexed
Find max/min Compare and update tracker Either
Modify in place arr[r][c] = newValue Indexed only
Search (find location) Return r, c when found Indexed only

Question 1 of 5

Given int[][] m = new int[3][5];, what does m.length return?

Question 2 of 5

What does this code compute?

Question 3 of 5

You want to replace every negative value in a 2D array with 0. Which loop type is required?

Question 4 of 5

This code traverses the array in which order?

Question 5 of 5

If the array is {{-5, -2}, {-8, -1}}, what does this method return?