Selection / Decisions - PowerPoint PPT Presentation

About This Presentation
Title:

Selection / Decisions

Description:

CIS 115 Lecture 7 * * * * * * * * * * * * * * * * * * * * * * * * If Statements Within If Statements Any type of statement may be used inside the statement(s) portion ... – PowerPoint PPT presentation

Number of Views:72
Avg rating:3.0/5.0
Slides: 42
Provided by: debrac7
Category:

less

Transcript and Presenter's Notes

Title: Selection / Decisions


1
Selection / Decisions
  • CIS 115 Lecture 7

2
Control Structures
  • 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

3
VB Decisions
  • Visual Basic decision statements
  • IfThen
  • one-way selection structure
  • IfThenElse
  • two-way selection structure
  • IfThenElseIf
  • multi-way selection structure
  • IfThenElseIfElse
  • multi-way selection structure
  • Select Case
  • multi-way selection structure

4
IfThen Decision Structure
  • IfThen decision structure
  • provides one choice
  • Evaluate the condition True or False
  • Ex Is it cold outside?
  • True execute code
  • Ex If yes, wear a coat
  • False do not execute code
  • Ex If no,

Condition
True
False
Conditional Code
5
IfThen Statement Syntax
  • If condition Then
  • statements
  • End If
  • Syntax explanation
  • If , Then, and End Keywords
  • Condition True/False value, variable, function
    call or expression
  • Statements one or more code statements to be
    executed if condition is true

6
Conditions
  • 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

7
Boolean Variables
  • 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
8
Boolean Functions
  • 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
9
Relational Operators
  • Often a condition is formed using a relational
    operator
  • A relational operator determines if a specific
    relationship exists between two values
  • gt Greater than
  • lt Less than
  • Equal to
  • ltgt Not equal to
  • gt Greater than or equal to
  • lt Less than or equal to

10
Relational Operators (cont.)
  • Relational operators are binary meaning they
    use two operands
  • Either or both relational operator operands may
    be values, variables, expressions or function
    calls
  • length lt 10 (Is length less than or equal to
    10)
  • len wid gt 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

11
Relational Operators (cont.)
  • Either or both relational operator operands may
    be expressions
  • Math operators are evaluated before relational
    operators
  • xy and a-b are evaluated first
  • Each result is then compared using the gt operator
  • Either or both relational operator operands may
    be function calls

If x y gt a - b Then lblMessage.Text "It is
true!" End If
If Val(txtInput.Text) lt getMinValue()
Then lblMessage.Text "Invalid Below
Minimum" End If
12
Logical Operators
  • 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

13
The And Operator
The truth table for the And Operator Expression
1 Expression 2 Expression 1 And Expression
2 True False False False True False False F
alse False True True True
If temperature lt 20 And minutes gt 12
Then lblMessage.Text Temperature is in the
danger zone." End If
  • AndAlso operator works identically but does not
    test minutesgt12 if temperaturelt20 is false

14
The Or Operator
The truth table for the Or Operator Expression 1
Expression 2 Expression 1 Or Expression
2 True False True False True True True True
True False False False
If temperature lt 20 Or temperature gt 100
Then lblMessage.Text Temperature is in the
danger zone." End If
  • OrElse operator works identically but does not
    test temperaturegt100 if temperaturelt20 is true

15
The Xor Operator
The truth table for the Xor Operator Expression
1 Expression 2 Expression 1 Xor Expression
2 True False True False True True True True
False False False False
If total gt 1000 Xor average gt 120
Then lblMessage.Text You may try again." End
If
16
The Not Operator
The truth table for the Not Operator Expression
1 Not Expression 1 True False False True
If Not temperature gt 100 Then lblMessage.Text
"You are below the max temp." End If
17
Example Checking Numerical Ranges
  • 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 lt vs lt or gt vs gt
  • Check problem requirements for ranges carefully

If x gt 20 And x lt 40 Then lblMessage.Text
Value is in the acceptable range." End If
If x lt 20 Or x gt 40 Then lblMessage.Text
Value is outside the acceptable range." End If
18
Precedence of Logical Operators
  • 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

19
Relational Logical Operators Combined
  • For example, in the statement
  • If x lt 0 And y gt 100 Or z 50
  • x lt 0 And y gt 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 lt 0 And (y gt 100 Or z 50)

20
All Operators Precedence
  • Parenthesis
  • Arithmetic
  • Exponential
  • Multiplication / Division
  • Integer Division
  • MOD
  • Addition / Subtraction
  • String Concatenation
  • Relational Operators (lt , gt , gt , lt , ltgt)
  • Logical Operators
  • Not
  • And
  • Or, Xor)

21
Arithmetic, Relational, Logical Operators
Combined
  • Evaluate the following if a5, b7, x100, y30
  • If x gt a 10 And y lt b 20
  • Evaluating the math operators leaves us with
  • If x gt 50 And y lt 27
  • Evaluating the relational operators leaves
  • If True And False
  • Evaluating the logical operators leaves
  • False
  • Parentheses make order of operations clear
  • If (x gt (a 10)) And (y lt (b 20))

22
IfThen Examples
  • If (intSales gt 50000) Then
  • blnGetsBonus True
  • End If
  • --------------------------------------------------
    ---------------
  • If ((blnGetsBonus)Or((intMissedDays lt
    2)And(intSales gt 30000)))
  • intDaysOff intDaysOff 1
  • intEmpRating 1
  • End If
  • --------------------------------------------------
    ---------------
  • If (Not(isNumeric(txtInput.text))) Then
  • txtInput.text
  • MsgBox(Please enter a number in the textbox)
  • End If
  • --------------------------------------------------
    ---------------
  • If (intGrade gt 80)And(intGrade lt 90) Then
    lblMessage.text B
  • --------------------------------------------------
    ---------------
  • If ((Val(txtGrade.text) lt 0)Or(Val(txtGrade.text)
    gt 100)) Then
  • lblMessage.text Invalid Grade Not in the
    range 0-100
  • End If

23
IfThen vs IfThenElse
  • The IfThen construct will execute or ignore a
    group of statements (do something or do nothing)
  • The IfThenElse construct will execute one group
    of statements or another group (do this or do
    that)

Condition
True
False
Statement(s) If True
Statement(s) If False
Condition
True
False
Statement(s) If True
24
IfThenElse Decision Structure
  • IfThenElse
  • provides two choices
  • Evaluate condition
  • True or False
  • True execute code
  • in IfThen block
  • False execute code
  • in Else Block
  • One of the two choices must be selected
  • They are mutually exclusive

Condition
True
False
Statement(s) If True
Statement(s) If False
25
IfThenElse Syntax
  • If condition Then
  • statements1
  • Else
  • statements2
  • End If
  • Syntax explanation
  • If , Then, Else, and End Keywords
  • Condition True/False value, variable, function
    call or expression
  • Statements1 executed if condition is True
  • Statements2 executed if condition is False

26
IfThenElse Examples
  • If (intSales gt 50000) Then
  • blnGetsDoubleBonus True
  • decBonus 4000.00
  • Else
  • decBonus 2000.00
  • End If
  • --------------------------------------------------
    ---------------
  • If (Not(isNumeric(txtInput.text))) Then
  • MsgBox(You did not enter a valid number
    program will end)
  • End
  • Else
  • intNumber Val(txtInput.text)
  • End If
  • --------------------------------------------------
    ---------------
  • If (intTemp gt 60)And(intTemp lt
    90)And(VisibRating() gt 5) Then
  • lblMessage.text Go - Weather conditions are
    ideal
  • Else
  • lblMessage.text Wait - Weather conditions
    unacceptable
  • End If

27
IfThenElseIf Decision Structure
  • IfThenElseIf
  • allows for multiple
  • mutually exclusive
  • choices
  • Each of the conditions
  • is tested in sequence
  • When a condition is
  • true, the corresponding
  • code is executed and the
  • remaining conditions are ignored

C1
True
Statement(s)1
False
True
C2
Statement(s)2
False
True
C3
Statement(s)3
False
28
IfThenElseIf Conditions
  • If it is very cold Then
  • Wear a coat
  • Elseif it is chilly
  • Wear a light jacket
  • Elseif it is windy
  • Wear a windbreaker
  • Elseif it is hot
  • Wear no jacket
  • The order of the conditions is vital
  • Wrong order can result in wrong decision
  • What if its chilly and windy?
  • If windy is tested before chilly, youd go out
    with a windbreaker when you need a jacket

29
IfThenElseIf Syntax
  • Syntax explanation
  • If , Then, ElseIf, and End
  • Keywords
  • Condition1 thru n True/False
  • value, variable, function
  • call or expression
  • Statements1 executed if
  • condition1 is True
  • Statements2 executed if condition1 is False
    and if condition2 is True
  • Statementsn executed if condition1 thru
    (n-1) is False and if conditionn is True
  • If condition1 Then
  • statements1
  • ElseIf condition2
  • statements2
  • ElseIf conditionn
  • statementsn
  • End If

30
IfThenElseIf Examples
  • If sngAvg lt 59.5 Then
  • lblGrade.Text "F"
  • ElseIf sngAvg lt 69.5 Then
  • lblGrade.Text "D"
  • ElseIf sngAvg lt 79.5 Then
  • lblGrade.Text "C"
  • ElseIf sngAvg lt 89.5 Then
  • lblGrade.Text "B"
  • ElseIf sngAvg lt 100 Then
  • lblGrade.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 Then
  • CredCrdPayment(decSubTot)
  • ElseIf radDebCrd.checked Then
  • DebCrdPayment(decSubTot)
  • ElseIf radCheck.checked Then
  • CheckPayment(decSubTot)
  • End If

31
IfThenElseIfElse (Trailing Else)
  • IfThenElseIf
  • Else is simply an
  • IfThenElseIf
  • with an Else at the end
  • Called a Trailing Else
  • If the initial If and none
  • of the ElseIf conditions
  • are True, the trailing
  • Else statement(s) will
  • be executed

C1
True
Statement(s)1
False
True
C2
Statement(s)2
False
True
C3
Statement(s)3
False
Statement(s)Else
32
IfThenElseIf Else Syntax
  • Syntax explanation
  • Same as If..ThenElseIf
  • thru statements n
  • StatementsElse
  • executed if condition1 thru n
  • (all previous conditions) are False
  • If condition1 Then
  • statements1
  • ElseIf conditionn
  • statementsn
  • Else
  • statementsElse
  • End If

33
IfThenElseIfElse Examples
  • If sngAvg lt 59.5 Then
  • lblGrade.Text "F"
  • ElseIf sngAvg lt 69.5 Then
  • lblGrade.Text "D"
  • ElseIf sngAvg lt 79.5 Then
  • lblGrade.Text "C"
  • ElseIf sngAvg lt 89.5 Then
  • lblGrade.Text "B"
  • ElseIf sngAvg lt 100 Then
  • lblGrade.Text "A
  • Else
  • lblGrade.Text "Invalid"
  • End If
  • If intCredScr gt 700 Then
  • strLoanType Prime
  • intLoanRate 1
  • ElseIf intCredScr gt 600 Then
  • strLoanType Standard
  • intLoanRate 2
  • ElseIf intCredScr gt 500 Then
  • strLoanType Risk
  • intLoanRate 3
  • ElseIf intCredScr gt 400 Then
  • strLoanType HiRisk
  • intLoanRate 4
  • Else
  • MsgBox(Not Qualified)
  • End
  • End If

34
Nested If
  • If Statements Within If Statements
  • Any type of statement may be used inside the
    statement(s) portion of any form of If
  • This includes other If statements
  • If statements within If statements create a more
    complex decision structure called a Nested If

35
Nested If Example
  • 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 gt 650 Then
  • If decIncome gt 30000 Then
  • lblMessage.Text qualified"
  • ElseIf DecDebt lt 1000
  • lblMessage.Text qualified
  • Else
  • lblMessage.Text not qualified
  • End If
  • ElseIf intCredScr gt 700 Then
  • lblMessage.Text qualified"
  • Else
  • lblMessage.Text not qualified
  • End If

36
Select Case Statement
  • Similar to IfThenElseIf
  • 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 statements
  • Case Else may be included and executed if none of
    the values match the expression

37
Select Case Statement Examples
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 strAnimal Case "Dog,"Cat" MsgBox("
House Pet") Case "Cow,"Pig,"Goat" MsgBox("Far
m Animal") Case "Lion,"Tiger,"Bear" MsgBox("O
h My!") End Select
Select Case intScore Case Is gt 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
38
Example Decision Problems
  • 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.)

39
Example Decision Problems
  • 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 .

40
Example Decision Problems
  • 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)

41
Homework
  • Lab 6 and Homework 6
  • Visual Basic Decisions
  • See handout for details and due date
  • Questions?
Write a Comment
User Comments (0)
About PowerShow.com