Week 5 More on the Selection Structure 1

advertisement

Week 5

More on the Selection Structure

1

Nested, If/ElseIf/Else, and Case Selection Structures

Lesson A Objectives

After completing this lesson, you will 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

2

Nested, If/ElseIf/Else, and Case Selection Structures

Lesson A Objectives

 Code an If/ElseIf/Else selection structure

 Include a Case selection structure in pseudocode and in a flowchart

 Code a Case selection structure

 Write code that uses the Is, TypeOf…Is, and Like comparison operators

3

Nested Selection Structures

When either a selection structure’s true path or its false path contains another selection structure, the inner selection structure is referred to as a nested selection structure , because it is contained

(nested) within the outer selection structure

Message

You are too young to vote

You can vote

You need to register before you can vote

Criteria

Person is younger than 18

Person is at least 18 years old

AND

Is registered to vote

Person is at least 18 years old

AND

Is not registered to vote

4

Pseudocode and Example of Nested Selection Structure

If your age < 18

Message is “You are too young to vote”

Else

If you are registered

Message is “You can vote

Else

Message is “You need to register before you can vote”

End If

End If

If intAge < 18 Then strMessage = “You are too young to vote”

Else

If blnRegistered Then strMessage = “You can vote

Else strMessage = “You need to register before you can vote”

End If

End If

5

Logic Errors in Selection Structures

 Logic errors commonly made when writing selection structures are a result of one of the following mistakes:

1.

Using a logical operator when a nested selection structure is needed

2.

Reversing the primary and secondary decisions

3.

Using an unnecessary nested selection structure

 An algorithm is simply the set of step-by-step instructions that accomplish a task

 Desk-checking , also called hand-tracing , means that you use sample data to walk through each of the steps in the algorithm manually, just as if you were the computer

6

An Algorithm

Algorithm for determining amount of vacation

1. Declare variables

2. Get employment status and years

3. If the employment status is full-time

If the years is greater than 5 display “3-weeks” else display “2-weeks” end if end if

7

Using a Logical Operator Rather Than a Nested Selection Structure

Incorrect algorithm

1. Declare variables

2. Get employment status and years

3. If the status is full-time AndAlso the years is greater than 5 display “3-weeks” else display “2-weeks” end if

8

Reversing the Primary and Secondary

Decision

Incorrect algorithm

1. Declare variables

2. Get employment status and years

3. If the years is greater than 5

If the status is full-time display “3-weeks” else display “2-weeks” end if end if

9

Using an Unnecessary Nested

Selection Structure

Inefficient algorithm

1.

Declare variables

2.

Get employment status and years

3. If the status is full-time

If the years is greater than 5 display “3-weeks” else if the years are less than or equal to 5 display “2-weeks” end if end if endif

10

The If/ElseIf/Else Selection Structure

Determination of grade

Dim strGrade As String strGrade = UCase(InputBox("Grade?", "Grade"))

If strgrade = "A" Then

Me.MsgLabel.Text = "Excelent"

ElseIf strgrade = "B" Then

Me.MsgLabel.Text = "Above Average"

ElseIf strGrade = "C" Then

Me.MsgLabel.Text = "Average"

ElseIf strGrade = "D" OrElse strGrade = "F" Then

Me.MsgLabel.Text = "Below Average"

Else

Me.MsgLabel.Text = "Error"

End If

11

The Case Selection Structure

Select Case selectorExpression

[Case expressionList1

[instructions for the first Case]]

[Case expressionList2

[instructions for the second Case]]

[Case expressionListn

[instructions for the nth Case]]

[Case Else

[instructions for when the

selectorExpression does not match any of the expressionLists]]

End Select

12

The Case Selection Structure

Determination of grade

Dim strGrade As String = InputBox("Grade?", "Grade").ToUpper

Select Case strGrade

Case "A"

Me.MsgLabel.Text = "Excelent"

Case "B"

Me.MsgLabel.Text = "Above Average"

Case "C"

Me.MsgLabel.Text = "Average"

Case "D", "F"

Me.MsgLabel.Text = "Below Average"

Case Else

Me.MsgLabel.Text = "Error"

End Select

13

To and Is Keywords

 To keyword: specifies a range of minimum and maximum values

Case 1 To 5

 Is keyword: specifies a range of values when you know only one value, either the minimum or the maximum

Case Is > 10

14

The Is, TypeOf…Is, and Like

Comparison Operators

 The Is operator determines whether two object references refer to the same object

 An object reference is a memory address within the computer’s internal memory; it indicates where in memory the object is stored

 The TypeOf…Is operator determines whether an object is a specified type

 The Like operator uses pattern matching to determine whether one string is equal to another string

15

The Is Operator

Is operator

Syntax: objectReference1 Is objectReference2

Private Sub CalcComm(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Handles Calc2Button.Click, Calc4Button.Click, Calc7Button.Click

Dim sngSales, sngComm As Single sngSales = Val(Me.SalesTextBox.Text)

If sender Is Me.Calc2Button Then sngComm = sngSales * 0.02

Handles

ElseIf sender Is Me.Calc4Button Then sngComm = sngSales * 0.04

ElseIf sender Is Me.Calc7Button Then sngComm = sngSales * 0.07

End If

End Sub

Compares memory addresses

16

The TypeOf…Is Operator

TypeOf … Is operator

Syntax: TypeOf objectReference1 Is objectType

Private Sub DisplayMessage(ByVal sender As System.Object, _

ByVal e As System.EventArgs) _

Compares

Handles SalesTextbox.TextChanged, ClearButton.Click

object to

Select Case True object type

Case TypeOf sender Is TextBox

Me.MsgLabel.Text = “The text box invoked procedure”

Case Else

Me.MsgLabel.Text = “The button invoked procedure”

End Select

End Sub

17

The Like Comparison Operator

Like comparison operator

Syntax: string Like pattern

Pattern Matches

?

Any single character

*

#

Zero or more characters

Any single digit

[charlist] Any character in charlist

[!charlist] Any character not in charlist

18

The Math Practice Application

Lesson B Objectives

After completing this lesson, you will 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 a user-defined Sub procedure

19

The Math Practice Application

Lesson B Objectives

 Generate random numbers using the Random object and the Random.Next method

 Call a user-defined Sub procedure

 Invoke a radio button control’s Click event procedure from code

 Process code when a form is first loaded into the computer’s memory

20

Completing the User Interface

 The application should display the addition or subtraction problem on the screen, then allow the student to enter the answer and then verify that the answer is correct

 If the student’s answer is not correct, the application should give him or her as many chances as necessary to answer the problem correctly

21

Adding a Radio Button to the Form

 RadioButton Control:

 Used to limit the user to only one choice in a group of options

 Should have a unique access key, which allows the user to select the button using the keyboard

 The selected button is called the default radio button and is either the radio button that represents the user’s most likely choice or the first radio button in the group

 You designate a radio button as the default radio button by setting the button’s Checked property to the Boolean value True

22

Adding a CheckBox

Control to the Form

 Checkbox Controls:

 Used to add a check box control to the interface

 Work like radio buttons in that they are either selected or deselected only; but that is where the similarity ends

 You use check box controls to allow the user to select any number of choices from a group of one or more independent and nonexclusive choices

 Any number of check boxes on a form can be selected at the same time

23

User-Defined Procedures

 A user-defined Sub procedure is a collection of code that can be invoked from one or more places in an application

 Enter Private Sub SubName() just above the End

Class statement

 The rules for naming a user-defined Sub procedure are the same as those for naming variables and constants

 The End Sub will automatically be generated

24

Generating Random Numbers

 Visual Studio provides a pseudo-random number generator, which is a device that produces a sequence of numbers that meet certain statistical requirements for randomness

 Dim GeneratorRandom As New Random()

 Methods

 Next(minValue, maxValue)

 NextDouble()

25

Coding the Grade1RadioButton and Grade2RadioButton

Click Event Procedures

You can use the Visual Basic Call statement , whose syntax is Call

procedurename([argumentlist]), to call

(invoke) a user-defined Sub procedure

 The square brackets in the syntax indicate that the argumentlist is optional

26

Coding the AdditionRadioButton and SubtractionRadioButton

Click Event Procedures

 When the user clicks either the

AdditionRadioButton control or the

SubtractionRadioButton control, the control’s

Click event procedure should display the appropriate mathematical operator (either a plus sign or a minus sign) in the OperatorPictureBox control and then generate and display two random numbers in the Num1Label and

Num2Label controls

27

Coding the Form’s

Load Event Procedure

 Instructions entered in the form’s Load event procedure are processed when the application is started and the form is loaded into memory

 The latter statement uses the

RandomButton.PerformClick method , whose syntax is radiobutton.

PerformClick (), to invoke the Addition radio button’s Click event, which causes the code in the Click event procedure to be processed by the computer

28

Completing the Math

Practice Application

Lesson C Objectives

After completing this lesson, you will be able to:

 Select the existing text in a text box control

 Code a check box control’s Click event procedure

 Display and hide a control

29

Coding the CheckAnswerButton

Click Event Procedure

 You still need to code the Click event procedures for the CheckAnswerButton and the DisplaySummaryCheckBox controls

 The pseudocode for the CheckAnswerButton control’s Click event procedure is shown in

Figure 5-49 in the textbook

30

31

Coding the SummaryCheckBox

Click Event Procedure

 The SummaryCheckBox control’s Click event procedure is responsible for both displaying and hiding the SummaryGroupBox control

 The procedure should display the group box control when the user selects the check box, and it should hide the group box control when the user deselects the check box

32

Download