Traversing a 2D Array in Row-Major Order
The nested loop
A rooftop has 2 rows of 4 solar panels, and
watts holds each panel's output at noon.int[][] watts = { {210, 190, 225, 0},
{205, 180, 230, 215} };
for (int row = 0; row < watts.length; row++)
{
for (int col = 0; col < watts[row].length; col++)
{
System.out.print(watts[row][col] + " ");
}
}The outer loop chooses the row. Inside it, the inner loop runs across every column before the outer loop chooses again. So the output is all of row 0, then all of row 1,
210 190 225 0 205 180 230 215, the order called row-major.The two bounds
The outer bound is
watts.length, the number of rows, 2. The inner bound is watts[row].length, the length of the current row, 4 columns. watts[0].length would work as well, since every row of watts holds 4 panels.Using
watts.length as the inner bound would be wrong. The inner loop would stop after 2 columns, and half of each row would never be visited. On a grid that's taller than it is wide, the same mistake throws an ArrayIndexOutOfBoundsException instead.Counting passes
The inner body runs once per element. Two rows of 4 make 8 runs, the row count times the column count.
A count of the panels producing under 200 watts puts an
if in that body.int weak = 0;
for (int row = 0; row < watts.length; row++)
{
for (int col = 0; col < watts[row].length; col++)
{
if (watts[row][col] < 200)
{
weak++;
}
}
}
The body still runs 8 times, and
weak counts 190, 0, and 180, ending at 3.One result per row
A statement between the two loops runs once per row. Declaring a total there gives each row its own.
for (int row = 0; row < watts.length; row++)
{
int rowWatts = 0;
for (int col = 0; col < watts[row].length; col++)
{
rowWatts += watts[row][col];
}
System.out.println(rowWatts);
}
This prints 625 and then 830. With
int rowWatts = 0; above the outer loop instead, the second number would be the running total for both rows, 1455.