AP Computer Science A — Unit 8 Review: Two‑Dimensional Arrays
int[][] a = new int[3][4];
[]
indicate a 2D array.int
elements → 0.int[][] b = {
{2,3,1},
{8,5,6}
};
{ ... }
defines a row.text
heap: [row0Ref, row1Ref, row2Ref]
row0Ref ──▶ [ , , , ]
row1Ref ──▶ [ , , , ]
row2Ref ──▶ [ , , , ]
* Outer array holds references to inner 1D arrays.
* Inner arrays hold actual elements.
System.out.println(b[0][1]); // row 0, col 1
a[1][2] = 9; // set row 1, col 2
boolean check = (a[2][0] < b[1][1]);
for
Loops (row‑major order)for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + " ");
}
System.out.println();
}
arr.length
→ number of rows.arr[r].length
→ length of row r
(number of columns in that row).r+=2
).for
Loopsfor (int[] row : arr) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
row
refers to each inner array in turn.val
is each element in row
.for (int r = 0; r < arr.length; r++)
for (int c = 0; c < arr[r].length; c++)
arr[r][c] *= 2;
for (int r = 0; r < arr.length; r++) {
int cols = arr[r].length;
for (int c = 0; c < cols/2; c++) {
int temp = arr[r][c];
arr[r][c] = arr[r][cols-1-c];
arr[r][cols-1-c] = temp;
}
}
Given a 2D String[][] floor
, implement:
lineOfIdentical(String[] row)
→ boolean
:
Return true
if all entries in row
are equal.
isFloorSafe(String[][] floor)
→ boolean
:
No entries equal to "X" or "Y".
canCrossFloor(String[][] floor)
→ boolean
:
isFloorSafe(floor) == true
and
lineOfIdentical(...)
.Traversal tip: Use for loops over floor.length
(rows) and floor[r].length
(cols).
arr.length
for rows and arr[r].length
for columns.for
loops (row-major) for full traversal.for
is concise but read-only for element assignments.Master these patterns to ace AP CSA questions on two‑dimensional arrays!