Section 5.9. Counter-Controlled Repetition


5.9. Counter-Controlled Repetition

Next, we modify the GradeBook class of Chapter 4 to solve two variations of a problem that averages student grades. Consider the following problem statement:

A class of 10 students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.

The class average is equal to the sum of the grades divided by the number of students (10). The program for solving this problem must input each grade, keep track of the total of all grades input, perform the averaging calculation and print the result.

We use counter-controlled repetition to input and process the grades one at a time. This technique uses a counter to specify the number of times that a set of statements will execute. Counter-controlled repetition also is called definite repetition because the number of repetitions is known before the loop begins executing. In this example, repetition terminates when the counter exceeds 10. This section presents a version of class GradeBook (Fig. 5.10) that implements the algorithm in a method. The section then presents an application (Fig. 5.11) that demonstrates the algorithm in action.

Figure 5.10. Counter-controlled repetition: Class-average problem.

  1  ' Fig. 5.10: GradeBook.vb  2  ' GradeBook class that solves class-average problem using  3  ' counter-controlled repetition.  4  Public Class GradeBook  5     Private courseNameValue As String ' course name for this GradeBook  6  7     ' constructor initializes CourseName with String supplied as argument  8     Public Sub New(ByVal name As String)  9        CourseName = name ' validate and store course name 10     End Sub ' New 11 12     ' property that gets and sets the course name; the Set accessor 13     ' ensures that the course name has at most 25 characters 14     Public Property CourseName() As String 15        Get ' retrieve courseNameValue 16           Return courseNameValue 17        End Get 18 19        Set(ByVal value As String) ' set courseNameValue 20           If value.Length <= 25 Then ' if value has 25 or fewer characters 21              courseNameValue = value ' store the course name in the object 22           Else ' if name has more than 25 characters 23              ' set courseNameValue to first 25 characters of parameter name 24              ' start at 0, length of 25 25              courseNameValue = value.Substring(0, 25) 26 27              Console.WriteLine( _ 28                 "Course name (" & value &") exceeds maximum length (25).") 29              Console.WriteLine( _ 30                 "Limiting course name to first 25 characters." & vbCrLf) 31           End If 32        End Set 33     End Property ' CourseName 34 35     ' display a welcome message to the GradeBook user 36     Public Sub DisplayMessage() 37        ' this statement uses property CourseName to get the 38        ' name of the course this GradeBook represents 39        Console.WriteLine("Welcome to the grade book for " _ 40            & vbCrLf & CourseName & "!" & vbCrLf) 41     End Sub ' DisplayMessage 42 43     ' determine class average based on 10 grades entered by user 44     Public Sub DetermineClassAverage() 45        Dim total As Integer ' sum of grades entered by user 46        Dim gradeCounter As Integer ' number of grades input 47        Dim grade As Integer ' grade input by user 48        Dim average As Integer ' average of grades 49 50        ' initialization phase 51        total = 0 ' set total to zero 52        gradeCounter = 1 ' prepare to loop 53 54        ' processing phase 55        While gradeCounter <= 10 ' loop 10 times 56           ' prompt for and input grade from user 57           Console.Write("Enter grade: ") ' prompt for grade 58           grade = Console.ReadLine() ' input the next grade 59           total += grade ' add grade to total 60           gradeCounter += 1 ' add 1 to gradeCounter 61        End While 62 63        ' termination phase 64        average = total \ 10 ' integer division yields integer result 65 66        ' display total and average of grades 67        Console.WriteLine(vbCrLf & "Total of all 10 grades is " & total) 68        Console.WriteLine("Class average is " & average) 69     End Sub ' DetermineClassAverage 70  End Class ' GradeBook 

Figure 5.11. Module GradeBookTest creates an object of class GradeBook (Fig. 5.10) and invokes its DetermineClassAverage method.

  1  ' Fig. 5.11: GradeBookTest.vb  2  ' Create GradeBook object and invoke its DetermineClassAverage method.  3  Module GradeBookTest  4     Sub Main()  5        ' create GradeBook object gradeBook and  6        ' pass course name to constructor  7        Dim gradeBook As New GradeBook("CS101 Introduction to VB")  8  9        gradeBook.DisplayMessage() ' display welcome message 10        gradeBook.DetermineClassAverage() ' find average of 10 grades 11     End Sub ' Main 12  End Module ' GradeBookTest 

Welcome to the grade book for CS101 Introduction to VB! Enter grade: 65 Enter grade: 78 Enter grade: 89 Enter grade: 67 Enter grade: 87 Enter grade: 98 Enter grade: 93 Enter grade: 85 Enter grade: 82 Enter grade: 100 Total of all 10 grades is 844 Class average is 84 



Implementing Counter-Controlled Repetition in Class GradeBook

Class GradeBook (Fig. 5.10) contains a constructor (lines 810) that assigns a value to the class's property CourseName. Lines 1433 and 3641 declare property CourseName and method DisplayMessage, respectively. Lines 4469 declare method DetermineClassAverage, which implements the class-averaging algorithm.

Lines 4548 declare local variables total, gradeCounter, grade and average to be of type Integer. In this example, variable total accumulates the sum of the grades entered and gradeCounter counts the number of grades entered. Variable grade stores the most recent grade value entered (line 58).

Note that the declarations (in lines 4548) appear in the body of method DetermineClassAverage. Recall that variables declared in a method body are local variables and can be used only from their declaration until the end of the method declaration. A local variable's declaration must appear before the variable is used in that method. A local variable cannot be accessed outside the method in which it is declared. In Visual Basic, numeric variables are initialized by default to 0 when they are declared, unless another value is assigned to the variable in its declaration.

In the versions of class GradeBook in this chapter, we simply read and process a set of grades. The averaging calculation is performed in method DetermineClassAverage using local variableswe do not preserve any information about student grades in instance variables of the class. In versions of the class in Chapter 8, Arrays, we maintain the grades in memory using an instance variable that refers to an array. This allows a GradeBook object to perform various calculations on the same set of grades without requiring the user to enter the grades multiple times.

The assignments (in lines 5152) initialize total to 0 and gradeCounter to 1.Line 55 indicates that the While statement should continue looping as long as the value of gradeCounter is less than or equal to 10. While this condition remains true, the While statement repeatedly executes the statements in its body (lines 5760).

Line 57 displays the prompt "Enter grade: ". Line 58 reads the grade entered by the user and assigns it to the variable grade. Then line 59 adds the new grade entered by the user into the variable total.

Line 60 adds 1 to gradeCounter to indicate that the program has processed another grade and is ready to input the next grade from the user. Incrementing gradeCounter eventually causes it to exceed 10. At that point the While loop terminates because its condition (line 55) becomes false.

When the loop terminates, line 64 performs the averaging calculation and assigns its result to the variable average. Line 67 displays the text "Total of all 10 grades is " followed by variable total's value. Line 68 then displays the text "Class average is " followed by variable average's value. Method DetermineClassAverage returns control to the calling method (i.e., Main in GradeBookTest of Fig. 5.11) after reaching line 69.

Module GradeBookTest

Module GradeBookTest (Fig. 5.11) creates an object of class GradeBook (Fig. 5.10) and demonstrates its capabilities. Line 7 of Fig. 5.11 creates a new GradeBook object and assigns it to variable gradeBook. The string in line 7 is passed to the GradeBook constructor (lines 810 of Fig. 5.10). Line 9 calls gradeBook's DisplayMessage method to display a welcome message to the user. Line 10 then calls gradeBook's DetermineClassAverage method to allow the user to enter 10 grades, for which the method then calculates and prints the average, performing the algorithm shown in Fig. 5.10.

Notes on Integer Division

The averaging calculation performed by method DetermineClassAverage in response to the method call at line 10 in Fig. 5.11 produces an integer result. The program's output indicates that the sum of the grade values in the sample execution is 844, which, when divided by 10, should yield the floating-point number 84.4. However, the result of the calculation total \ 10 (line 64 of Fig. 5.10) is the integer 84, because the integer division operator is used. Recall that the integer division operator takes two integer operands and returns an integer result. We use the floating-point division operator in the next section to determine a floating-point average.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net