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 Programming with Microsoft Visual Basic 2010, 5th Edition 2 Previewing the Math Practice Application (cont’d.) Figure 5-1 Math Practice application’s user interface Programming with Microsoft Visual Basic 2010, 5th Edition 3 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 Programming with Microsoft Visual Basic 2010, 5th Edition 4 Lesson A Objectives (cont’d.) Include a multiple-alternative selection structure in pseudocode and in a flowchart Code a multiple-alternative selection structure Programming with Microsoft Visual Basic 2010, 5th Edition 5 Nested Selection Structures Selection structure ◦ 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 Programming with Microsoft Visual Basic 2010, 5th Edition 6 Figure 5-3 Selection structures you might use today Programming with Microsoft Visual Basic 2010, 5th Edition 7 The Voter Eligibility Application Figure 5-4 Problem specification for the Voter Eligibility application Programming with Microsoft Visual Basic 2010, 5th Edition 8 The Voter Eligibility Application (cont’d.) Figure 5-5 Sample run of the Voter Eligibility application Programming with Microsoft Visual Basic 2010, 5th Edition 9 Figure 5-6 Flowchart showing the nested selection structure in the true path Programming with Microsoft Visual Basic 2010, 5th Edition 10 Figure 5-7 Flowchart showing the nested selection structure in the false path Programming with Microsoft Visual Basic 2010, 5th Edition 11 Figure 5-8 Code for the flowcharts in Figures 5-6 and 5-7 (continues) Programming with Microsoft Visual Basic 2010, 5th Edition 12 Figure 5-8 Code for the flowcharts in Figures 5-6 and 5-7 (cont’d.) Programming with Microsoft Visual Basic 2010, 5th Edition 13 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 Programming with Microsoft Visual Basic 2010, 5th Edition 14 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 Programming with Microsoft Visual Basic 2010, 5th Edition 15 Logic Errors in Selection Structures (cont’d.) Figure 5-9 A correct algorithm for the bonus procedure Programming with Microsoft Visual Basic 2010, 5th Edition 16 Logic Errors in Selection Structures (cont’d.) Figure 5-10 Results of desk-checking the correct algorithm Programming with Microsoft Visual Basic 2010, 5th Edition 17 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 Programming with Microsoft Visual Basic 2010, 5th Edition 18 Figure 5-11 Correct algorithm and an incorrect algorithm containing the first logic error Programming with Microsoft Visual Basic 2010, 5th Edition 19 Figure 5-12 Results of desk-checking the incorrect algorithm shown in Figure 5-11 Programming with Microsoft Visual Basic 2010, 5th Edition 20 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 Programming with Microsoft Visual Basic 2010, 5th Edition 21 Figure 5-13 Correct algorithm and an incorrect algorithm containing the second logic error Programming with Microsoft Visual Basic 2010, 5th Edition 22 Reversing the Primary and Secondary Decisions (cont’d.) Figure 5-14 Results of desk-checking the incorrect algorithm shown in Figure 5-13 Programming with Microsoft Visual Basic 2010, 5th Edition 23 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 Programming with Microsoft Visual Basic 2010, 5th Edition 24 Using an Unnecessary Nested Selection Structure (cont’d.) Figure 5-15 Correct algorithm and an incorrect algorithm containing the third logic error Programming with Microsoft Visual Basic 2010, 5th Edition 25 Using an Unnecessary Nested Selection Structure (cont’d.) Figure 5-16 Results of desk-checking the inefficient algorithm shown in Figure 5-15 Programming with Microsoft Visual Basic 2010, 5th Edition 26 Multiple-Alternative Selection Structures 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 Programming with Microsoft Visual Basic 2010, 5th Edition 27 Multiple-Alternative Selection Structures (cont’d.) Figure 5-17 Letter grades and messages Programming with Microsoft Visual Basic 2010, 5th Edition 28 Figure 5-18 Pseudocode containing a multiple-alternative selection structure Programming with Microsoft Visual Basic 2010, 5th Edition 29 Figure 5-19 Flowchart containing a multiple-alternative selection structure Programming with Microsoft Visual Basic 2010, 5th Edition 30 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 multiplealternative selection structure Programming with Microsoft Visual Basic 2010, 5th Edition 31 Figure 5-20 Two versions of the code containing a multiple-alternative selection structure (continues) Programming with Microsoft Visual Basic 2010, 5th Edition 32 Figure 5-20 Two versions of the code containing a multiple-alternative selection structure (cont’d.) Programming with Microsoft Visual Basic 2010, 5th Edition 33 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 Programming with Microsoft Visual Basic 2010, 5th Edition 34 Figure 5-22 Syntax and an example of the Select Case statement (continues) Programming with Microsoft Visual Basic 2010, 5th Edition 35 Figure 5-22 Syntax and an example of the Select Case statement (cont’d.) Programming with Microsoft Visual Basic 2010, 5th Edition 36 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 = , < , <= , > , >= , <> Programming with Microsoft Visual Basic 2010, 5th Edition 37 Figure 5-23 Syntax and an example of specifying a range of values Programming with Microsoft Visual Basic 2010, 5th Edition 38 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 Programming with Microsoft Visual Basic 2010, 5th Edition 39 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 Programming with Microsoft Visual Basic 2010, 5th Edition 40 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 Programming with Microsoft Visual Basic 2010, 5th Edition 41 Adding a Radio Button to the Form Radio Button ◦ 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 Programming with Microsoft Visual Basic 2010, 5th Edition 42 Adding a Radio Button to the Form (cont’d.) Figure 5-29 Subtraction radio button added to the Operation group box Programming with Microsoft Visual Basic 2010, 5th Edition 43 Adding a Check Box Control to the Form Check box ◦ ◦ ◦ ◦ 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 Programming with Microsoft Visual Basic 2010, 5th Edition 44 Adding a Check Box Control to the Form (cont’d.) Figure 5-30 Display summary check box added to the form Programming with Microsoft Visual Basic 2010, 5th Edition 45 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 Programming with Microsoft Visual Basic 2010, 5th Edition 46 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 Programming with Microsoft Visual Basic 2010, 5th Edition 47 Figure 5-33 Independent Sub procedure syntax, example, and steps Programming with Microsoft Visual Basic 2010, 5th Edition 48 Figure 5-34 Pseudocode for the GenerateAndDisplayIntegers procedure Programming with Microsoft Visual Basic 2010, 5th Edition 49 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 Programming with Microsoft Visual Basic 2010, 5th Edition 50 Figure 5-35 Syntax and examples of generating random integers Programming with Microsoft Visual Basic 2010, 5th Edition 51 Figure 5-36 Random number generation code entered in the procedure Programming with Microsoft Visual Basic 2010, 5th Edition 52 Figure 5-37 Additional comments and code entered in the procedure Programming with Microsoft Visual Basic 2010, 5th Edition 53 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 Programming with Microsoft Visual Basic 2010, 5th Edition 54 Figure 5-38 Syntax and examples of the Call statement Programming with Microsoft Visual Basic 2010, 5th Edition 55 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 Programming with Microsoft Visual Basic 2010, 5th Edition 56 Coding the Form’s Load Event Procedure 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 Programming with Microsoft Visual Basic 2010, 5th Edition 57 Lesson B Summary Radio button 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 Programming with Microsoft Visual Basic 2010, 5th Edition 58 Lesson B Summary (cont’d.) Call statement ◦ Used to call (invoke) independent Sub procedure Use object.PerformClick() to invoke object’s Click event Programming with Microsoft Visual Basic 2010, 5th Edition 59 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 Programming with Microsoft Visual Basic 2010, 5th Edition 60 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 Programming with Microsoft Visual Basic 2010, 5th Edition 61 Figure 5-44 Pseudocode for the btnCheckAnswer control’s Click event procedure Programming with Microsoft Visual Basic 2010, 5th Edition 62 Figure 5-45 Memory locations used by the btnCheckAnswer control’s Click event procedure Programming with Microsoft Visual Basic 2010, 5th Edition 63 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 Programming with Microsoft Visual Basic 2010, 5th Edition 64 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 Programming with Microsoft Visual Basic 2010, 5th Edition 65