Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

int[][] m = {{1, 2, 3}, {4, 5, 6}};
StringBuilder sb = new StringBuilder();
for (int c = 0; c < m[0].length; c++) {
    for (int r = 0; r < m.length; r++) {
        sb.append(m[r][c]);
    }
}
System.out.println(sb.toString());

What is printed?

  • A

    123456

  • B

    142536

    check_circle
  • C

    456123

  • D

    147258

Explanation

Column-major visits col 0: m[0][0]=1, m[1][0]=4; col 1: 2, 5; col 2: 3, 6. Result: "142536".

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

Related questions