Implementing
2D Array Algorithms
Master row-major traversal, nested loops, and common patterns for processing two-dimensional arrays in Java.
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.
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.
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] } }
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
A restorer repairs a luminous pixel 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
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; }
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
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
int count = 0; for (int[] row : arr) { for (int val : row) { if (val % 2 == 0) { count++; } } }
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
int result = 0; for (int c = 0; c < arr[0].length; c++) { for (int r = 0; r < arr.length; r++) { result += arr[r][c]; } }
This code traverses the array in which order?
Question 5 of 5
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;
If the array is {{-5, -2}, {-8, -1}}, what does this method return?