The Do…Loop statement executes a set of statements as long as a condition is true.
Loop While conditionstatements is the body of the loop and is executed at least once. The loop will repeat as long as condition is true. The condition is tested at the end of each loop.
Look at the following example.
Dim intNumber As Integer intNumber = 0 Do intNumber = intNumber + 1 Loop While intNumber < 5
How many iterations (repetitions) does Example 1 do? What is the final value of
Dim intNumber As Integer intNumber = 21 Do While intNumber < 21 intNumber = intNumber + 1 Loop
Alternate Forms of the Do…Loop Statement
The Do…Loop statement has several forms. First, condition can be tested at the beginning or the end. In addition, we have the option of using
Dim intNumber As Integer intNumber = 21 Do intNumber = intNumber + 2 Loop Until intNumber > 25
What is the difference between
Dim intNumber As Integer intNumber = 10 Do intNumber = intNumber + 2 Loop While intNumber > 5
How many iterations does this code complete?
Infinite loop – one that continues forever (the condition never changes). Example 4 results in an infinite loop because intNumber will always be greater than 5.
|The Mobius Strip is the universal symbol of infinity, looking like a sideways number 8. Its unique properties result from a paper loop with a twist in it. When cut in two lengthwise, it remains one.|
Class Exercise: Guesser
We will make a program that turns the tables on the previous guessing game we had. This time, the user chooses the number and the computer will try to guess it.
- Begin by designing the form.
- Use the names
txtSecret, lblStatus, cmdGuess, cmdDonefor the controls on the form.
- Add code to
- Since we will be using random numbers, what do we need to put in
- Add the code for
Private Sub Form_Load() ' initialize random numbers Randomize End Sub
Private Sub cmdGuess_Click()
Private Sub cmdDone_Click()
The Do…Loop Worksheet is due next class.