Nested Loops for 2D Arrays
Getting the Number of Rows and Columns: 8.2.2
- Arrays know their length
arrayName.length
array2D.length // rows
array2D[0].length // columns in row 0
// all arrays on the exam are rectangular so this can be assumed to be the same for all
Looping Through a 2D Array: 8.2.3
- You can know the number of rows and columns in a 2D array
- Use a
nested for loop
to traverse all elements - The loop will execute number of rows * number of columns times
- Use a
- you can write them to traverse rows or columns first
int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// row -> column
for (int row = 0; row < myArray.length; row++) {
// Though the second statement could be hardcoded to index 0; this makes it more versatile!
for (int col = 0; col < myArray[row].length; col++) {
System.out.println(myArray[row][col]);
}
}
// column -> row
for (int col = 0; col < myArray[0].length; col++) {
for (int row = 0; row < myArray.length; row++) {
System.out.println(myArray[row][col]);
}
}
Enhanced For-Each Loop for 2D Arrays: 8.2.5
- 2D Arrays are just arrays of arrays
- we can use nested for-each loops on them!
- We can’t modify values if we’re using for-each
int[][] myArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int[] row : myArray) {
for (int val : row) {
System.out.println(val);
}
}
Summary: 8.2.8
- We can loop through 2D arrays using nested for or for-each loops
- The outer loop traverses rows
- The inner loop traverses columns
- This can be done in row-major order in this way
- If we instead traverse columns first; column-major order
- A 2D Array’s length gives the number of rows
- The length of a row is the number of columns
- The type of variable in a for-each loop must be an array for the outer loop
- It should be the type of the elements for the inner loop
- All 1D array algorithms apply to 2D arrays
- When applying sequential/linear search algorithms to 2D arrays, each row must be accessed then sequential/linear search applied to each row of a 2D array
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.