Stringing Words Together

Just as we can have multi-dimensional arrays of numbers, we can have multi-dimensional arrays of characters. One of the best ways of thinking about a two-dimensional arrays of characters is to think of it as an array of strings.

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];

which creates the array 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);
}

This example points out an interesting distinction between how we use two-dimensional arrays of numbers and how we use arrays of strings. Notice that when we use the 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]);
}

This code fragment will list all those students whose names begin with '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.)
What will this loop print?
for(i = 0; i < num_stud; ++i) {
   if(grades[i][3] > 90 && names[i][1] == 's')
      printf("%s\n", names[i]);
}

All names of students whose names have the first letter s or who scored better than 90 on the third assignment.

All names of students whose names have the second letter s or who scored better than 90 on the fourth assignment.

All names of students whose names have the first letter s and who scored better than 90 on the third assignment.

The name of the first student whose name has the second letter s and who scored better than 90 on the fourth assignment.

All names of students whose names have the second letter s and who scored better than 90 on the fourth assignment.