AP CS A: 2D Arrays and Nested Loops (the patterns that show up)
The 2D array FRQ is one of the four AP CS A FRQ types and shows up every year. The traversal patterns are limited — learn these 4 and you've covered everything the exam can ask.
Pattern 1 — Full row-major traversal
The standard traversal. Visit every element row by row.
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
// do something with arr[r][c]
}
}
Used for: summing all elements, finding max/min, applying an operation to every cell.
Pattern 2 — Column-major traversal
Visit by column, then row.
for (int c = 0; c < arr[0].length; c++) {
for (int r = 0; r < arr.length; r++) {
// do something with arr[r][c]
}
}
Used for: column sums, finding the ‘heaviest’ column, transposing.
Pattern 3 — Diagonal traversal
The main diagonal where row index equals column index. For a square 2D array:
for (int i = 0; i < arr.length; i++) {
// arr[i][i] is on the main diagonal
}
For the anti-diagonal (top-right to bottom-left): arr[i][arr.length - 1 - i].
Pattern 4 — Neighbor traversal
Visit each cell and its neighbors. Tricky because neighbors might not exist at edges.
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
// check each neighbor with bounds check
if (r > 0) { /* arr[r-1][c] is north neighbor */ }
if (r < arr.length - 1) { /* south */ }
if (c > 0) { /* west */ }
if (c < arr[r].length - 1) { /* east */ }
}
}
Used for: cellular-automata-style problems, “count neighbors with property X”.
Common 2D array FRQ mistakes
-
Confusing rows and columns.
arr[r][c]is row r, column c. NOT column r, row c. -
Using
arr.lengthfor columns.arr.lengthis the number of rows.arr[0].length(orarr[r].length) is the number of columns. - Forgetting that 2D arrays in Java are arrays of arrays. Rows can technically have different lengths (jagged arrays). The exam rarely tests this but it's worth knowing.
-
Off-by-one on neighbor bounds.
if (r < arr.length - 1), notif (r <= arr.length).
Need a long-term AP Computer Science mentor, not just a one-off explanation? Learn about AP Computer Science mentorship at Palo Alto Mentor. Most of our students stay with the same mentor for 3–5 years.