100 95 90 95 80 95 90 85 95 100 88 95 85 70 75 80 85 90Here we have three students and six grades for each student.
C provides us with the ability to define such two-dimensional arrays. For example, the declaration:
int grades[30][10] ;would create an array with 30 rows of 10 integers each for a total of 300 integers. (This form of declaration generalizes to more than two dimensions. In fact, C puts no limit on the number of dimensions that we have in an array. Here, we'll only look at one and two-dimensional arrays.) Given this declaration of an array and assuming that we have a variable called
num_stud
that tells us how many students
we have and another called num_grades
that tells us how
many grades each student has, we can do something like this:
for( i = 0; i < num_stud; ++i ) { sum = 0 ; for( j = 0; j < num_grades; ++j ) sum += grades[i][j] ; printf( "%d\n", sum / num_grades ) ; }This code fragment will compute each student's average and print it out. Notice that we have one loop inside of another. The way to think about this is as in the following algorithm:
For each student, i, Set the sum to 0 For each grade, j, of student i, add student i's grade j to the sum Print out the value of the sum divided by the number of gradesThis algorithm illustrates one particularly important way of thinking about loops. Namely, a loop is executed once for each something. Determining what that something is will will often help in designing the loop. Here we have two loops. The first is done once for each student and for each student we will have another loop that is done once for each grade. Also notice that we need to reset the sum to zero for each student so that the previous student's sum is not added to the current one. If the code fragment above is executed on the array of grades given at the top, what will be the set of numbers printed?