Traversing 2D Arrays

AP Computer Science A· difficulty 4/5

public static int run() {
    int[][] m = new int[3][3];
    int n = 1;
    for (int j = 0; j < 3; j++)
        for (int i = 0; i < 3; i++)
            m[i][j] = n++;
    return m[1][2];
}
// Call: System.out.println(run());

What is printed?

  • A

    6

  • B

    5

  • C

    9

  • D

    8

    check_circle

Explanation

Column-major fill. Column j=0: m[0][0]=1, m[1][0]=2, m[2][0]=3. j=1: m[0][1]=4, m[1][1]=5, m[2][1]=6. j=2: m[0][2]=7, m[1][2]=8, m[2][2]=9.

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

Related questions