Codehs 8.1.5 Manipulating 2d Arrays New! Official
A: Use arr[i].length for each row in the inner loop. Avoid arr[0].length if rows have different sizes. Conclusion CodeHS 8.1.5, "Manipulating 2D Arrays," is a rite of passage for aspiring Java developers. It forces you to master nested loops, index math, and algorithmic thinking. By understanding how to swap rows, swap columns, and rotate matrices, you are building the spatial reasoning required for technical interviews, game programming, and data science.
For an N x N matrix, the element at (r, c) moves to (c, N - 1 - r) . Codehs 8.1.5 Manipulating 2d Arrays
Since columns are not stored as contiguous variables, you must iterate through each row and swap the specific column values. A: Use arr[i]
public static void swapColumns(int[][] arr, int colA, int colB) { for (int row = 0; row < arr.length; row++) { int temp = arr[row][colA]; arr[row][colA] = arr[row][colB]; arr[row][colB] = temp; } } Prompt: Modify the array so that cells where (row + col) % 2 == 0 become 1 , and odd sum cells become 0 . It forces you to master nested loops, index
// Manipulation task 8.1.5 specific: Create diagonal pattern public static void diagonalOne(int[][] arr) { for (int r = 0; r < arr.length; r++) { for (int c = 0; c < arr[0].length; c++) { if (r == c) { arr[r][c] = 1; } else if (r + c == arr.length - 1) { arr[r][c] = 1; // Anti-diagonal also to 1 } else { arr[r][c] = 0; } } } }