Bird
0
0

How would you modify this code to sum all elements in a 2D array?

hard📝 Application Q9 of 15
Java - Arrays
How would you modify this code to sum all elements in a 2D array?
int[][] matrix = {{1,2}, {3}};
int sum = 0;
// Your code here
Afor(int i = 0; i <= matrix.length; i++) { for(int j = 0; j < matrix.length; j++) { sum += matrix[i][j]; } }
Bfor(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } }
Cfor(int i = 0; i < matrix.length; i++) { sum += matrix[i]; }
Dfor(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix.length; j++) { sum += matrix[j][i]; } }
Step-by-Step Solution
Solution:
  1. Step 1: Use nested loops for 2D array traversal

    Outer loop runs over rows, inner loop over columns of each row.
  2. Step 2: Add each element to sum

    Access element at matrix[i][j] and add to sum inside inner loop.
  3. Final Answer:

    for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } } -> Option B
  4. Quick Check:

    Nested loops with correct bounds sum all elements [OK]
Quick Trick: Use nested loops for 2D arrays [OK]
Common Mistakes:
  • Using <= length causes errors
  • Adding entire row instead of elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes