Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

246 135 789 row 0 row 1 row 2

Given the matrix shown and:

<code class="language-java">int sum = 0; for (int r = 0; r < m.length; r++) for (int c = 0; c < m[r].length; c++) if (r != c) sum += m[r][c]; </code></pre> What is the value of <code>sum</code>?

  • A

    33

  • B

    27

  • C

    45

  • D

    31

    check_circle

Explanation

Sum of all entries = 2+4+6+1+3+5+7+8+9 = 45. The diagonal (r==c) values are 2, 3, 9 totaling 14. So 45 - 14 = 31.

Want 10 more like this — adaptive to your weak spots?

Related questions