Page 164 - DCAP507_SYSTEM_SOFTWARE
P. 164
System Software
Notes You have to read complicated declarations like these “inside out.” What this one says is that a2
is an array of 5 somethings, and that each of the somethings is an array of 7 ints. More briefly, “a2
is an array of 5 arrays of 7 ints,” or, “a2 is an array of array of int.” In the declaration of a2, the
brackets closest to the identifier a2 tell you what a2 first and foremost is. That’s how you know
it’s an array of 5 arrays of size 7, not the other way around. You can think of a2 as having 5
“rows” and 7 “columns,” although this interpretation is not mandatory. (You could also treat
the “first” or inner subscript as “x” and the second as “y.” Unless you're doing something fancy,
all you have to worry about is that the subscripts when you access the array match those that you
used when you declared it, as in the examples.)
To illustrate the use of multidimensional arrays, we might fill in the elements of the above array
a2 using this piece of code:
int i, j;
for(i = 0; i < 5; i = i + 1)
{
for(j = 0; j < 7; j = j + 1)
a2[i][j] = 10 * i + j;
}
This pair of nested loops sets a[1][2] to 12, a[4][1] to 41, etc. Since the first dimension of a2 is 5, the
first subscripting index variable, i, runs from 0 to 4. Similarly, the second subscript varies from
0 to 6.
We could print a2 out (in a two-dimensional way, suggesting its structure) with a similar pair of
nested loops:
for(i = 0; i < 5; i = i + 1)
{
for(j = 0; j < 7; j = j + 1)
printf("%d\t", a2[i][j]);
printf("\n");
}
(The character \t in the printf string is the tab character.)
Just to see more clearly what's going on, we could make the “row” and “column” subscripts
explicit by printing them, too:
for(j = 0; j < 7; j = j + 1)
printf("\t%d:", j);
printf("\n");
for(i = 0; i < 5; i = i + 1)
{
printf("%d:", i);
for(j = 0; j < 7; j = j + 1)
printf("\t%d", a2[i][j]);
printf("\n");
}
158 LOVELY PROFESSIONAL UNIVERSITY