Programming with Microsoft Visual Basic 2010 5th Edition Chapter Five More on the Selection Structure
Previewing the Math Practice Application Open Math.exe file The Math Practice application will be used by 1st and 2nd grade students
Previewing the Math Practice Application (cont’d.) Figure 5-1 Math Practice application’s user interface
Lesson A Objectives After studying Lesson A, you should be able to: Include a nested selection structure in pseudocode and in a flowchart Code a nested selection structure Desk-check an algorithm Recognize common logic errors in selection structures
Lesson A Objectives (cont’d.) Include a multiple-alternative selection structure in pseudocode and in a flowchart Code a multiple-alternative selection structure
Nested Selection Structures Used to make a decision and select the appropriate path Nested selection structure Selection structure that lies on true or false path of an outer selection structure Two decisions are involved Primary decision: Made by outer structure Secondary decision: Made by inner structure
Figure 5-3 Selection structures you might use today
The Voter Eligibility Application Figure 5-4 Problem specification for the Voter Eligibility application
The Voter Eligibility Application (cont’d.) Figure 5-5 Sample run of the Voter Eligibility application
Figure 5-6 Flowchart showing the nested selection structure in the true path
Figure 5-7 Flowchart showing the nested selection structure in the false path
Figure 5-8 Code for the flowcharts in Figures 5-6 and 5-7 (continues)
Figure 5-8 Code for the flowcharts in Figures 5-6 and 5-7 (cont’d.)
Logic Errors in Selection Structures Common logic errors Using compound condition instead of nested structure Reversing primary and secondary decisions Using unnecessary nested selection structure Algorithm Set of step-by-step instructions for accomplishing a task
Logic Errors in Selection Structures (cont’d.) Desk-checking (or hand-tracing) Using pencil and paper to follow algorithm’s steps Using sample data Goal is to verify that algorithm is correct
Logic Errors in Selection Structures (cont’d.) Figure 5-9 A correct algorithm for the bonus procedure
Logic Errors in Selection Structures (cont’d.) Figure 5-10 Results of desk-checking the correct algorithm
Using a Compound Condition Rather Than a Nested Selection Structure Bonus scenario Calculate bonus amount for all employee types Give extra bonus to X contingent on sales amount Display the bonus amount Problem when using compound condition It does not indicate hierarchy in decision process Nested selection structure does enforce hierarchy of decisions Extra bonus decision depends on sales type decision
Figure 5-11 Correct algorithm and an incorrect algorithm containing the first logic error
Figure 5-12 Results of desk-checking the incorrect algorithm shown in Figure 5-11
Reversing the Primary and Secondary Decisions Incorrect algorithm reverses primary and secondary decisions All salespeople with sales >= 10000 get extra bonus Amount of bonus depends on sales type Extra bonus decision should depend on sales type decision first Reminder: Desk-check your algorithm with sample data to verify its correctness
Figure 5-13 Correct algorithm and an incorrect algorithm containing the second logic error
Reversing the Primary and Secondary Decisions (cont’d.) Figure 5-14 Results of desk-checking the incorrect algorithm shown in Figure 5-13
Using an Unnecessary Nested Selection Structure Problem with incorrect algorithm Adds extra, redundant selection structure on inner false path Extra code reduces efficiency and readability The redundant selection structure: Makes decision that was already decided in prior selection structure Solution: Eliminate second nested structure
Using an Unnecessary Nested Selection Structure (cont’d.) Figure 5-15 Correct algorithm and an incorrect algorithm containing the third logic error
Using an Unnecessary Nested Selection Structure (cont’d.) Figure 5-16 Results of desk-checking the inefficient algorithm shown in Figure 5-15
Multiple-Alternative Selection Structures Designed to choose from several alternatives Condition in multiple-alternative selection structure does not require true/false answer Requires expression whose value determines which path is chosen Example: Display message based on grades ranging from A to F
Multiple-Alternative Selection Structures (cont’d.) Figure 5-17 Letter grades and messages
Figure 5-18 Pseudocode containing a multiple-alternative selection structure
Figure 5-19 Flowchart containing a multiple-alternative selection structure
Multiple-Alternative Selection Structures (cont’d.) Figure 5-20 Shows two versions of code for btnDisplay control’s Click event procedure Both versions use If…Then…Else statements Second version contains more convenient way of writing a multiple- alternative selection structure
Figure 5-20 Two versions of the code containing a multiple-alternative selection structure (continues)
Figure 5-20 Two versions of the code containing a multiple-alternative selection structure (cont’d.)
The Select Case Statement Simpler and clearer when there are many paths Select Case statement Begins with Select Case, ends with End Select Each case represents a different instruction path Optional Case Else clause handles all values not covered by other Case paths selectorExpression is evaluated to determine path Each case, except Case Else, has expressionList that is compared to selectorExpression
Figure 5-22 Syntax and an example of the Select Case statement (continues)
Figure 5-22 Syntax and an example of the Select Case statement (cont’d
Specifying a Range of Values in a Case Clause To specify range of minimum and maximum values To keyword: Use if both upper and lower bounds are known Is keyword: Use if only upper or lower bound is known Example with To: Case 1 To 5 Example with Is: Case Is > 10 Comparison operators used with Is = , < , <= , > , >= , <>
Figure 5-23 Syntax and an example of specifying a range of values
Lesson A Summary Nested selection structure lies on true or false path of outer selection structure Desk-check Validate algorithm by hand with sample data Multiple-alternative selection structures Use If/ElseIf/Else statement or Select Case statement Use To and Is keywords to specify range of values in Case clause of Select Case statement
Lesson B Objectives After studying Lesson B, you should be able to: Include a group of radio buttons in an interface Designate a default radio button Include a check box in an interface Create and call an independent Sub procedure Generate random numbers
Creating the Math Practice Application Objective: Practice addition and subtraction Specifications 1st grade students use numbers 1 through 10 2nd grade students use numbers 10 through 99 Should not allow problems whose answers will be negative numbers Students should be able to check their answers Extra attempts allowed when answer is incorrect Application should track and display number of correct and incorrect responses
Adding a Radio Button to the Form Limits user to one choice in group of options Should be labeled so its purpose is understood Should have unique keyboard access key RadioButton tool: Used to add radio button Each group of radio buttons must be placed within container such as group box Default radio button: Button initially selected Set Checked property to True
Adding a Radio Button to the Form (cont’d.) Figure 5-29 Subtraction radio button added to the Operation group box
Adding a Check Box Control to the Form Allows multiple selections among group of choices Any number of check boxes can be selected at once Does not limit choices like radio button control Should be labeled to indicate its purpose Checkbox tool: Used to add check box control Lock controls, then set TabIndex after interface design is complete
Adding a Check Box Control to the Form (cont’d.) Figure 5-30 Display summary check box added to the form
Coding the Math Practice Application Procedures to code based on TOE chart Form’s load event procedure Click event procedures for seven controls One task will be coded with an independent Sub procedure Generating and displaying two random numbers
Creating an Independent Sub Procedure Event procedure Sub procedure associated with specific object and event Processed when specific event occurs Independent Sub procedure Processed only when called (invoked) from code Can be invoked from one or more places in an application Not associated with specific control Reduces amount of code; promotes modularity
Figure 5-33 Independent Sub procedure syntax, example, and steps
Figure 5-34 Pseudocode for the GenerateAndDisplayIntegers procedure
Generating Random Integers Pseudo-random number generator Device that produces sequence of pseudo-random numbers Pseudo-random: Values statistically resemble randomness To use pseudo-random number generator: Create Random object within procedure Generate random integers with Random.Next method
Figure 5-35 Syntax and examples of generating random integers
Figure 5-36 Random number generation code entered in the procedure
Figure 5-37 Additional comments and code entered in the procedure
Coding the Grade Radio Buttons’ Click Event Procedures Radio button controls should invoke GenerateAndDisplayNumbers procedure Call statement: Invokes independent procedure Syntax Call procedureName([argumentList]) procedureName: Name of procedure to be invoked argumentList: Optional list of arguments to pass Keyword Call is optional Can simply use procedure name
Figure 5-38 Syntax and examples of the Call statement
Coding the Operation Radio Buttons’ Click Event Procedures Requirements for Click event procedures Display appropriate mathematical operator (+ or -) Generate and display two random integers Show addition problem by default when program starts
Coding the Form’s Load Event Procedure Processed when application is started Form is not displayed until its instructions are processed Two ways to initially display addition problem Call GenerateAndDisplayIntegers() radAddition.PerformClick() Enter either statement in Load event procedure
Lesson B Summary Radio button control Check box control Limits user to only one choice among group of choices Check box control Allows user to select multiple choices in a group Independent Sub procedures Not linked to controls and can be invoked anywhere in program Use Random object to generate pseudo-random numbers
Lesson B Summary (cont’d.) Call statement Used to call (invoke) independent Sub procedure Use object.PerformClick() to invoke object’s Click event
Lesson C Objectives After studying Lesson C, you should be able to: Code a check box’s Click event procedure Show and hide a control
Coding the Check Answer Button’s Click Event Procedure Study procedure’s pseudocode to determine what variables and named constants are needed Six integer variables and one named constant are needed Two variables have static storage type
Figure 5-44 Pseudocode for the btnCheckAnswer control’s Click event procedure
Figure 5-45 Memory locations used by the btnCheckAnswer control’s Click event procedure
Coding the Display Summary Check Box’s Click Event Procedure chkSummary control’s Click event procedure Displays and hides grpSummary control When user selects check box, event is triggered, showing group box and its contents When user deselects check box, event is triggered, hiding group box control Checked property indicates whether check box is selected Visible property indicates whether control is shown
Lesson C Summary To show or hide control, set control’s Visible property Use selection structure to determine if check box was either selected or deselected by user