Popular searches

2d Arrays !!exclusive!! — Codehs 8.1.5 Manipulating

function doubleArray(matrix) for (let i = 0; i < matrix.length; i++) for (let j = 0; j < matrix[i].length; j++) matrix[i][j] *= 2;

You might be asked to change an item only if its row index matches its column index ( r == c ). 3. Modifying the Value

Manipulation usually requires a check. For example, if you are asked to change all even numbers to zero, you would use the modulo operator ( % ) inside your nested loops: if (array[row][col] % 2 == 0) array[row][col] = 0; Use code with caution. Common Pitfalls to Avoid

// Removing a row array.pop(); console.log(array); // Output: // [ // [1, 2, 3], // [4, 10, 6], // [7, 8, 9] // ] Codehs 8.1.5 Manipulating 2d Arrays

, and I'll write the complete code solution for you.

Multiply every element by 2:

When you declare int[][] matrix = new int[3][4]; , you are creating an outer array with 3 elements. Each of those 3 elements is an individual 1D array containing 4 integers. function doubleArray(matrix) for (let i = 0; i &lt; matrix

// Sum: Calculate the class average public double calculateClassAverage() int total = 0; for (int row = 0; row < scores.length; row++) for (int col = 0; col < scores[row].length; col++) total += scores[row][col];

for (int row = 0; row < matrix.length; row++) for (int col = 0; col < matrix[row].length; col++) // do something with matrix[row][col]

int max = matrix[0][0]; for (int row = 0; row < matrix.length; row++) for (int col = 0; col < matrix[row].length; col++) if (matrix[row][col] > max) max = matrix[row][col]; For example, if you are asked to change

double classAverage = (double) total / (studentScores.length * studentScores[0].length);

sum of the first element of the first array and the last element of the last array Implementation Guide 1. Calculate the 2D Length

public void replaceNegatives(int[][] grid) for (int row = 0; row < grid.length; row++) for (int col = 0; col < grid[row].length; col++) if (grid[row][col] < 0) grid[row][col] = 0; Use code with caution. Pattern C: Manipulating Specific Rows or Columns