Introduction to Loops

Do…Loop Statement

The Do…Loop statement executes a set of statements as long as a condition is true.

Syntax

Do
statements
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.

Example 1
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 intNumber?

Example 2
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 While or Until.

Example 3
Dim intNumber As Integer
intNumber = 21
Do
    intNumber = intNumber + 2
Loop Until intNumber > 25

What is the difference between While and Until?

Example 4
Dim intNumber As Integer
intNumber = 10
Do
    intNumber = intNumber + 2
Loop While intNumber > 5

How many iterations does this code complete?

Infinite Loops

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.

Guesser form design

  1. Begin by designing the form.
  2. Use the names txtSecret, lblStatus, cmdGuess, cmdDone for the controls on the form.
  3. Add code to cmdDone.
  4. Since we will be using random numbers, what do we need to put in Form_Load()?
  5. Add the code for cmdGuess_Click.

 

Guesser Code
Private Sub Form_Load()
    ' initialize random numbers
    Randomize
End Sub

Private Sub cmdGuess_Click()
‘ dimension
Dim intSecretNumber As Integer
Dim intGuesses As Integer
Dim intGuess As Integer
‘ get secret number
intSecretNumber = txtSecret.Text
‘ guess loop
Do
‘ take a guess from 1 to 100
intGuess = Int(Rnd * 100 + 1)
‘ increment counter
intGuesses = intGuesses + 1
Loop Until intGuess = intSecretNumber
‘ display
lblStatus.Caption = “I guessed your number in ” & _
Format(intGuesses, “0”) & ” guesses.”
End Sub

Private Sub cmdDone_Click()
‘ end program
Unload frmMain
End Sub

Assignment

The Do…Loop Worksheet is due next class.