Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

4.10 Formulating Algorithms: Counter-Controlled Repetition

To illustrate how algorithms are developed, we solve a problem that averages student grades. Consider the following problem statement:

A class of 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. The algorithm for solving this problem on a computer must input each grade, keep track of the total of all grades input, perform the averaging calculation and display the result.

GUI for the Class-Average Application

Figure 4.10 shows this application's GUI. For this example, we introduce the ListBox control, which we use to display the grades the user enters and to manipulate those grades to perform the class-average calculation. Each grade that the user enters into the program by pressing the Submit Grade Button is placed in the ListBox. We calculate the class average when the user presses the Calculate Average Button. We also provide a Clear Grades Button to remove all the grades from the ListBox and clear the results, so the user can enter a new set of grades.

Figure 4.10

Fig. 4.10 GUI for the class-average problem.

Setting the Form 's Default Button

When you execute this program, notice that the Submit Grade Button has a blue highlight around it. This Button is the Form's default Button—the one that will be pressed when the user presses the Enter key. In this program, the user can type a value in the TextBox and press Enter to press the Submit Grade Button rather than clicking it with the mouse. This convenience feature enables the user to rapidly enter grades. You can specify a Form's default Button in the Properties window by setting the Form's AcceptButton property to the appropriate Button. For this program, we set the AcceptButton property to the submitGradeButton.

Pseudocode Algorithm with Counter-Controlled Repetition

Let's use pseudocode to list the actions to execute and specify the order of execution for calculating the class average. After the user enters the grades and presses the Calculate Average Button, we use counter-controlled repetition to get the grades from the ListBox and process them one at a time. This technique uses a variable called a counter (or control variable) to specify the number of times that a set of statements will execute. This is also called definite repetition because the number of repetitions is known before the loop begins executing. In this example, repetition terminates when the counter exceeds the number of grades in the ListBox. Figure 4.11 presents a fully developed pseudocode algorithm and Fig. 4.12 presents the program that implements the algorithm. In the next section, you'll learn how to develop pseudocode algorithms and convert them to Visual Basic. (In Exercise 4.15, you'll use counter-controlled repetition to output a table of values.)

Fig 4.11. Pseudocode algorithm that uses counter-controlled repetition to solve the class-average problem.

1   Set total to zero

2   Set grade counter to zero


4   While grade counter is less than the number of grades

5   Get the next grade

6   Add the grade into the total

7   Add one to the grade counter


9   If the grade counter is not equal to zero then

10  Set the class average to the total divided by the number of grades

11  Display the class average

12  Else

13  Display "No grades were entered"

Fig 4.12. Counter-controlled repetition: Class-average problem.

1   ' Fig. 4.12: ClassAverage.vb
2   ' Counter-controlled repetition: Class-average problem.
3   Public Class ClassAverage
4      ' place a grade in the gradesListBox
5   Private Sub submitGradeButton_Click(ByVal sender As System.Object,
6   ByVal e As System.EventArgs) Handles submitGradeButton.Click
8         ' if the user entered a grade
9         If gradeTextBox.Text <> String.Empty Then
10        ' add the grade to the end of the gradesListBox
11        gradesListBox.Items.Add(gradeTextBox.Text)     
12            gradeTextBox.Clear() ' clear the gradeTextBox
13        End If
15         gradeTextBox.Focus() ' gives the focus to the gradeTextBox
16      End Sub ' submitGradeButton_Click
18      ' calculates the class average based on the grades in gradesListBox
19      Private Sub calculateAverageButton_Click(ByVal sender As System.Object,
20      ByVal e As System.EventArgs) Handles calculateAverageButton.Click
22         Dim total As Integer ' sum of grades entered by user
23          Dim gradeCounter As Integer ' counter for grades
24         Dim grade As Integer ' grade input by user
25         Dim average As Double ' average of grades
27         ' initialization phase
28         total = 0 ' set total to zero before adding grades to it
29         gradeCounter = 0 ' prepare to loop
31         ' processing phase
32         Do While gradeCounter < gradesListBox.Items.Count
33         grade = gradesListBox.Items(gradeCounter) ' get next grade
34            total += grade ' add grade to total
35         gradeCounter += 1 ' add 1 to gradeCounter
36         Loop
38         ' termination phase
39         If gradeCounter <> 0 Then
40         average = total / gradesListBox.Items.Count ' calculate average
42            ' display total and average (with two digits of precision)
43            classAverageLabel.Text = "Total of the " & gradeCounter &
44         " grade(s) is " & total & vbCrLf & "Class average is " &
45         String.Format("{0:F}", average)
46         Else
47            classAverageLabel.Text = "No grades were entered"
48         End If
49      End Sub ' calculateAverageButton_Click
51      ' clear grades from gradeListBox and results from classAverageLabel
52      Private Sub clearGradesButton_Click(ByVal sender As System.Object,
53      ByVal e As System.EventArgs) Handles clearGradesButton.Click
55         gradesListBox.Items.Clear() ' removes all items from gradesListBox
56         classAverageLabel.Text = String.Empty ' clears classAverageLabel
57      End Sub ' clearGradesButton_Click
58   End Class ' ClassAverage

Note the references in the pseudocode algorithm (Fig. 4.11) to a total and a counter. A total is a variable used to accumulate the sum of several values. A counter is a variable used to count—in this case, the grade counter records the number of grades input by the user. It's important that variables used as totals and counters have appropriate initial values before they're used. Counters usually are initialized to 0 or 1, depending on their use. Totals generally are initialized to 0. Numeric variables are initialized to 0 when they're declared, unless another value is assigned to the variable in its declaration.

In the pseudocode, we add one to the grade counter only in the body of the loop (line 7). If the user does not enter any grades, the condition "grade counter is less than the number of grades" (line 4) will be false and grade counter will be zero when we reach the part of the algorithm that calculates the class average. We test for the possibility of division by zero—a logic error that, if undetected, would cause the program to fail.

Implementing Counter-Controlled Repetition

The ClassAverage class (Fig. 4.12) defines the Click event handlers for the submitGradeButton, calculateAverageButton and clearGradesButton. The calculateAverageButton_Click method (lines 19–49) implements the class-averaging algorithm described by the pseudocode in Fig. 4.11.

Method submitGradeButton_Click

When the user presses the Submit Grade Button, method submitGradeButton_Click (lines 5–16) obtains the value the user typed and places it in the gradesListBox. Line 9 first ensures that the gradeTextBox is not empty by comparing its Text property to the constant String.Empty. This prevents the program from inserting an empty string in the ListBox, which would cause the program to fail when it attempts to process the grades. This is the beginning of our efforts to validate data entered by the user. In later chapters, we'll ensure that the data is in range (for example, an Integer representing a month needs to be in the range 1–12) and that data meets various other criteria. For this program, we assume that the user enters only Integer values—noninteger values could cause the program to fail when the grades are processed.

If the gradeTextBox is not empty, line 11 uses the ListBox's Items property to add the grade to the ListBox. This property keeps track of the values in the ListBox. To place a new item in the ListBox, call the Items property's Add method, which adds the new item at the end of the ListBox. Line 12 then clears the value in the gradeTextBox so the user can enter the next grade. Line 15 calls the gradeTextBox's Focus method, which makes the TextBox the active control—the one that will respond to the user's interactions. This allows the user to immediately start typing the next grade, without clicking the TextBox.

Method calculateAverageButton_Click ; Introducing Type Double and Floating-Point Numbers

Method calculateAverageButton_Click (lines 19–49) uses the algorithm in Fig. 4.11 to calculate the class average and display the results. Lines 22–24 declare variables total, gradeCounter and grade to be of type Integer. Line 25 declares variable average to be of type Double. Although each grade is an Integer, the average calculation uses division, so it is likely to produce a number with a fractional result. Such numbers (like 84.4) contain decimal points and are called floating-point numbers. Type Double is typically used to store floating-point numbers. All the floating-point numbers you type in aprogram's source code (such as 7.33 and 0.0975) are treated as Double values by default and are known as floating-point literals. Values of type Double are represented approximately in memory. For precise calculations, such as those used in financial calculations, Visual Basic provides type Decimal (discussed in Section 5.4).

Variable total accumulates the sum of the grades entered. Variable gradeCounter helps us determine when the loop at lines 32–36 should terminate. Variable grade stores the most recent grade value obtained from the ListBox (line 33). Variable average stores the average grade (line 40).

The declarations (in lines 22–25) appear in the body of method calculateAverageButton_Click. Variables declared in a method body are so-called 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.

The assignments (in lines 28–29) initialize total and gradeCounter to 0. Line 32 indicates that the Do While...Loop statement should continue looping (also called iterating) while gradeCounter's value is less than the ListBox's number of items. ListBox property Items keeps track of the ListBox's number of items, which you can access via the expression gradesListBox.Items. Count. While this condition remains true, the Do While...Loop statement repeatedly executes the statements in its body (lines 33–35).

Line 33 reads a grade from the ListBox and assigns it to the variable grade. Each value in the ListBox's Items property has a position number associated withit—this is known as the item's index. For example, in the sample output of Fig. 4.12, the grade 65 is at index 0, 78 is at index 1, 89 is at index 2, and so on. The index of the last item is always one less than the total number of items represented by the ListBox's Items.Count property. To get the value at a particular index, we use the expression:

 grade = gradesListBox.Items(gradeCounter)

in which gradeCounter's current value is the index.

Line 34 adds the new grade entered by the user into the variable total using the += compound assignment operator. Line 35 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 the loop to terminate when the condition gradeCounter <gradesListBox.Items.Count becomes false.

When the loop terminates, the If...Then...Else statement at lines 39–48 executes. Line 39 determines whether any grades have been entered. If so, line 40 performs the averaging calculation using the floating-point division operator (/) and stores the result in Double variable average. If we used the integer division operator (\), the class average would not be as precise because any fractional part of the average would be discarded. For example, 844 divided by 10 is 84.4, but with integer division the result would be 84. Lines 43–45 display the results in the classAverageLabel. If no grades were entered, line 47 displays a message in the classAverageLabel.

Method clearGradesButton_Click

When the user presses the Clear Grades Button, method clearGradesButton_Click (lines 52–57) prepares for the user to enter a new set of grades. First, line 55 removes the grades from the gradesListBox by calling the Item's property's Clear method. Then, line 56 clears the text on the classAverageLabel.

Control Statement Stacking

In this example, we see that control statements may be stacked on top of one another (that is, placed in sequence) just as a child stacks building blocks. The Do While...Loop statement (lines 32–36) is followed in sequence by an If...Then...Else statement (lines 39–48).

Formatting for Floating-Point Numbers

The statement in lines 43–45 outputs the class average. In this example, we decided to display the class average rounded to the nearest hundredth and to output the average with exactly two digits to the right of the decimal point. To do so, we used the expression

String.Format("{0:F}", average)

which indicates that average's value should be displayed as a number with a specific number of digits to the right of the decimal point—called a fixed-point number. This is an example of formatted output, in which you control how a number appears for display purposes. The String class's Format method performs the formatting. The first argument to the method ("{0:F}") is the format string, which acts as a placeholder for the value being formatted. The numeric value that appears before the colon (in this case, 0) indicates which of Format's arguments will be formatted—0 specifies the first argument after the format string passed to Format, namely average. As you'll see in later examples, additional values can be inserted into the string to specify other arguments. The value after the colon (in this case, F ) is known as a format specifier, which indicates how a value is to be formatted. The format specifier F indicates that a fixed-point number should be rounded to two decimal places by default. The entire placeholder ({0:F}) is replaced with the formatted value of variable average. You can change the number of decimal places to display by placing an integer value after the format specifier—for example, the string "{0:F3}" rounds the number to three decimal places.

  • + Share This
  • 🔖 Save To Your Account