Download Software Development

Transcript
HIGH LEVEL LANGUAGE PROGRAMMING – BASIC CONSTRUCTS
4.12
Do .. Loop Until
We have used For ... Next loops to repeat a section of program a set
number of times. This is fine if we know how many times the section of
program is to be repeated. What about when the number of repetitions
is unknown in advance?
For example, a quiz program might give the user repeated chances to
get the answer correct. The programmer doesn’t know in advance
whether the user will get the question right first time, or take 2, 3, 4 or
more attempts.
In this type of situation, the programmer needs to use another kind of
loop. Visual BASIC provides several other types of loop. We will use a
type called Do ... Loop Until.
The pattern (syntax) for this type of loop is very simple:
Do
Line(s) of code
To be repeated
Loop Until condition
Here is a simple example:
Set up a form like this: Enter the following coding for the
command button:
Private Sub cmdQuestion_Click()
‘ generates a question to the user
‘ and waits for the correct answer
Dim user_answer As Integer
Dim correct_answer As Integer
correct_answer = 4
Do
user_answer = InputBox(“What is 2 + 2?”)
Loop Until user_answer = correct_answer
MsgBox (“Well done!”)
End Sub
Run the program. Does it behave as predicted?
SOFTWARE DEVELOPMENT (INT 2, COMPUTING)
119