Loops

Keywords: 

A loop is when a program executes the same code again and again. Sometimes a loop runs a fixed number of times, like 100. More often, the loop runs until something happens.

Logical loops for input validation

An example. Click the button below and a program will ask you to type a number. Type anything you want. The program will keep asking until you give it a number.

Here it is in VBA:

  1. Dim userInput As String
  2. Do
  3.     userInput = InputBox("Please enter a number")
  4. Loop Until IsNumeric(userInput)
  1. Dim userInput As String
  2. Do
  3.     userInput = InputBox("Please enter a number")
  4. Loop While Not IsNumeric(userInput)
The general form is:

Do
    [code]
Loop Until [logical expression]
Do
    [code]
Loop While [logical expression]

[logical expression] is either True or False. Loop Until keeps going until [logical expression] is True. Loop While keeps going while [logical expression] is True.

[code] is often called the body of the loop. [logical expression] is often called the loop test, or just test.

Recall that [logical expression] is used in If statements as well:

If [logical expression] Then
    [code]
End if

Variable changes in the loop

Remember that programming is all about the variables. A loop…

Do
    [code]
Loop Until [logical expression]

… keeps going until the value of [logical expression] changes. Almost always, there's a variable in [logical expression] that's also used in [code]. That's what happened here:

  1. Dim userInput As String
  2. Do
  3.     userInput = InputBox("Please enter a number")
  4. Loop Until IsNumeric(userInput)
userInput is in the body of the loop, and in the test. userInput changes in the body of the loop, depending on what the user types. Eventually, it gets a value that lets the loop terminate.

Buggy loops

Check this out:

  1. Dim userInput As String
  2. Dim thing as String
  3. Do
  4.     userInput = InputBox("Please enter a number")
  5. Loop Until IsNumeric(thing)
The variable that's in the test – thing – is not in the body of the loop. The body never changes thing. This is an infinite loop, because it will never stop. No matter what users type, thing is not affected.

Check this out:

  1. Dim userInput As String
  2. Dim thing as String
  3. thing = "16"
  4. Do
  5.     userInput = InputBox("Please enter a number")
  6. Loop Until IsNumeric(thing)
This loop will always run just once, no matter what the user types.

Loops and flags

Sometimes the loop test can be long:

Loop Until animal = "dog" Or animal = "cat" Or animal = "horse" Or animal = "frog" Or userInput = "exit" Or taylorHasLeftTheBuilding

The flag pattern lets you break up the test into manageable pieces. An example:

  1. Dim userInput As String
  2. Dim dataOK As Boolean
  3. Do
  4.     'Init the flag.
  5.     dataOK = False
  6.     'Get user input.
  7.     userInput = InputBox("Type a number, or 'dog'")
  8.     'Check for a number.
  9.     If IsNumeric(userInput) Then
  10.         dataOK = True
  11.     End If
  12.     'Check for dog.
  13.     If userInput = "dog" Then
  14.         dataOK = True
  15.     End If
  16.     If Not dataOK Then
  17.         'Show error message.
  18.         MsgBox "Sorry, that's not valid."
  19.     End If
  20. Loop Until dataOK
Instead of one long test, your break it up into several Ifs. Each one can set the flag. Easier to program, and easier to debug.

Exercise

Exercise: Migos
Write a program that asks the user for the name of a Migos band member.

Input

It keeps asking until the user types Offset, Takeoff, or Quavo. Case doesn't matter. When the user enters valid data, the program shows a MsgBox saying "Thank you!"

For example:

  • Program asks the user to type a band member.
  • User types "cat".
  • Program asks the user to type a band member.
  • The user types "dog".
  • Program asks the user to type a band member.
  • The user types "offset".
  • The program says "Thank you!"

Use the flag pattern.

Upload your Excel file.

(If you were logged in as a student, you could submit an exercise solution, and get some feedback.)

Numbery loops

Click the button to see numbers from 10 to 13, and their squares.

Here's VBA to do that.

  1. Dim x As Integer
  2. x = 10
  3. Do
  4.     MsgBox "The square of " & x & " is " & x * x
  5.     x = x + 1
  6. Loop While x <= 13
Line 5 is the key: add 1 to x. It's common for loops to change their values like that.

Here's another one.

  1. Dim x As Integer
  2. x = 10
  3. Do
  4.     MsgBox "The square of " & x & " is " & x * x
  5.     x = x + 1
  6. Loop Until x < 5
This is an infinite loop. x will never be less than 5.

You don't have to just add 1. You can do any calculation. For example:

  1. Dim count As Integer
  2. Dim message As String
  3. message = "Start the countdown! "
  4. count = 10
  5. Do
  6.     message = message & count & " "
  7.     count = count - 1
  8. Loop While count >= 0
  9. message = message & "We have liftoff!"
  10. MsgBox message
This shows:

Output

There's another way to do numbery loops: a For loop. You'll see that later.

Another exercise

Exercise: Odds
Write a program to show the odd numbers from 1 to 9, when the user clicks a button:

Output

Use a loop.

Upload your Excel file. Note: when you save the file, call it "odds-exercise-solution", not "odd". Sometimes, the name "odd" seems to trigger a Windows security warning.

(If you were logged in as a student, you could submit an exercise solution, and get some feedback.)

Summary

A loop is when a program executes the same code again and again. Sometimes a loop runs a fixed number of times, like 100. More often, the loop runs until something happens.

A loop keeps going until the value of its test expression changes. Almost always, there's a variable in test that's also used in loop body.

The flag pattern lets you break up the test into manageable pieces.