Download - Selection / Decisions
CIS 115 Lecture 7
There are 3 control structures common to most computer languages that determine the flow, or path of execution, of the code:
Sequential
Selection / Decisions
Repetition / Looping
Visual Basic decision statements If…Then▪ one-way selection structure
If…Then…Else▪ two-way selection structure
If…Then…ElseIf▪ multi-way selection structure
If…Then…ElseIf…Else▪ multi-way selection structure
Select Case▪ multi-way selection structure
If…Then decision structureprovides one choice
Evaluate the condition: True or FalseEx: Is it cold outside?
True – execute codeEx: If yes, wear a coat
False – do not execute code Ex: If no,
Condition
ConditionalCode
True
False
If condition Thenstatement[s]
End If
Syntax explanation: If , Then, and End – Keywords Condition – True/False value, variable,
function call or expression Statement[s] – one or more code
statements to be executed if condition is true
The execution of an If block is controlled by a condition
Must be (or evaluate to) either true or false
Can be a value, variable, or function call (Boolean DataType)
Can be formed by using the six Relational operators and the three Logical operators
A flag is a Boolean variable that signals when some condition exists in the program
Since a Boolean variable is either True or False, it can be used as the condition of an If Note that an operator is not required
(there is alternate syntax that does use operator)
If blnQuotaMet Then lblMessage.Text = “Congratulations you have met your sales quota"
End If
Boolean Functions return a single True or False Value
Since Boolean Functions return either True or False, a Boolean Function Call can be used as the condition of an If Note that an operator is not required
(there is alternate syntax that does use operator)If isNumeric(strInput) Then
intNumber = Val(strInput)End If
Often a condition is formed using a relational operator
A relational operator determines if a specific relationship exists between two values > Greater than < Less than = Equal to <> Not equal to >= Greater than or equal to <= Less than or equal to
Relational operators are binary – meaning they use two operands Either or both relational operator operands may
be values, variables, expressions or function calls
length <= 10 (Is length less than or equal to 10)
len * wid > max + 1 (Is len * wid greater than max + 1)
Val(txtNum.Text) = 0 (Is Val result equal to 0 – not assignment)
Relational operators yield a True or False result
Either or both relational operator operands may be expressions Math operators are evaluated before relational
operators
x+y and a-b are evaluated first Each result is then compared using the > operator
Either or both relational operator operands may be function calls
If x + y > a - b ThenlblMessage.Text = "It is true!"
End If
If Val(txtInput.Text) < getMinValue() ThenlblMessage.Text = "Invalid: Below Minimum"
End If
These operators are used to evaluate boolean values and will yield a boolean result
And Both operands must be true for the overall expression to be
true, otherwise it is false
Or One or both operands must be true for the overall
expression to be true, otherwise it is false
Xor One operand (but not both) must be true for the overall
expression to be true, otherwise it is false
Not Reverses the logical value of an expression
The truth table for the And Operator
Expression 1 Expression 2 Expression 1 And Expression 2
True FalseFalseFalse True
FalseFalse False
FalseTrue True True
If temperature < 20 And minutes > 12 ThenlblMessage.Text = “Temperature is in the danger zone."
End If
AndAlso operator works identically but does not test minutes>12 if temperature<20 is false
If temperature < 20 Or temperature > 100 ThenlblMessage.Text = “Temperature is in the danger zone."
End If
OrElse operator works identically but does not test temperature>100 if temperature<20 is true
The truth table for the Or Operator
Expression 1 Expression 2 Expression 1 Or Expression 2
True False TrueFalse True
TrueTrue True TrueFalse False
False
If total > 1000 Xor average > 120 ThenlblMessage.Text = “You may try again."
End If
The truth table for the Xor Operator
Expression 1 Expression 2 Expression 1 Xor Expression 2
True False TrueFalse True
TrueTrue TrueFalseFalse False
False
If Not temperature > 100 ThenlblMessage.Text = "You are below the max temp."
End If
The truth table for the Not Operator
Expression 1 Not Expression 1
True FalseFalse True
Checking for a value inside a range uses And
Checking for a value outside a range uses Or
Must pay careful attention to differences in resulting range using: < vs <= or > vs >= Check problem requirements for ranges carefully
If x >= 20 And x <= 40 ThenlblMessage.Text = “Value is in the acceptable range."
End If
If x < 20 Or x > 40 ThenlblMessage.Text = “Value is outside the acceptable range."
End If
Logical operators have an order of precedence just as arithmetic operators do
From highest to lowest precedence Not And Or Xor
As with arithmetic operations, parentheses are often used to clarify order of operations
For example, in the statement If x < 0 And y > 100 Or z = 50 x < 0 And y > 100 is evaluated first If the And condition is true, we then evaluate True Or z = 50 If the And condition is false, we then
evaluate False Or z = 50
If the Or condition is to be evaluated first parentheses must be used If x < 0 And (y > 100 Or z = 50)
ParenthesisArithmetic
Exponential Multiplication / Division Integer Division MOD Addition / Subtraction
String ConcatenationRelational Operators (< , > , >= , <= ,
<>)Logical Operators
Not And Or, Xor)
Evaluate the following if a=5, b=7, x=100, y=30 If x > a * 10 And y < b + 20 Evaluating the math operators leaves us with If x > 50 And y < 27 Evaluating the relational operators leaves If True And False Evaluating the logical operators leaves False
Parentheses make order of operations clear If (x > (a * 10)) And (y < (b + 20))
If (intSales > 50000) ThenblnGetsBonus = True
End If-----------------------------------------------------------------If ((blnGetsBonus)Or((intMissedDays < 2)And(intSales > 30000)))
intDaysOff = intDaysOff + 1intEmpRating += 1
End If-----------------------------------------------------------------If (Not(isNumeric(txtInput.text))) Then
txtInput.text = “”MsgBox(“Please enter a number in the textbox”)
End If-----------------------------------------------------------------If (intGrade >= 80)And(intGrade < 90) Then lblMessage.text = “B” -----------------------------------------------------------------If ((Val(txtGrade.text) < 0)Or(Val(txtGrade.text) > 100)) Then
lblMessage.text = “Invalid Grade: Not in the range 0-100”End If
The If…Then construct will execute or ignore a group of statements (do something or do nothing)
The If…Then…Else construct will execute one group of statements or another group (do this or do that)
Condition
Statement(s)If True
True
False
Statement(s)If True
TrueFalse
Statement(s)If False
Condition
If…Then…Else provides two choices
Evaluate condition:True or False
True – execute codein If…Then block
False – execute codein Else Block
One of the two choices must be selectedThey are mutually exclusive
Condition
Statement(s)If True
TrueFalse
Statement(s)If False
If condition Thenstatement[s]1
Elsestatement[s]2
End If
Syntax explanation: If , Then, Else, and End – Keywords Condition – True/False value, variable, function call
or expression Statement[s]1 – executed if condition is True Statement[s]2 – executed if condition is False
If (intSales > 50000) ThenblnGetsDoubleBonus = TruedecBonus = 4000.00
ElsedecBonus = 2000.00
End If-----------------------------------------------------------------If (Not(isNumeric(txtInput.text))) Then
MsgBox(“You did not enter a valid number – program will end”)End
ElseintNumber = Val(txtInput.text)
End If-----------------------------------------------------------------If (intTemp >= 60)And(intTemp < 90)And(VisibRating() > 5) Then
lblMessage.text = “Go - Weather conditions are ideal” Else
lblMessage.text = “Wait - Weather conditions unacceptable”End If
If…Then…ElseIfallows for multiplemutually exclusivechoices
Each of the conditionsis tested in sequence
When a condition istrue, the correspondingcode is executed and theremaining conditions are ignored
C1
C2
C3
Statement(s)1
True
Statement(s)2
True
Statement(s)3
True
False
False
False
If it is very cold ThenWear a coat
Elseif it is chillyWear a light jacket
Elseif it is windyWear a windbreaker
Elseif it is hotWear no jacket
The order of the conditions is vital Wrong order can result in wrong decision What if it’s chilly and windy? If windy is tested before chilly, you’d go out
with a windbreaker when you need a jacket
If condition1 Thenstatement[s]1
ElseIf condition2
statement[s]2
• • •ElseIf conditionn
statement[s]n
End If
Syntax explanation: If , Then, ElseIf, and End –
Keywords Condition1 thru n – True/False
value, variable, functioncall or expression
Statement[s]1 – executed ifcondition1 is True
Statement[s]2 – executed if condition1 is False and if condition2 is True
Statement[s]n – executed if condition1 thru (n-1) is False and if conditionn is True
If sngAvg < 59.5 ThenlblGrade.Text = "F"
ElseIf sngAvg < 69.5 ThenlblGrade.Text = "D"
ElseIf sngAvg < 79.5 ThenlblGrade.Text = "C"
ElseIf sngAvg < 89.5 ThenlblGrade.Text = "B"
ElseIf sngAvg <= 100 ThenlblGrade.Text = "A"
End If
In each example, does the order of the conditions matter?
What happens if the order is reversed in each example?
If radCredCrd.checked ThenCredCrdPayment(decSubTot)
ElseIf radDebCrd.checked ThenDebCrdPayment(decSubTot)
ElseIf radCheck.checked ThenCheckPayment(decSubTot)
End If
If…Then…ElseIf…Else is simply anIf…Then…ElseIfwith an Else at the end
Called a Trailing Else If the initial If and none
of the ElseIf conditionsare True, the trailingElse statement(s) willbe executed
C1
C2
C3
Statement(s)1
True
Statement(s)2
True
Statement(s)3
True
False
False
False
Statement(s)Else
If condition1 Thenstatement[s]1
• • •ElseIf conditionn
statement[s]n
Else
statement[s]Else
End If
Syntax explanation: Same as If..Then…
ElseIfthru statement[s] n
Statement[s]Else – executed if condition1
thru n
(all previous conditions) are False
If sngAvg < 59.5 ThenlblGrade.Text = "F"
ElseIf sngAvg < 69.5 ThenlblGrade.Text = "D"
ElseIf sngAvg < 79.5 ThenlblGrade.Text = "C"
ElseIf sngAvg < 89.5 ThenlblGrade.Text = "B"
ElseIf sngAvg <= 100 ThenlblGrade.Text = "A“
ElselblGrade.Text = "Invalid"
End If
If intCredScr >= 700 ThenstrLoanType = “Prime”intLoanRate = 1
ElseIf intCredScr >= 600 ThenstrLoanType = “Standard”intLoanRate = 2
ElseIf intCredScr >= 500 ThenstrLoanType = “Risk”intLoanRate = 3
ElseIf intCredScr >= 400 ThenstrLoanType = “HiRisk”intLoanRate = 4
ElseMsgBox(“Not Qualified“)End
End If
If Statements Within If StatementsAny type of statement may be used
inside the statement(s) portion of any form of If
This includes other If statementsIf statements within If statements
create a more complex decision structure called a Nested If
A customer qualifies for a special rate loan if: If credit score is higher than 650 and▪ Income is more than 30000 Or Debt is less than 1000
Or If credit score is higher than 700
If intCredScr > 650 ThenIf decIncome > 30000 Then
lblMessage.Text = “qualified"ElseIf DecDebt < 1000
lblMessage.Text = “qualified“Else
lblMessage.Text = “not qualified“End If
ElseIf intCredScr > 700 ThenlblMessage.Text = “qualified"
ElselblMessage.Text = “not qualified“
End If
Similar to If…Then…ElseIf Performs a series of tests Conditionally executes the first true condition
Select Case is different in that: A single test expression may be evaluated The test expression is listed once The possible values of the expression are then
listed with their conditional statementsCase Else may be included and executed
if none of the values match the expression
Select Case Val(txtInput.Text)Case 1
MsgBox("Day 1 is Monday.")Case 2
MsgBox("Day 2 is Tuesday.")Case 3
MsgBox("Day 3 is Wednesday.")Case 4
MsgBox("Day 4 is Thursday.")Case 5
MsgBox("Day 5 is Friday.")Case 6
MsgBox("Day 6 is Saturday.")Case 7
MsgBox("Day 7 is Sunday.")Case Else
MsgBox("The value is invalid.")End Select
Select Case strAnimalCase "Dog“,"Cat"
MsgBox("House Pet")Case "Cow“,"Pig“,"Goat"
MsgBox("Farm Animal")Case "Lion“,"Tiger“,"Bear"
MsgBox("Oh My!")End Select
Select Case intScoreCase Is >= 90
strGrade = “A”Case 80 to 89
strGrade = “B”Case 70 to 79
strGrade = “C”Case 60 to 69
strGrade = “D”Case 0 to 59
strGrade = “F”End Select
Write a program that will prompt the user to input a number. Check for valid input. If the input is invalid (non-numeric) – give an error message via MsgBox and end the Event Procedure. If valid – assign the number to a variable and output the number to the user
Now experiment with validity checking for more restrictive input criteria with numbers (ex: only numbers from 1-100, only integers, only positive integers, etc.) and text (ex: only single characters, only the letters a-d, etc.)
Write a program that inputs 2 values and displays their positive difference. For example, if the first input is 6 and the second input is 9, then the positive difference is 3 (note: 3 is still the answer if the first input is 9 and the second input is 6).
Now add the code to handle invalid (non-numeric) input .
Write a VB application to have the user input via textbox an integer from 1 t0 100,000 (inclusive). Determine if the input is a valid. If invalid, give an error message, clear the textbox, and end the event procedure (discuss). If valid, use a boolean function to determine if the integer is even or odd and use an integer function to determine if the integer is a perfect square (return the root if yes, return -1 if no). Report your results via label.
Write a VB application to have the user input a 2 digit binary number via input box. Determine if the input is a valid 2 digit binary number. If not give a specific error message and terminate the app. If valid, convert the number to a decimal value (try using a function to do this) and report the results via message box. (try with 3 digits)
Lab 6 and Homework 6 Visual Basic – Decisions See handout for details and due date Questions?