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