decision structures - · pdf file14/10/2012 · decision structures ... the decision...

19
Decision Structures In the programs created thus far, Visual Basic reads and processes each of the procedure instructions in turn, one after the other. This is known as sequential processing or as the sequence structure. There are however two other programming structures known as decision structures and repetition structures. Many applications use decision (or selection) structures to control which program instructions are processed. Decision structures enable a program to make decisions, or comparisons, and then select one of two program paths based on the result. This structure can be thought of as a fork in a road and can be represented visually using a flowchart. In a typical day, you probably make hundreds of decisions. For example if you have a test tomorrow morning, then you should study tonight, if not, you can watch the late night showing of Greys Anatomy on TV. This could be represented using a flowchart. In the above flowchart, the diamond shape represents the decision structure. Inside the diamond is a question or condition with a yes/no answer. The decision structure has one flow-line leading into it, and two flow-lines leading out of it. The out-flowing lines are marked with “Y” & “N” (for Yes/No) or “T” & “F” (for True/False) to clearly indicate the ‘true’ path from the ‘false’ path. Flowcharts can be used to show the steps that must be completed in order to accomplish a task. To translate a flowchart into VB code, simply start at the top and write the code for each symbol as you follow the flow-lines down the flowchart. Some symbols may require several lines of code, while the start symbol requires no coding. Y N Do I have a test in morning? Start Stop Study for test Watch TV tonight

Upload: volien

Post on 15-Mar-2018

220 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Decision Structures

In the programs created thus far, Visual Basic reads and processes each of the procedure instructions in turn,

one after the other. This is known as sequential processing or as the sequence structure. There are however

two other programming structures known as decision structures and repetition structures.

Many applications use decision (or selection) structures to control which program instructions are processed.

Decision structures enable a program to make decisions, or comparisons, and then select one of two program

paths based on the result. This structure can be thought of as a fork in a road and can be represented visually

using a flowchart.

In a typical day, you probably make hundreds of decisions. For example if you have a test tomorrow morning,

then you should study tonight, if not, you can watch the late night showing of Greys Anatomy on TV. This could

be represented using a flowchart.

In the above flowchart, the diamond shape represents the decision structure. Inside the diamond is a question

or condition with a yes/no answer. The decision structure has one flow-line leading into it, and two flow-lines

leading out of it. The out-flowing lines are marked with “Y” & “N” (for Yes/No) or “T” & “F” (for True/False) to

clearly indicate the ‘true’ path from the ‘false’ path. Flowcharts can be used to show the steps that must be

completed in order to accomplish a task. To translate a flowchart into VB code, simply start at the top and write

the code for each symbol as you follow the flow-lines down the flowchart. Some symbols may require several

lines of code, while the start symbol requires no coding.

Y

N

Do I have

a test in

morning?

Start

Stop

Study for test

Watch TV tonight

Page 2: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

The IF…Then Statement

The If…Then statement executes a set of statements when a condition is true.

For example in the following If…Then statement intCredits >= 20 is the condition and there is one statement

that will be executed when the condition is true.

Care must be taken when writing the condition of an If…Then statement as it must be written as a Boolean

expression that evaluates to true or false. In the above condition, the relational operator >= is used to

determine the value of the variable intCredits. If the value is greater than or equal to 20, then the Text property

of lblMessage will be changed to display the message “congratulations, you can graduate this year!”. If the

value is less than 2, the statement is not executed as the condition is not true. Program flow continues to the

code directly after the End If

Relational Operators

Operator Meaning

= equal to

< less than

> greater than

>= greater than OR equal to

<= less than OR equal to

<> not equal to

Syntax: If condition Then

statements executed when condition is true

End If

If intCredits >= 20 Then

lblMessage.Text= “Congratulations, you can graduate this year!”

End If

Page 3: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Lab# 6 – Decisions

You will create a grading application that enables the user to

enter a test mark. If the mark entered is greater than 90, the

message “Good job A+” should be displayed.

Open a new Project and create the form at the right. Name

the project Grading.

Make the following changes to the controls:

Form1

Name - frmGrading

Text – Grading

Form1.vb renamed MainForm

Label 1

Name - lblEnterPrompt

Text – Enter a Numeric Grade

Label 2

Name - lblMessage

Text – Grade Information

TextBox

Name - txtNumericGrade

Button

Name - cmdProcess

Text – Process

MenuStrip

File

Name -mnuFile

Process

Name –mnuFileProcess

Clear

Name –mnuFileClear

Exit

Name –mnuFileExit

Help

Name –mnuHelp

About

Name -mnuHelpAbout

Page 4: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

In this program, we are going to code for five events, all clicks of the mouse on the menu objects or the command button. When the Exit menu is clicked, the program will close. We have seen this code in the last lab. When the Clear menu is clicked, the value in the textbox and the value in the Message label will be cleared (Message caption will change to reflect the “Grade Information” message). When the Process button is clicked or when the Process menu is clicked, the program will determine if the entered value is greater than 90. If it is, the message label will change.

Planning: For this program we will need the following: No formulas needed

Variables:

grade – needs to be a number, decimals should be allowed The scope of these variables needs only to be used within the form class, thus, they should be declared after Public Class and before any of the subroutines using Private.

Page 5: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

The flowchart for the Process procedure looks like this:

Y

N

Is value

>= 90?

Start

Stop

Convert value to a

number

Get numeric

grade from

user

Display

message

“Good

Work A+”

Page 6: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Pseudo-code: Declare Variable – Grade (Use Option Explicit On and Option Infer Off) mnuFileExit _Click Exit program End Sub mnuFileClear_Click clear contents of textbox (set to empty strings) reset label for message to “Grade Information” End Sub cmdProcess_Click AND mnuFileProcess_Click get user input from text box and put them into variable using Val to convert to Numeric data If variable > 90 then display the message “Good Job A+” in the label End If End Sub mnuHelpAbout_Click Display MessageBox with program details. End Sub Code: 'Grading Application

'purpose: to introduce Decision Structures to students.

'Program will request a grade from the user and if the

'value is greater than 90, a message will display "Good job A+"

'of a sqaure that has that length measurement.

'Written by Computer Teacher, One day

'Modified by you, today

Option Explicit On

Option Infer Off

Page 7: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Public Class frmGrading

'Declare variables

Private sngGrade As Single

Private Sub cmdProcess_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdProcess.Click

sngGrade = Val(txtNumericGrade.Text 'converts textbox value to number

If sngGrade > 90 Then 'decision structure

lblMessage.Text = "Good Job A+"

End If

End Sub

'repeat of code from Command Button

Private Sub mnuFileProcess_Click(ByVal sender As Object, ByVal e As

System.EventArgs) Handles mnuFileProcess.Click

sngGrade = Val(txtNumericGrade.Text) ’converts textbox value to number

If sngGrade > 90 Then 'decision structure

lblMessage.Text = "Good Job A+"

End If

End Sub

'Exit program

Private Sub mnuFileExit_Click(ByVal sender As Object, ByVal e As

System.EventArgs) Handles mnuFileExit.Click

Me.Close()

End Sub

'Displays information about the program

Private Sub mnuHelpAbout_Click(ByVal sender As Object, ByVal e As

System.EventArgs) Handles mnuHelpAbout.Click

MessageBox.Show("Letter Grading messenger", "Grading 2.0")

End Sub

'clear text box and reset message

Private Sub mnuFileClear_Click(ByVal sender As Object, ByVal e As

System.EventArgs) Handles mnuFileClear.Click

lblMessage.Text = "Grade Information"

txtNumericGrade.Text = " " 'empty string

End Sub

End Class

Save All and test your program. If you enter a grade of 90 or below, no action is taken as there is no allowance for that in the code.

Page 8: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

The IF…Then…Else Statement

The If…Then…Else statement executes one set of statements when a condition is true and another set of

statements if the condition is not true.

Only ONE of the above statements can be executed, depending on if the condition evaluates as true or false.

In the following example, if the condition radAdd.checked=True evaluates as true (meaning the radio button

radADD is checked), then program flow continues to the statements immediately below the condition. The

variable sngSum is therefore calculated by adding the contents of the two textboxes Mark1 and Mark2. The text

property of the label control lblAnswer would then be updated as shown. Program flow would then skip ahead

to the end of the statement.

If the condition evaluates as false (meaning the radio button radAdd is NOT checked) then program flow skips

the statements immediately following the condition, and instead jumps ahead and executes the statements

following the Else statement. In this case the variable sngSum would be assigned the value zero. Program flow

then continues.

Syntax: The If…Then…Else statement takes the form:

If condition Then

statements executed when condition IS true

Else

statements executed when condition IS NOT true

End If

If radAdd.checked = True Then

sngSum = Val(txtMark1.text) + Val(txtMark2.text)

lblAnswer.text = ”The sum of the marks is “ & sngSum

Else

sngSum = 0

End If

Page 9: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Lab# 6 continued

We will modify the previous grade application so that in addition to displaying “Good job A+” for marks

greater than 90, the message “Good work, keep practicing!” is displayed for marks of 90 or less.

Our form will not need to change, nor will our variable. The flowchart would need to be changed to reflect

another message after the decision:

The pseudocode changes are only to the Process procedures:

cmdProcess_Click AND mnuFileProcess_Click get user input from text box and put them into variable using Val to convert to Numeric data If variable > 90 then display the message “Good Job A+” in the label Else Display the message “Not bad…keep going” End If End Sub

Y

N

Is value

>= 90?

Stop

Display

message

“Good

Work A+”

Display

message

“Not bad …

keep

going”

Page 10: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Code (note that there are only two lines added to each procedure):

Private Sub cmdProcess_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdProcess.Click

sngGrade = Val(txtNumericGrade.Text) 'converts text box value to

numeric value

If sngGrade > 90 Then 'decision structure

lblMessage.Text = "Good Job A+"

Else

lblMessage.Text = "Not bad...keep going"

End If

End Sub

'repeat of code from Command Button

Private Sub mnuFileProcess_Click(ByVal sender As Object, ByVal e As

System.EventArgs) Handles mnuFileProcess.Click

sngGrade = Val(txtNumericGrade.Text) 'converts text box value to

numeric value

If sngGrade > 90 Then 'decision structure

lblMessage.Text = "Good Job A+"

Else

lblMessage.Text = "Not bad...keep going"

End If

End Sub

Page 11: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Logical Operators

Logical operators (AND, OR, NOT) can also be used to combine several conditions into one compound condition.

The chart below shows the three most commonly used operators and their meaning.

Truth Table for AND operator

Value of Condition 1 Value of Condition 2 Value of Compound condition (condition 1 AND condition 2)

True True True

True False False

False True False

False False False

Truth Table for OR operator

Value of Condition 1 Value of Condition 2 Value of Compound condition (condition 1 OR condition 2)

True True True

True False True

False True True

False False False

Truth Table for NOT operator

Value of Condition Value of NOT Condition

True False

False True

Logical Operator Meaning

AND ALL conditions connected by the AND operator must be true for the compound operator to evaluate as true.

OR

Only ONE of the conditions connected by the OR operator needs to be true for the compound operator to evaluate as true.

NOT

REVERSES the value of the condition. True becomes false, false becomes true.

Page 12: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Truth Tables explained The truth tables show the possible combinations in which the separate conditions that make up a compound

condition can evaluated using logical operators, along with their combined result.

AND operator

Notice that when the AND logical operator is used to combine the two conditions, condition 1 and condition 2,

then the resulting compound condition is True ONLY when BOTH conditions are True. If either condition is False,

or if both are False, then the compound condition evaluates as False.

When Visual Basic evaluates a compound condition that uses an AND operator, if the first condition is False,

then the second condition is not even evaluated. Also, if either one of the conditions is False, the resulting

compound condition must also be False.

OR operator

When the OR logical operator is used to combine the two conditions, condition 1 and condition 2, then the

resulting compound condition is False only when BOTH conditions are False. If either condition is True, or if

both are TRUE, then the compound condition evaluates as TRUE.

NOT operator

Reverses the Truth condition of the operator. Use of the NOT operator is best avoided if possible as it can be

confusing!

Just like expressions that contain relational operators, expressions containing logical operators always result in

either a True or False answer. In the case of compound expressions, any mathematical operators are evaluated

first, relational operators are operated next, and logical operators are evaluated last.

Exercise

For example in the following compound expression 8 > 4 AND 10 < 2 * 6 uses the AND logical operator

and evaluates as True.

2*6 is evaluated first resulting In 8 > 4 AND 10 < 12

8 > 4 is evaluated next resulting In True AND 10 <12

10 < 12 is evaluated next resulting In True AND True

True AND True is evaluated last resulting In True

Calculate and determine if the following compound expressions evaluate as True or false.

1. 12 > 0 AND 12 < 10 * 2

2. 12 / 3 > 4 AND 12 < 7 * 2

3. 4^2 > 10 AND 2 * 3 + 2 < 9

4. 12 < 2 * 7 OR 12 > 10 * 2

5. 3 + 7 * 2 > 3* 7 + 2 OR 12 / 6 – 2 > 10 * SQR(9) – 6 * 7 -2

Page 13: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Nested If…Then…Else Statements

If…Then…Else statements can each contain another If…Then…Else statement, and is then said to be nested.

It is good programming style to indent nested If…Then…Else statements as shown. The last Else statement is

optional.

In the following example, if the radio button radCube is checked then the variable sngVolume is calculated using

the formula for the volume of a cube and is then displayed. Else if the radio button radSphere is checked

instead, then the value of sngVolume is calculated using the formula for the volume of a sphere.

Syntax: Nested If…Then…Else statements take the form:

If condition 1 Then

statements executed when condition1 is true

Else

If condition 2 Then

statements executed when condition2 is true

Else

If condition 3 Then

statements executed when condition 3 is true

Else

statements

End If

End If

End If

If radCube.checked=True Then

sngVolume = length * width * height

lblMessage.text = ”Volume of cube is “ & sngVolume

Else

If radSphere.checked=True Then

sngVolume = 4/3 * 3.14 * radius^3

lblMessage.text = ”Volume of cube is “ & sngVolume

Else

sngVolume =0

lblMessage.visible=False

End If

End If

Page 14: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

The IF…Then…ElseIf Statement

The If…Then…ElseIf statement is generally used to decide among 3 or more actions.

There can be multiple ElseIf statements as shown above. The last Else statement is optional.

Decision structures with several branches can be difficult to understand so should include inline comments to

help explain the logic. This is especially true of the last branch of a decision structure which does not always

include an explicit instruction!

A single If…Then…Else If statement is generally easier to understand and considered better programming style

than nested If…Then…Else statements.

Syntax: The If…Then…Else If statement takes the form:

If condition 1 Then

statements executed when condition 1 is true

ElseIf condition 2 Then

statements executed when condition 2 is true

ElseIf condition3 Then

statements executed when condition 3 is true

Else

statement

End If

Page 15: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Lab# 6 Continued

Modify the grades lab to reflect the following:

If mark 80 and above, display “Excellent, grade A”

If mark 70 and above, but less than80, display “Well done, grade B”

If mark 60 and above, but less than 70, display “Pass, grade C”

If mark < 60, display “Try studying more”

Our form will not need to change, nor will our variable. The flowchart would need to be changed to reflect

another message after the decision:

Y

N

Is value

>=80? Display

message

“Excellent,

Grade A”

Display

message

“Try

studying

more”

Is value

>=70 &

<80?

N

Y

Display

message

“Well done,

Grade B”

Y Is value

>=60 &

<70?

N

Display

message

“Pass, Grade

C”

Stop

Page 16: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Code

Private Sub cmdProcess_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles cmdProcess.Click

sngGrade = Val(txtNumericGrade.Text) 'converts text box value to

numeric value

If sngGrade >= 80 Then 'decision structure

lblMessage.Text = "Excellent, Grade A"

ElseIf sngGrade >= 70 And sngGrade < 80 Then

lblMessage.Text = "Well done, Grade B"

ElseIf sngGrade >= 60 And sngGrade < 70 Then

lblMessage.Text = "Pass, Grade C"

Else

lblMessage.Text = "Try studying more"

End If

End Sub

Don’t forget to place the same code in the mnuFile Process_Click procedure.

Save all and test your program with several different data to ensure that it functions properly.

The Select…Case Statement

The Select…Case statement is a decision structure that is useful used as an alternative to nested If…Then…Else

statements as the code is generally easier to read. The select…case structure uses the result of a condition to

determine which statements to execute.

Syntax: The Select…Case statement takes the form.

Select Case expression

Case value 1

statement executed if value 1 true

Case value 2

statement executed if value 2 true

Case Else

statement executed if value 1 AND value 2 NOT true

End Select

Page 17: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

The Select…Case Is Statement

The Select…Case Is statement compares the result of an expression to a range of values when a relational

operator is part of the value.

For example the Select…Case Is statement below uses a relational operator to compare the value of the

variable intSpeed to the values shown. The lblMessage.text will therefore be changed depending on the

windspeed represented by the variable intSpeed.

For example the Select Case statement below assigns a value to the variable curCost, depending on the

value of the variable intGroupsize. If intGroupsize=1 then curCost=50. If intGroupsize=2 then

curCost=75.

Select Case intGroupSize

Case 1

curCost=50

Case 2

curCost=75

Case 3

curCost=100

End Select

Select Case intSpeed

Case Is < 74

lblMessage.Text = "Not Hurricaine strength"

Case Is < 95

lblMessage.Text = "Category 1 Hurricaine"

Case Is < 110

lblMessage.Text = "Category 2 Hurricaine"

Case Is < 130

lblMessage.Text = "Category 3 Hurricaine"

End Select

Page 18: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Random Numbers Random Numbers are required by many types of applications, such as games, simulators, and screen savers. The RND ( ) function generates a random number greater or equal to 0 and less than 1. Remember a function is a procedure that performs a task and returns a value.

Larger Range To generate random numbers in a greater range, multiply Rnd by the upper limit of the range. Changing the lower limit If you would like to use a lower limit other than zero, use the following syntax:

High_Number - the maximum value desired. Low_Number - the minimum value desired.

INT The INT() function returns an integer portion of a number (without rounding). Combining INT and RND will produce random integers.

IE. lblRandom.Text = Rnd( ) * 10

IE. lblRandom.Text = Rnd( )

(High_Number - Low_Number +1) * Rnd() + Low_Number

Example lblRandom.Text = 16 * Rnd ( )+ 20 Would give a range of 20 to 45. To figure this out use the formula of high_number – low_number +1 = number before Rnd or (X - 20 + 1) = 16

IE. lblRandom.Text = Int ( 16 * Rnd( ) + 20)

Page 19: Decision Structures - · PDF file14/10/2012 · Decision Structures ... The decision structure has one flow-line leading into it, and two flow-lines ... Truth Table for AND operator

Randomize Programs using random numbers need the Randomize ( ) statement in order for different numbers to be generated each run of the program. The Randomize statement should only be executed once in a program and be placed before any call of the Rnd () function, thus placing it in the form_load procedure is the best place for it.

IE. Private Sub Form _ Load ( ) Randomize () ‘ initializes random number generator

End Sub