The If..Then control structure allows computer programs to make decisions based on the data that is stored in the computer. A good example of getting the computer to make decisions is to find the maximum or minimum values of data that is entered.
The general form is:
|
If - Then |
|
If condition Then |
Condition controls the outcome and must be a Boolean expression.
An
example would be Age < 6.
Consider the following problem;
A student has a Social Science project for which the maximum temperature for a day must be found. The student goes to the Bureau of Meteorology www.bom.gov.au site every hour and downloads the temperature for Perth throughout the day. You are contracted to write a Visual Basic program that will accept the temperatures downloaded over the day and determines the maximum temperature.

GET Temperature
SET Maximum TO Temperature
FOR Time <- 2 TO 12 do
GET Temperature
IF Temperature > Maximum
SET Temperature TO Maximum
END IF
NEXT Time
WRITE Maximum
When the Calculate Button is pressed, a dialogue box asks you enter the first temperature. This is stored in Temperature. Maximum is then set to this temperature. The program uses a loop to displays a dialogue box for you enter the all other temperatures for the day. As each temperature is entered, it is compared to Maximum. If the new Temperature is greater than Maximum then Maximum is changed to this temperature.
Private Sub cmdCalculate_Click()
Dim strTemperature as string Dim Temperature As Integer
Dim DataTime As Integer
Dim Maximum As Integer
Temperature = InputBox("Enter Temperature for 1 O'Clock")
Maximum = Temperature MaxTime = 1
For DataTime = 2 To 12
strTemperature = InputBox("Maximum temp: " & Maximum & " Time: " & MaxTime & " o'clock. " & "Enter Temperature for " & DataTime & " O'Clock")
temperature = CInt(strTemperature) If Temperature > Maximum Then
Maximum = Temperature MaxTime = DataTime
End If
Next DataTime
MsgBox "The maximum temperature is: " & Maximum & " degrees"
End Sub
Depending on whether the condition for the If statement is true or false, a different outcome occurs. If Temperature is greater than Maximum then Maximum is set to Temperature. If the Temperature is not greater than Maximum then there is no change. When all the temperatures have been entered, the largest value is stored in Maximum.
EXERCISE 8 - Attempt ONE of these.
Author Mike Leishman
Last Updated 28 June 1998