What do we call an array of arrays in Java?
A 2D array or matrix
Declare a 3x4 integer 2D array.
int[][] arr = new int[3][4];
Write a loop to print all elements in a 2D array.
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
}
Give an example of a real-world 2D array.
Spreadsheet, grid, map
int[][] a = {{1, 2}, {3, 4}};
System.out.println(a[0][1]);
2
What does .length give you in a 2D array?
Number of rows
Fill a 2x2 array with 1, 2, 3, 4.
int[][] arr = {{1,2}, {3,4}};
Use enhanced for-loops to sum all elements.
int sum = 0;
for (int[] row : arr)
for (int val : row)
sum += val;
How can 2D arrays be used in games?
Store game board like tic-tac-toe
int[][] b = new int[2][2];
System.out.println(b[1][1]);
0 (default int value)
What's the term for accessing all elements in a 2D array?
Traversal
What does arr[1][2] mean?
Access element at row 1, column 2
What does arr[i].length represent?
Number of columns in row i
Why are 2D arrays good for image processing?
Images are made of pixel rows and columns
int[][] a = {{5, 6}, {7, 8}};
a[1][0] = a[0][1];
System.out.println(a[1][0]);
6
What type of loop is most commonly used with 2D arrays?
Nested for-loops
Is this valid? int[][] a = new int[][4];
No. Must specify number of rows.
Traverse only the diagonal of a square 2D array.
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i][i] + " ");
How would a 2D array help with seating charts?
Each row and column stores a seat
int[][] x = {{1,2,3},{4,5,6}};
System.out.println(x.length + " " + x[0].length);
2 3
What is the difference between arr.length and arr[0].length?
arr.length = rows, arr[0].length = columns
How do you replace an element at row 2, column 1 with 9?
arr[2][1] = 9;
Count how many even numbers are in a 2D array.
int count = 0;
for (int[] row : arr)
for (int val : row)
if (val % 2 == 0) count++;
Explain how a 2D array might be used in a robot navigation system.
Track visited cells or obstacles in a grid
int[][] arr = {{1, 2}, {3, 4}};
for (int i = 1; i >= 0; i--)
System.out.print(arr[i][0] + " ");
3 1