Home > Articles > Programming > Windows Programming

This chapter is from the book

4.11 Formulating Algorithms: Nested Control Statements

We've seen that control statements can be stacked on top of one another (in sequence). We now examine the only other structured way that control statements can be combined—by nesting one control statement inside another.

Problem Statement and Notes

Consider the following problem statement:

  • A college offers a course that prepares students for the state real estate broker licensing exam. Last year, 10 of the students who completed this course took the exam. The college wants to know how well its students did. You've been asked to write a program to summarize the results. You've been given a list of the 10 students. Next to each name is written a "P" if the student passed the exam and an "F" if the student failed the exam.
  • Your program should analyze the results of the exam as follows:
  1. Input each exam result (that is, a "P" or an "F").
  2. Count the number of passes and the number of failures.
  3. Display a summary of the exam results, indicating the number of students who passed and the number who failed.
  4. If more than eight students passed the exam, display the message "Bonus to Instructor."

After reading the problem statement carefully, we make the following observations:

  1. The program must process exam results for 10 students. A counter-controlled loop can be used because the number of test results is known in advance.
  2. Each exam result is a string—either a "P" or an "F." When the program reads an exam result, it must determine whether the result is a "P" or an "F." We test for a "P" in our algorithm. If the input is not a "P," we assume it's an "F." An exercise at the end of the chapter considers the consequences of this assumption. For instance, consider what happens when the user enters a lowercase "p."
  3. Two counters store the exam results—one counts the number of students who passed the exam and the other counts the number of students who failed.
  4. After the program has processed all the exam results, it must determine whether more than eight students passed the exam, and, if so, bonus the instructor.

GUI for the Licensing-Exam Analysis Application

Figure 4.13 shows this application's GUI. Each result is placed in the ListBox when the user presses the Submit Result Button. We process all 10 results when the user presses the Analyze Results Button. We also provide a Clear Results Button to reset the GUI so the user can enter a new set of results. As in the previous example, we used the Form's Accept-Button property to set the Submit Result Button as the default Button. We disabled the Analyze Results Button initially by setting its Enabled property to False.

Figure 4.13

Fig. 4.13 GUI for the licensing-exam analysis problem.

Developing the Pseudocode Algorithm with Top-Down, Stepwise Refinement: The Top and the First Refinement

We approach this program with top-down, stepwise refinement, a technique for developing well-structured algorithms. We begin with a pseudocode representation of the top—a single statement that conveys the overall function of the program:

   Analyze exam results and decide if the instructor should receive a bonus

The top is a complete representation of a program. Unfortunately, the top rarely conveys enough detail from which to write a program, so we conduct the refinement process. We divide the top into a series of smaller tasks and list them in the order in which they must be performed, resulting in the following first refinement:

   Initialize variables

   Input the 10 exam results, and count passes and failures

   Display a summary of the exam results and decide if the instructor should
   
   receive a bonus

Proceeding to the Second Refinement

To proceed to the second refinement, we commit to specific variables. In this example, counters are needed to record the passes and failures. A counter controls the looping process and a variable stores the user input. The pseudocode statement

   Initialize variables

can be refined as follows:

   Initialize passes to zero

   Initialize failures to zero

   Initialize student to zero

Only the counters for the number of passes, number of failures and number of students need to be initialized before they're used. The variable we use to store each value the user enters does not need to be initialized because the assignment of its value does not depend on its previous value, as is the case for the counter variables.

The pseudocode statement

   Input the 10 exam results, and count passes and failures

requires a repetition statement (that is, a loop) that successively inputs the result of each exam. We know in advance that there are 10 exam results, so counter-controlled looping is appropriate. Inside the loop (that is, nested inside the loop), a double-selection statement will determine whether each exam result is a pass or a failure and will increment the appropriate counter. The refinement of the preceding pseudocode statement is then

   While student counter is less than or equal to 10
   
   Get the next exam result

   
   If the student passed then
       
   Add one to passes
   
   Else
       
   Add one to failures

   
   Add one to student counter

Note the use of blank lines to set off the If...Else control statement to improve readability.

The pseudocode statement

   Display a summary of the exam results and decide if the instructor should
   
   receive a bonus

may be refined as follows:

   Display the number of passes

   Display the number of failures


   If more than eight students passed then
   
   Display "Bonus to instructor!"

Complete Second Refinement of Pseudocode

The complete second refinement of the pseudocode appears in Fig. 4.14. Blank lines are also used to set off the While loop (lines 5–13) for readability. This pseudocode is now sufficiently refined for conversion to Visual Basic.

Fig 4.14. Pseudocode for examination-results problem.

 
1   Initialize passes to zero
2   Initialize failures to zero
3   Initialize student to zero
4
5   While student counter is less than or equal to 10
6      Get the next exam result
7
8      If the student passed then
9        Add one to passes
10      Else

11         Add one to failures
12
13      Add one to student counter

14
15  Display the number of passes

16  Display the number of failures

17
18 If more than eight students passed then

19 Display "Bonus to instructor!"

Class Analysis

The program that implements the pseudocode algorithm and the sample outputs are shown in Fig. 4.15. We defined the Click event handlers for the submitResultButton, analyzeResultsButton and clearResultsButton. The analyzeResultsButton_Click method (lines 24–55) implements the class-averaging algorithm described by the pseudo-code in Fig. 4.14.

Fig 4.15. Nested control statements: Examination-results problem.

 
1  ' Fig. 4.15: Analysis.vb
2  ' Nested control statements: Examination-results problem.
3  Public Class Analysis
4     ' place a result in the resultsListBox
5  Private Sub submitResultButton_Click(ByVal sender As System.Object,
6  ByVal e As System.EventArgs) Handles submitResultButton.Click
7
8  If resultsListBox.Items.Count < 10 Then
9          ' add the grade to the end of the resultsListbox
10           resultsListBox.Items.Add(resultTextBox.Text)
11           resultTextBox.Clear() ' clear the resultTextBox
12           resultTextBox.Focus() ' select the resultTextBox
13   End If
14
15        ' determine whether to prevent the user from entering more results
16        If resultsListBox.Items.Count = 10 Then
17         submitResultButton.Enabled = False ' disables submitResultButton 
18         resultTextBox.Enabled = False ' disables resultTextBox           
19         analyzeResultsButton.Enabled = True ' enable analyzeResultsButton
20        End If
21     End Sub  ' submitResultButton_Click
22
23     ' analyze the results
24     Private Sub analyzeResultsButton_Click(ByVal sender As System.Object,
25        ByVal e As System.EventArgs) Handles analyzeResultsButton.Click
26
27        ' initializing variables in declarations        
28        Dim passes As Integer = 0 ' number of passes    
29        Dim failures As Integer = 0 ' number of failures
30        Dim student As Integer = 0 ' student counter    
31        Dim result As String ' one exam result
32
33        ' process 10 students using counter-controlled loop
34        Do While student < 10
35           result = resultsListBox.Items(student) ' get a result
36
37           ' nested control statement                     
38           If result = "P" Then                           

39              passes += 1 ' increment number of passes    
40           Else                                           

41              failures += 1 ' increment number of failures
42           End If                                         

43
44           student += 1 ' increment student counter
45        Loop
46
47        ' display exam results
48        analysisResultsLabel.Text =
49           "Passed: " & passes & vbCrLf & "Failed: " & failures & vbCrLf
50
51        ' raise tuition if more than 8 students passed
52       If passes > 8 Then
53           analysisResultsLabel.Text &= "Bonus to instructor!"
54        End If
55     End Sub ' analyzeResultsButton_Click
56
57     ' clears the resultsListBox and analysisResultsLabel
58     Private Sub clearResultsButton_Click(ByVal sender As System.Object,
59       ByVal e As System.EventArgs) Handles clearResultsButton.Click
60
61         resultsListBox.Items.Clear() ' removes all items
62         analysisResultsLabel.Text = String.Empty ' clears the text
63         submitResultButton.Enabled = True ' enables submitResultButton      
64         resultTextBox.Enabled = True ' enables resultTextBox                
65         analyzeResultsButton.Enabled = False ' disables analyzeResultsButton
66         resultTextBox.Focus() ' select the resultTextBox
67      End Sub ' clearResultsButton_Click
68   End Class ' Analysis

Method submitResultButton_Click

When the user presses the Submit Result button, method submitResultButton_Click (lines 5–21) executes. The problem statement specified that the user can enter only 10 results, so we need to keep track of the number of results that have been entered. Since the ListBox property Items keeps track of the ListBox's total number of items, we use its Count property in line 8 to determine whether 10 results have been entered. If not, line 10 adds the next result to the ListBox, line 11 clears the TextBox and line 12 gives the Text-Box the focus so the user can enter the next result. The last result entered could have been the 10th result (line 16). If so, lines 17–18 disable the submitResultButton and the resultTextBox by setting their Enabled properties to False. This prevents the user from interacting with these two controls, so the user cannot enter more than 10 results. Line 19 enables analyzeResultsButton by setting its Enabled property to True so the user can tell the program to analyze the results.

Method analyzeResultsButton_Click

Method analyzeResultsButton_Click (lines 24–55) uses the algorithm in Fig. 4.14 to calculate the class average and display the results. Lines 28–31 declare the variables the algorithm uses to process the examination results. Several of these declarations incorporate variable initialization—passes, failures and student are all initialized to 0.

The Do While...Loop statement (lines 34–45) loops 10 times. During each iteration, the loop inputs and processes one exam result from the ListBox. The If...Then...Else statement (lines 38–42) for processing each result is nested in the Do While...Loop statement. If the result is "P", the If...Then...Else statement increments passes; otherwise, it assumes the result is "F" and increments failures. Strings are case sensitive by default—uppercase and lowercase letters are different. Only "P" represents a passing grade. In Exercise 4.13, we ask you to enhance the program by processing lowercase inputs such as "p" and "f".

Line 44 increments student before the loop condition is tested again at line 34. After 10 values have been processed, the loop terminates and lines 48–49 display the number of passes and failures. The If...Then statement at lines 52–54 determines whether more than eight students passed the exam and, if so, displays "Bonus to instructor!". In the first sample execution, the condition at line 52 is True—more than eight students passed the exam, so the program outputs the bonus message.

Method clearResultsButton_Click

When the user presses the Clear Results Button, method clearResultsButton_Click (lines 58–67) prepares for the user to enter a new set of results. Line 61 removes the results from the resultsListBox by calling the Item property's Clear method. Line 62 clears the text on the analysisResultsLabel. Lines 63 and 64 enable the submitResultButton and the resultTextBox by setting their Enabled properties to True—the user can now interact with these controls again. Line 65 disables the analyzeResultsButton by settingits Enabled property to False so the user cannot click it. Line 66 gives the focus to the result-TextBox so the user can begin typing the next result immediately.

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