Codehs 8.1.5 Manipulating 2d Arrays
To manipulate every element in a 2D array, you must use nested for loops. The outer loop traverses the rows, while the inner loop traverses the columns.
This error happens if your loops try to access a row or column that does not exist. Ensure your loop conditions use < instead of <= . Because of zero-indexing, a grid with a length of 4 only has indices 0, 1, 2, and 3.
This creates a 3x3 2D array with the specified values. Codehs 8.1.5 Manipulating 2d Arrays
// Swap two columns by iteration public static void swapColumns(int[][] arr, int c1, int c2) for (int r = 0; r < arr.length; r++) int temp = arr[r][c1]; arr[r][c1] = arr[r][c2]; arr[r][c2] = temp;
var myArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; for (var i = 0; i < myArray.length; i++) myArray[i].push(i + 1); To manipulate every element in a 2D array,
Summing all values in a specific row, column, or the entire grid.
You can modify the existing value using operators like += , *= , or ++ . A common task is scaling an entire grid (like brightening an image): Ensure your loop conditions use This creates a
for (let r = 0; r < grid.length; r++) for (let c = 0; c < grid[r].length; c++) console.log(grid[r][c]);
return sum;
To solve for Row 2, you must first calculate the total number of elements in the 2D array. Since sub-arrays can have different lengths (jagged arrays), you need a nested loop. totalElements = ; i < array.length; i++) < array[i].length; ++) totalElements++;