public static int[][] transpose(int[][] matrix) int rows = matrix.length; int cols = matrix[0].length; int[][] transposed = new int[cols][rows]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) transposed[j][i] = matrix[i][j];
Mastering 2D array manipulation will prepare you for more advanced topics like multidimensional data processing and algorithm design.
Vertical lines, indexed from 0 to grid[0].length - 1 . Accessing an Element: grid[row][col] Core Concepts of Lesson 8.1.5
Think of a 2D array as a spreadsheet. It has rows (going down) and columns (going across). In Java, a 2D array is declared using two sets of brackets: int[][] matrix = new int[rows][cols]; . Codehs 8.1.5 Manipulating 2d Arrays
for (int r = 0; r < array.length; r++) for (int c = 0; c < array[r].length; c++) // Manipulation logic goes here Use code with caution. 2. Implementing Conditional Logic
Here is how you would write the solution for a typical manipulation task:
Never use fixed numbers like row < 3 or col < 4 unless explicitly told to do so. Always use .length so your code works for any size test case the autograder throws at it. public static int[][] transpose(int[][] matrix) int rows =
it. Here’s a breakdown of the core concepts you need to master. 1. The Power of Nested Loops
public void initializeGrid(int[][] arr) for (int row = 0; row < arr.length; row++) for (int col = 0; col < arr[row].length; col++) arr[row][col] = -1; // Changes the value at the current index Use code with caution. 2. Conditionally Modifying Values
let matrix = [ [1, 2, 3], // Row 0 [4, 5, 6], // Row 1 [7, 8, 9] // Row 2 ]; Use code with caution. To access the number It has rows (going down) and columns (going across)
While CodeHS occasionally changes exercises, is widely known to require writing a method that doubles every element in a 2D array of integers. The exact wording may be:
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.
function zeroOutNegatives(matrix) for (let i = 0; i < matrix.length; i++) for (let j = 0; j < matrix[i].length; j++) if (matrix[i][j] < 0) matrix[i][j] = 0;