Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

3141 5926 5358 9793

For the 4x4 matrix shown:

<code class="language-java">int s = 0; for (int i = 0; i < m.length; i++) s += m[i][m.length - 1 - i]; </code></pre> What is <code>s</code> (sum of the anti-diagonal)?

  • A

    16

  • B

    22

  • C

    15

    check_circle
  • D

    20

Explanation

The loop reads the anti-diagonal: <code>m[0][3]</code>, <code>m[1][2]</code>, <code>m[2][1]</code>, <code>m[3][0]</code>. From the figure those are 1, 2, 3, 9, so the sum is <code>1 + 2 + 3 + 9 = 15</code>.

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

Related questions