4.2 Working With 2-D ArraysTo illustrate the use of a 2-D array, suppose we have a collection of exam grades stored in a text file for a group of students that we need to process. For example, we may want to compute the average exam grade for each student or the average grade for each exam, or both. A sample text file is illustrated below 7 3 90 96 92 85 91 89 82 73 84 69 82 86 95 88 91 78 64 84 92 85 89 The file contains the grades for multiple students, each of whom have grades for multiple exams. The first line indicates the number of students for whom we have grades, and the second line indicates the number of exams for which each student has a grade. The remaining lines contain the actual exam grades. Each line contains the grade for an individual student, with the grades listed in exam order. Since we have multiple grades for multiple students, we can store the grades in a 2-D array in which each row contains the grades for an individual student and each column contains the grades for a given exam. A 2-D array used to store the exam grades from the sample file is illustrated in Figure 4.2.1. The source listing at the bottom of the page provides the implementation of a program that extracts the exam grades from the text file and stores them into a 2-D array. Notice that we create the array after extracting the first two values from the file. These values indicate the number of students and the number of exams that correspond to the number of rows and columns needed in the array. After extracting the grades from the file and storing them into the 2-D array, we can now process the grades as needed. In this case, the program computes and displays each student's average exam grade. Program Listing
|