8.8 Case Study: GradeBook Using an Array to Store Grades

We now present the first version of a GradeBook class that instructors can use to maintain students’ grades on an exam and display a grade report that includes the grades, class average, lowest grade, highest grade and a grade distribution bar chart. The version of class GradeBook presented in this section stores the grades for one exam in a one-dimensional array. In Section 8.10, we present a second version of class GradeBook that uses a two-dimensional array to store students’ grades for several exams.

Storing Student Grades in an array in Class GradeBook

Figure 8.14 shows the output that summarizes the 10 grades we store in an object of class GradeBook (Fig. 8.15), which uses an array of integers to store the grades of 10 students for a single exam. The array grades is declared as an instance variable in line 7 of Fig. 8.15—therefore, each GradeBook object maintains its own set of grades.

Fig. 8.14 Output of the GradeBook example that stores one exam’s grades in an array.

Alternate View

Welcome to the grade book for
CS101 Introduction to C# Programming!

The grades are:

Student  1:   87
Student  2:   68
Student  3:   94
Student  4:  100
Student  5:   83
Student  6:   78
Student  7:   85
Student  8:   91
Student  9:   76
Student 10:   87

Class average is 84.90
Lowest grade is 68
Highest grade is 100

Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
  100: *

Fig. 8.15 Grade book using an array to store test grades.

Alternate View

  1   // Fig. 8.15: GradeBook.cs
  2   // Grade book using an array to store test grades.
  3   using System;
  4
  5   class GradeBook
  6   {
  7      private int[] grades; // array of student grades
  8
  9      // getter-only auto-implemented property CourseName
 10      public string CourseName { get; }
 11
 12      // two-parameter constructor initializes
 13      // auto-implemented property CourseName and grades array
 14      public GradeBook(string name, int[] gradesArray)
 15      {
 16         CourseName = name; // set CourseName to name
 17         grades = gradesArray; // initialize grades array
 18      }
 19
 20      // display a welcome message to the GradeBook user
 21      public void DisplayMessage()
 22      {
 23         // auto-implemented property CourseName gets the name of course
 24          Console.WriteLine(
 25             $"Welcome to the grade book for
{CourseName}!
");
 26      }
 27
 28      // perform various operations on the data
 29      public void ProcessGrades()
 30      {
 31         // output grades array
 32         OutputGrades();
 33
 34         // call method GetAverage to calculate the average grade
 35         Console.WriteLine($"
Class average is {GetAverage():F}");
 36
 37         // call methods GetMinimum and GetMaximum
 38         Console.WriteLine($"Lowest grade is {GetMinimum()}");
 39         Console.WriteLine($"Highest grade is {GetMaximum()}
");
 40
 41         // call OutputBarChart to display grade distribution chart
 42         OutputBarChart();
 43      }
 44
 45      // find minimum grade
 46      public int GetMinimum()
 47      {
 48         var lowGrade = grades[0]; // assume grades[0] is smallest
 49
 50         // loop through grades array
 51         foreach (var grade in grades)                            
 52         {                                                        
 53            // if grade lower than lowGrade, assign it to lowGrade
 54            if (grade < lowGrade)                                 
 55            {                                                     
 56               lowGrade = grade; // new lowest grade              
 57            }                                                     
 58         }                                                        
 59
 60         return lowGrade; // return lowest grade
 61      }
 62
 63      // find maximum grade
 64      public int GetMaximum()
 65      {
 66         var highGrade = grades[0]; // assume grades[0] is largest
 67
 68         // loop through grades array
 69         foreach (var grade in grades)
 70         {
 71            // if grade greater than highGrade, assign it to highGrade
 72            if (grade > highGrade)
 73            {
 74               highGrade = grade; // new highest grade
 75            }
 76         }
 77
 78         return highGrade; // return highest grade
 79      }
 80
 81      // determine average grade for test
 82      public double GetAverage()
 83      {
 84         var total = 0.0; // initialize total as a double
 85
 86         // sum students' grades
 87         foreach (var grade in grades)
 88         {                            
 89         total += grade;              
 90         }                            
 91
 92         // return average of grades
 93         return total / grades.Length;
 94      }
 95
 96      // output bar chart displaying grade distribution
 97      public void OutputBarChart()
 98      {
 99         Console.WriteLine("Grade distribution:");
100
101         // stores frequency of grades in each range of 10 grades
102         var frequency = new int[11];
103
104         // for each grade, increment the appropriate frequency
105         foreach (var grade in grades)
106         {                            
107            ++frequency[grade / 10];  
108         }                            
109
110         // for each grade frequency, display bar in chart
111         for (var count = 0; count < frequency.Length; ++count)
112         {
113            // output bar label ("00-09: ", ..., "90-99: ", "100: ")
114            if (count == 10)
115            {
116               Console.Write(" 100: ");
117            }
118            else
119            {
120               Console.Write($"{count * 10:D2}-{count * 10 + 9:D2}: ");
121             }
122
123             // display bar of asterisks
124             for (var stars = 0; stars < frequency[count]; ++stars)
125             {
126                Console.Write("*");
127             }
128
129             Console.WriteLine(); // start a new line of output
130          }
131      }
132
133      // output the contents of the grades array
134      public void OutputGrades()
135      {
136         Console.WriteLine("The grades are:
");
137
138        // output each student's grade
139        for (var student = 0; student < grades.Length; ++student)
140        {                                                        
141           Console.WriteLine(                                    
142               $"Student {student + 1, 2}: {grades[student],3}");
143        }                                                        
144      }
145   }

The constructor (lines 14–18) receives the name of the course and an array of grades. When an app (e.g., class GradeBookTest in Fig. 8.16) creates a GradeBook object, the app passes an existing int array to the constructor, which assigns the array’s reference to instance variable grades (Fig. 8.15, line 17). The size of grades is determined by the class that passes the array to the constructor. Thus, a GradeBook can process a variable number of grades—as many as are in the array in the caller. The grade values in the passed array could have been input from a user at the keyboard or read from a file on disk (as discussed in Chapter 17). In our test app, we simply initialize an array with a set of grade values (Fig. 8.16, line 9). Once the grades are stored in instance variable grades of class GradeBook, all the class’s methods can access the elements of grades as needed to perform various calculations.

Methods ProcessGrades and OutputGrades

Method ProcessGrades (Fig. 8.15, lines 29–43) contains a series of method calls that result in the output of a report summarizing the grades. Line 32 calls method OutputGrades to display the contents of array grades. Lines 139–143 in method OutputGrades use a for statement to output the student grades. We use a for statement, rather than a foreach, because lines 141–142 use counter variable student’s value to output each grade next to a particular student number (see Fig. 8.14). Although array indices start at 0, an instructor would typically number students starting at 1. Thus, lines 141–142 output student + 1 as the student number to produce grade labels "Student 1: ", "Student 2: " and so on.

Method GetAverage

Method ProcessGrades next calls method GetAverage (line 35) to obtain the average of the grades in the array. Method GetAverage (lines 82–94) uses a foreach statement to total the values in array grades before calculating the average. The iteration variable in the foreach’s header indicates that for each iteration, grade takes on a value in array grades. The average calculation in line 93 uses grades.Length to determine the number of grades being averaged. Note that we initialized total as a double (0.0), so no cast is necessary.

Methods GetMinimum and GetMaximum

Lines 38–39 in method ProcessGrades call methods GetMinimum and GetMaximum to determine the lowest and highest grades of any student on the exam, respectively. Each of these methods uses a foreach statement to loop through array grades. Lines 51–58 in method GetMinimum loop through the array, and lines 54–57 compare each grade to lowGrade. If a grade is less than lowGrade, lowGrade is set to that grade. When line 60 executes, lowGrade contains the lowest grade in the array. Method GetMaximum (lines 64– 79) works the same way as method GetMinimum.

Method OutputBarChart

Finally, line 42 in method ProcessGrades calls method OutputBarChart to display a distribution chart of the grade data, using a technique similar to that in Fig. 8.7. In that example, we manually calculated the number of grades in each category (i.e., 0–9, 10–19, …, 90–99 and 100) by simply looking at a set of grades. In this example, lines 102–108 use a technique similar to that in Figs. 8.8 and 8.9 to calculate the frequency of grades in each category. Line 102 declares variable frequency and initializes it with an array of 11 ints to store the frequency of grades in each grade category. For each grade in array grades, lines 105–108 increment the appropriate element of the frequency array. To determine which element to increment, line 107 divides the current grade by 10, using integer division. For example, if grade is 85, line 107 increments frequency[8] to update the count of grades in the range 80–89. Lines 111–130 next display the bar chart (see Fig. 8.7) based on the values in array frequency. Like lines 27–30 of Fig. 8.7, lines 124–127 of Fig. 8.15 use a value in array frequency to determine the number of asterisks to display in each bar.

Class GradeBookTest That Demonstrates Class GradeBook

Lines 11–12 of Fig. 8.16 create an object of class GradeBook (Fig. 8.15) using int array gradesArray (declared and initialized in line 9 of Fig. 8.16). Line 13 displays a welcome message, and line 14 invokes the GradeBook object’s ProcessGrades method. The output reveals the summary of the 10 grades in myGradeBook.

Software Engineering Observation 8.1

A test harness (or test app) creates an object of the class to test and provides it with data, which could be placed directly into an array with an array initializer, come from the user at the keyboard or come from a file (as you’ll see in Chapter 17). After initializing an object, the test harness uses the object’s members to manipulate the data. Gathering data in the test harness like this allows the class to manipulate data from several sources.

Fig. 8.16 Create a GradeBook object using an array of grades.

Alternate View

  1   // Fig. 8.16: GradeBookTest.cs
  2   // Create a GradeBook object using an array of grades.
  3   class GradeBookTest
  4   {
  5      // Main method begins app execution
  6      static void Main()
  7      {
  8         // one-dimensional array of student grades
  9         int[] gradesArray = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
 10
 11         var myGradeBook = new GradeBook(
 12            "CS101 Introduction to C# Programming", gradesArray);
 13         myGradeBook.DisplayMessage();
 14         myGradeBook.ProcessGrades();
 15      }
 16   }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset