Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

public static int run() {
    int[][] m = {{1,2,3},{4,5,6},{7,8,9}};
    int s = 0;
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j <= i; j++) {
            s += m[i][j];
        }
    }
    return s;
}
// Call: System.out.println(run());

What is printed?

  • A

    45

  • B

    21

  • C

    34

    check_circle
  • D

    30

Explanation

Lower triangle sum: row 0 (j<=0): 1. Row 1 (j<=1): 4+5=9. Row 2 (j<=2): 7+8+9=24. Total = 1+9+24 = 34.

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

Related questions