Skip to Main Navigation Skip to Section Navigation Skip to Main Content Skip to Footer

Arrays | Codehs 8.1.5 Manipulating 2d

function sumBorder(matrix) 
  let sum = 0;
  let rows = matrix.length;
  let cols = matrix[0].length;

for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) i === rows - 1 return sum;


"Write a function that rotates the 2D array 90 degrees clockwise."

Depending on your specific school’s sandbox, 8.1.5 may ask you to implement one or more of the following methods. Codehs 8.1.5 Manipulating 2d Arrays

Prompt: Write a method swapRows(int[][] arr, int rowA, int rowB) that swaps the data of two rows.

Logic: Treat each row as a single unit. Instead of swapping individual elements, we can swap the references (in Java) or loop through columns (in languages without pointer arrays).

Solution (Java):

public static void swapRows(int[][] arr, int rowA, int rowB) 
    int[] temp = arr[rowA];
    arr[rowA] = arr[rowB];
    arr[rowB] = temp;

Note: If your 2D array uses ArrayList<ArrayList<Integer>>, you’ll need a deep swap, but for standard [][], this works perfectly.

Remove last row: matrix.pop();

Remove last column:

for (let i = 0; i < matrix.length; i++) 
  matrix[i].pop();

Manipulating 2D arrays is used in:


In a swap, you cannot write:

matrix[r][a] = matrix[r][b];
matrix[r][b] = matrix[r][a]; // Wrong! Original value is lost.

Always use temp.

The exact prompt may vary, but typical tasks include:

"Write a function that takes a 2D array and returns a new 2D array where each inner array is reversed."