Chapter 9 If ..Then ..Else.

In the previous chapter, the result of the decision made some action, or nothing to happen. The command can be used to make an alternate action happen as well, which is the norm.

The general form is:

If - Then -Else

If condition Then
… statements
Else
... statements
EndIf

Condition controls the outcome and must be a Boolean expression.
An example would be Age < 6.

The following example will demonstrate how this is done.

PROBLEM 9

The Australian Taxation office allows some people to claim use of their private car. Cars which have engine capacities 1500 cc and over are allowed 65c per kilometer travelled, while those with engine capacities up to 1500cc are allowed 45c per kilometer because they are smaller. A program is needed to calculate the allowances.

PLANNING

Get EngineSize 
Get Kilometers
If EngineSize < 1500 Then
  Set CurrentRate To SmallRate
Else
  Set CurrentRate To LargeRate
EndIf
Set Allowance To CurrentRate * Kilometers
Write Kilometers and Allowance

CODING

Private Sub CmdCalculate_Click()
  Const SmallRate = 0.3
  Const LargeRate = 0.35
Dim strEnginesize, strKilometers as string

  Dim EngineSize As Integer
  Dim Kilometers As Integer
  Dim CurrentRate As Single
  Dim Allowance As Currency
strEngineSize = InputBox("Enter the size of the engine (cc)", "Enduro")
Enginesize = cInt(strEngineSize)
  strKilometers = InputBox("Enter the number of Kilometers travelled", "Enduro")
Kilometers = cInt(strKilometers)
  If EngineSize < 1500 Then
    CurrentRate = SmallRate
  Else
    CurrentRate = LargeRate
  End If
  Allowance = CurrentRate * Kilometers
  MsgBox "The allowance for " & Kilometers & " kilometers is $" & Allowance
End Sub 

If the condition is true, the first set of commands are carried out (in this case the CurrentRate is set to the SmallRate). If the condition is fales, the alternate commands are carried out. (CurrentRate is set to the LargeRate)

EXERCISE 9 - Attempt 1

  1. Rewrite the guessing game program so that if a person guesses the wrong number, they will receive a message telling them that they are too high or too low.
  2. You have been contracted to write a Wages Calculator in Visual Basic by Freddies Fast Food. Juniors under 18 get $5.60 and hour and the rest get $7.80 and hour. Write the program to calcule the wage of an employeee based on the ageand number of hours worked in a week.
  3. The Western Water Works charged $2.45 per kilolitre of water used for the first 100 kiloliters used. Then it charges $3.15 for every kilolitre of water used thereafter. Write a program in Visual Basic to allow a person to calculate the amout owing after entering the amount of water used (in kilolitres).

Author: Mike Leishman

updated: 28 June 1998

edited FDS 27/3/07