Suppose that in addition to the array of students' grades, we want to store the first name of each student in the class. We might create an array of names like this:
char names[30][40];
name
with room for 30 students
whose names are no more than 39 characters each.
Now with this array, we can label each of the averages we printed
earlier:
for(i = 0; i < num_stud; ++i) { sum = 0; for(j = 0; j < num_grades; ++j) sum += grades[i][j]; printf("%s - %d\n", names[i], sum / num_grades); }
grades
array, we give two indices to
indicate which grade we're interested in.
But even though the names array is also two-dimensional, when
we go to print out a name, we only give it one index (the row).
The reason for this is that we're treating an entire row of
the array as a single thing, a string.
If we want to deal with the individual letters that make up the
names, then we would need to provide two indices.
The next example illustrates this:
for(i = 0; i < num_stud; ++i) { if(names[i][0] == 'M') printf("%s\n", names[i]); }
'M'
.
So where we're dealing with single characters in a two-dimensional
array, as in the
if
, we provide two indices,
but where we're dealing with a row at a time, we only give one.
(As long as we're on this example, it bears pointing out that
it will not find students whose names are listed beginning with
a lower case
'm'
.
The upper and lower case letters are distinct.)