(^584) | Multidimensional Arrays and Numeric Computation
hiTemp
[0]
[0]
[1]
[2]
[51]
[1][2][5]
hiTemp[2] [6]
//Print temperture values
// for 3rd week (row 2)
for (day = 0; day < 7; day++)
outFile.printin(hiTemp[2] [day]);
Figure 12.2 hiTempArray
in a year. Each row represents one of the 52 weeks in a year, and each column represents one
of the 7 days in a week. (To keep the example simple, we ignore the fact that there are 365—
and sometimes 366—days in a year.) The expression hiTemp[ 2 ][6]refers to the intvalue in the
third row (row 2) and the seventh column (column 6). Semantically,hiTemp[ 2 ][6]is the tem-
perature for the seventh day of the third week. The code fragment shown in Figure 12.2
would print the temperature values for the third week.
To obtain the number of columns in a row of an array, we access the lengthfield for the
specific row. For example, the statement
midYear = hiTemp[26].length;
stores the length of row 26 of the array hiTemp, which is 7, into the intvariable midYear.
Using Initializer Lists
Just as we can create a one-dimensional array with a list of values, so we can create a two-
dimensional array with a list of a list of values. For example, the following statement in-
stantiates a two-dimensional array of baseball hits. This array represents the hits for a
five-day period for your four favorite baseball players.
int[][] hits = {{2, 1, 0, 3, 2},
{1, 1, 2, 3, 4},
{1, 0, 0, 0, 0},
{0, 1, 2, 1, 1}};
As in the case of a one-dimensional array, you do not use newwith an initializer list. Now what
would happen if one of your favorite players went into a slump, and the manager gave him
a rest for a few days? How could you represent that scenario in your array? Suppose that the
third player sat out three games. Here is how you would represent this situation: