Task 7 of 9 · 0 solved · 9 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

5.4 2D arrays — column-major and diagonals

Lesson

Порядок обхода задаёте вы

Row-major — outer loop over rows, inner over columns — reads the grid the way you read a page. Swap the two loops and you get column-major: down the first column, then down the second. Same grid, same elements, different order.


Worked example

// grid = {{1,2,3},{4,5,6},{7,8,9}}
row-major:     1 2 3 4 5 6 7 8 9
column-major:  1 4 7 2 5 8 3 6 9

Two more useful patterns. The main diagonal is where row equals column — g[i][i] gives 1 5 9. The anti-diagonal runs the other way: g[i][g.length - 1 - i] gives 3 5 7.

⚠️ And the classic mix-up: g.length is the number of rows, g[0].length the number of columns. Swapping them is the most common 2D bug.


▶ Try it: run this, then change something and run it again.



Column-major traversal means...


The main diagonal consists of elements where...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    int[][] g = {{1, 2}, {3, 4}};
    for (int c = 0; c < g[0].length; c++) {
        for (int r = 0; r < g.length; r++) {
            System.out.print(g[r][c] + " ");
        }
    }
}}

g.length gives...


True or false?