IF Statement
VB09
If statements deal with uncertainty
• If statements allow the computer program to take a different course of action, depending on certain conditions
Syntax of IF statement
If booleanExpression Thenone or more statements
Elseone or more statements
End If
Semantics of IF statement
If booleanExpression Thenone or more statements
Elseone or more statements
End If
If the Boolean expression evaluates to TRUE then execute the first block of statements. Otherwise execute the second block.
Example 1
If raining then
get a taxiElse
walkEnd If
Example 2
If curOwe > curHave Then
blnDebt = TRUE
Else
blnDebt = FALSE
End If
If statements can be nested
If curTaxOwed > curTadPaid ThenIf blnPolitician Then
blnJail = FALSEElse
blnJail = TRUEEnd If
ElseblnJail = FALSE
End If
If statements can be nested
If curTaxOwed > curTadPaid ThenIf blnPolitician Then
blnJail = FALSEElse
blnJail = TRUEEnd If
ElseblnJail = FALSE
End If
Add 10% for shipping. Free Shipping for all orders over $20!
If curPrice < 20 then
curShipping = curPrice * 10 / 100
Else
curShipping = 0
End if
curTotal = curPrice + curShipping
Example: Books on the web
• Write a program that accepts as input the price of a book in local currency at four Amazon stores and outputs the name of the cheapest store
Books on the web - Plan
• Input the 4 prices• Convert to Euro where required• Figure out the cheapest• Output the name
Books on the web - Form
Amazon.com
Amazon.co.uk
Amazon.fr
Buy the book at
Calculate
Exit
Books on the web - Form
Amazon.com
Amazon.co.uk
Amazon.fr
Buy the book at
Calculate
Exit
txtUS
txtUK
txtFR
txtCheapest
Attach code to Calculate button
Input Prices
curUSlocal = txtUS.text
curUKlocal = txtUK.text
curFR = txtFR.text
This takes the values from the text boxes and puts them into variables
Convert prices to Euro
curUS = curUSlocal * .99
curUK = curUKlocal * 1.6
This code converts the US $ and UK £ to €. The French price is already in €
Find the cheapestIf (curUS <= curUK) And (curUS <= curFR) Then
-- USA is cheapeststrCheapest = “Amazon.com”
Else-- Contest between Uk and FRIf curUK <= curFrance Then
-- UK is cheapeststrCheapest =
“Amazon.co.uk”Else
-- FR is cheapeststrCheapest =“Amazon.fr”
End ifEnd if
Output Results
txtCheapest.text = strCheapest
Exercise 09.1
• Write a program that accepts the price of a book in local currency at four stores and outputs the location of the cheapest
• Remember that prices at Amazon.de are in €
Exercise 09.2
• Modify the program written for Exercise 09.1 so that the exchange rates are input by the user
Exercise 09.3
• The cost of shipping one book to Ireland is different depending on where it comes from
• Modify the program written for Exercise 09.2 so that the cost of shipping the book is taken into account
$7.98
£3.94
€7.52
€5.60