ACSA Exam Prep
Unit 4 · Data Collections · Topic 4.12

2D Array Traversals

Skill 2.BSkill 3.BSkill 3.D

Big idea: Nested loops visit every cell. Row-major goes across each row; column-major goes down each column.

Learning objectives
  • Develop code used to traverse the elements in a 2D array and determine the result of these traversals.

Row-major order

Code
int[][] m = { {1, 2, 3}, {4, 5, 6} };
for (int r = 0; r < m.length; r++) {
  for (int c = 0; c < m[0].length; c++) {
    System.out.print(m[r][c] + " ");
  }
}
System.out.println();
Output
1 2 3 4 5 6

Column-major order

Swap the loops: the outer loop runs over columns. The access is still m[r][c].

Code
int[][] m = { {1, 2, 3}, {4, 5, 6} };
for (int c = 0; c < m[0].length; c++) {
  for (int r = 0; r < m.length; r++) {
    System.out.print(m[r][c] + " ");
  }
}
System.out.println();
Output
1 4 2 5 3 6

Nested enhanced for

The outer variable is a row (type int[]); the inner variable is one element. As with 1D arrays, assigning to the inner variable doesn't change the grid.

Code
int[][] m = { {1, 2}, {3, 4} };
int total = 0;
for (int[] row : m) {
  for (int v : row) {
    total += v;
  }
}
System.out.println(total);
Output
10
Key points
  • Row-major: across each row. Column-major: down each column.
  • In a nested enhanced for, the outer variable is a row (a 1D array) and the inner one is an element.
  • Assigning to an enhanced for variable doesn't change the array.
Watch out
  • For column-major, the outer loop bound is the number of columns, but the access is still g[r][c].
Quick check
What is the type of row in for (String[] row : names)?
Show answer
String[], one row of the 2D array.