Home > Articles > Programming > Windows Programming

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

3

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

8

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
7
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
14 
15         gradeTextBox.Focus() ' gives the focus to the gradeTextBox
16      End Sub ' submitGradeButton_Click
17
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
21
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
26
27         ' initialization phase
28         total = 0 ' set total to zero before adding grades to it
29         gradeCounter = 0 ' prepare to loop
30
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
37
38         ' termination phase
39         If gradeCounter <> 0 Then
40         average = total / gradesListBox.Items.Count ' calculate average
41
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
50
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
54
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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020