Column-Major Order and Enhanced for Loops on 2D Arrays
Column-major order
A word puzzle stores its letters in a 2D array of one-letter strings.
String[][] letters = { {"C", "A", "T"},
{"O", "R", "E"} };Read in row-major order, the letters are C, A, T, O, R, and E. A loop that puts the columns on the outside reads down each column instead.
String out = "";
for (int col = 0; col < letters[0].length; col++)
{
for (int row = 0; row < letters.length; row++)
{
out += letters[row][col];
}
}
Now
out is "COARTE", reading column 0 downward, then column 1, then column 2, which is column-major order.Bounds and indexes
The bounds traded places with the loops. The outer loop counts columns, so it stops at
letters[0].length, 3. The inner loop counts rows, so it stops at letters.length, 2.The access is still
letters[row][col], row first, whichever loop is outside. The order of the loops sets the order of the output, and the order of the indexes in the brackets never changes. On this 2-by-3 array, exchanging the two bounds would make the inner loop ask for row 2 and throw.A traversal can also follow any order the problem defines. Reading the bottom row first starts the outer loop at
letters.length - 1 and counts down while row >= 0, which gives O, R, E, C, A, and T. Each dimension gets its own header, so the direction of one doesn't affect the other.Enhanced for loops
A 2D array is an array of rows, so an enhanced
for loop over it hands over one row at a time.String all = "";
for (String[] row : letters)
{
for (String s : row)
{
all += s;
}
}
The outer variable has the type of a row,
String[]. The inner loop goes through one row, so its variable has the element type, String. This builds "CATORE", since nested enhanced loops hand over row 0, then row 1, and the letters of each in their stored order. No pair of enhanced loops produces column-major order.So a body of
s = "X"; leaves letters as it was, since s holds a copy. Writing into the array takes an index: row[k] = "X"; inside the outer enhanced loop, or letters[r][c] = "X"; in an indexed loop.