What is a 2D array?
A one dimensional array of arrays, or a table/matrix
How do you change the value of an element in a 2D array?
By specifying the indices and assigning a new value, e.g., array[1][2] = 5;
How would you traverse a 2D array using a nested for loop?
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) { System.out.println(arr[i][j]);
}
}
In a 2D array arr, how can you access the last element in each row using a loop?
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i][arr[i].length - 1]); }
How do you appropriately declare and initialize a 2D array of integers?
int [][] name = new int[rows][columns]
What function would you use to transpose a matrix in many programming languages?
You’d swap rows and columns, or you could use a custom function to achieve this.
In a 2D array, how can you traverse all the elements and calculate the sum of all values?
int sum = 0;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) { sum += array[i][j];
}
}
How can you dynamically resize a 2D array?
You can create a new array with a larger size and copy elements from the old array to the new one
In a 2D array, if array[3][2] = 5;, what does this represent?
The element in the 4th row and 3rd column of the array is 5.
Given a 2D array matrix[3][3], how would you set all elements to zero?
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) { matrix[i][j] = 0;
}
}
What is the time complexity of traversing a 2D array with dimensions M x N?
O(M * N).
What is a jagged array in the context of 2D arrays?
A jagged array is an array of arrays where the inner arrays may have different lengths
What is the default value of a boolean in a 2D array in Java?
False
What will happen if you attempt to set an element outside the bounds of a 2D array (e.g., array[4][10] in a 3x5 array)?
It will throw an IndexOutOfBoundsException.
How would you print the diagonal elements of a square matrix array[n][n]?
for (int i = 0; i < array.length; i++) { System.out.println(array[i][i]);
}
What is the concept of "row-major" and "column-major" ordering in a 2D array?
How would you initialize a 3x3 matrix of integers with values 1 through 9?
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
How do you rotate a square matrix (2D array) 90 degrees clockwise?
Code
How would you traverse a 2D array in a spiral order starting from the top-left corner?
Code
How can you implement matrix addition using two 2D arrays?
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}