Which declaration correctly creates a 2D array of integers with 4 rows and 3 columns?
Loading test…
Loading test…
12 questions
Which declaration correctly creates a 2D array of integers with 4 rows and 3 columns?
What is the output of the following code?
int[][] m = {{2, 4}, {6, 8}};
for (int r = 0; r < m.length; r++) {
for (int c = 0; c < m[r].length; c++) {
System.out.print(m[r][c] + " ");
}
}
Consider a 2D array representing a grid where each row may have a different length (a jagged array). Which expression safely gives the number of columns in row i?
A student writes the following method to count elements equal to a target value in a 2D array:
public static int count(int[][] arr, int target) {
int cnt = 0;
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[0].length; c++) {
if (arr[r][c] == target) cnt++;
}
}
return cnt;
}
For which input would this method produce incorrect results?
What is the state of array a after the following code executes?
int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[] temp = a[0];
a[0] = a[2];
a[2] = temp;
A method receives a 2D array and should return the largest value in the array. Which implementation is correct?
public static int findMax(int[][] arr) {
int max = arr[0][0];
for (int[] row : arr) {
for (int val : row) {
if (val > max) max = val;
}
}
return max;
}
What value does the following method return when called with the array {{1, 2}, {3, 4}}?
public static int total(int[][] arr) {
int sum = 0;
for (int r = 0; r < arr.length; r++) {
for (int c = 0; c < arr[r].length; c++) {
sum += arr[r][c];
}
}
return sum;
}
What is the output of the following code?
int[][] t = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int c = 0; c < t[0].length; c++) {
for (int r = 0; r < t.length; r++) {
System.out.print(t[r][c] + " ");
}
}
Given the following code snippet:
int[][] grid = new int[3][4];
System.out.println(grid.length + " " + grid[0].length);
What is printed?
The following code attempts to print the sum of the main diagonal of a 3×3 array:
int[][] m = {{1, 0, 0}, {0, 5, 0}, {0, 0, 9}};
int diag = 0;
for (int i = 0; i < m.length; i++) {
diag += m[i][i];
}
System.out.println(diag);
What does it print?
Consider the following 2D array declaration:
int[][] arr = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
What is the value of arr[1][2]?
What is the output of the following code?
int[][] g = new int[2][3];
for (int r = 0; r < g.length; r++) {
for (int c = 0; c < g[r].length; c++) {
g[r][c] = r + c;
}
}
System.out.println(g[1][2]);