Challenge - 5 Problems
2D Arrays Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of nested loop filling 2D array
What is the output of the following Java code that fills a 2D array and prints it?
Java
public class Main { public static void main(String[] args) { int[][] arr = new int[2][3]; int count = 1; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { arr[i][j] = count++; } } for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
Attempts:
2 left
💡 Hint
Look at how the count variable increments inside the nested loops.
✗ Incorrect
The code fills the 2D array row by row with increasing numbers starting from 1, then prints each row on a new line.
❓ Predict Output
intermediateValue of element after initialization
What is the value of arr[1][2] after this code runs?
Java
int[][] arr = { {5, 10, 15}, {20, 25, 30}, {35, 40, 45} }; // What is arr[1][2]?
Attempts:
2 left
💡 Hint
Remember that the first index is the row, the second is the column.
✗ Incorrect
arr[1][2] means row 1 (second row), column 2 (third element), which is 30.
🔧 Debug
advancedIdentify the error in 2D array declaration
What error does this code produce?
Java
int[][] arr = new int[2][]; arr[0] = new int[3]; arr[1] = new int[2]; arr[0][3] = 5;
Attempts:
2 left
💡 Hint
Check the valid indices for arr[0].
✗ Incorrect
arr[0] has length 3, so valid indices are 0,1,2. Accessing index 3 causes ArrayIndexOutOfBoundsException.
🧠 Conceptual
advancedNumber of elements in jagged 2D array
Given the jagged array below, how many total elements does it contain?
Java
int[][] arr = { {1, 2}, {3, 4, 5}, {6} };
Attempts:
2 left
💡 Hint
Count the elements in each inner array and add them up.
✗ Incorrect
The first row has 2 elements, second has 3, third has 1. Total is 2+3+1=6.
❓ Predict Output
expertOutput of 2D array transpose code
What is the output of this Java code that transposes a 2D array?
Java
public class Main { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; int rows = matrix.length; int cols = matrix[0].length; int[][] transpose = new int[cols][rows]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { transpose[j][i] = matrix[i][j]; } } for (int i = 0; i < transpose.length; i++) { for (int j = 0; j < transpose[i].length; j++) { System.out.print(transpose[i][j] + " "); } System.out.println(); } } }
Attempts:
2 left
💡 Hint
Transpose swaps rows and columns.
✗ Incorrect
The transpose of a 2x3 matrix is a 3x2 matrix where rows and columns are swapped.
