Visual Basic 2010 (Console) Guide
Do Loops

The For loop is used when the number of iterations is predictable and can be specified. Sometimes, the number of iterations will change at runtime, perhaps based on choices made by a user. In such cases, a Do loop can be used.

Do ... Loop Until

The following program allows a user to type in numbers until they are sick of doing so. They then type in 999 and get to see the total of all of the numbers that they have entered.

Dim numEntered As Integer = 0
Dim total As Integer = 0
Console.Write("Enter a number or 999 to finish> ")
numEntered = Console.ReadLine()
Do
   total += numEntered
   Console.Write("Enter a number or 999 to finish> ")
   numEntered = Console.ReadLine()
Loop Until numEntered = 999

Console.WriteLine("The total of the numbers entered is {0}", total)
Console.ReadLine()

The lines requesting input are duplicated. This structure means that the block of code inside the Do loop is executed at least once. On the first iteration, zero values are added to the total.

Do ... Loop While

Here is the same program using the Loop While condition.

Dim numEntered As Integer = 0
Dim total As Integer = 0
Console.Write("Enter a number or 999 to finish> ")
numEntered = Console.ReadLine()
Do
   total += numEntered
   Console.Write("Enter a number or 999 to finish> ")
   numEntered = Console.ReadLine()
Loop While numEntered <> 999

Console.WriteLine("The total of the numbers entered is {0}", total)
Console.ReadLine()

Do Until...Loop

The Do Loop can also have its stopping condition expressed at the start of the loop. This has the added advantage that the stopping condition can be in place before the first iteration.

Dim numEntered As Integer = 0
Dim total As Integer = 0
Console.Write("Enter a number or 999 to finish> ")
numEntered = Console.ReadLine()
Do Until numEntered = 999
   total += numEntered
   Console.Write("Enter a number or 999 to finish> ")
   numEntered = Console.ReadLine()
Loop

Console.WriteLine("The total of the numbers entered is {0}", total)
Console.ReadLine()

Do While... Loop

The while condition can also be used at the start of the loop.

Dim numEntered As Integer = 0
Dim total As Integer = 0
Console.Write("Enter a number or 999 to finish> ")
numEntered = Console.ReadLine()
Do While numEntered <> 999
   total += numEntered
   Console.Write("Enter a number or 999 to finish> ")
   numEntered = Console.ReadLine()
Loop

Console.WriteLine("The total of the numbers entered is {0}", total)
Console.ReadLine()

Having A Go

  1. Write a program that generates a random number between 1 and 100. Allow the user to keep guessing the number until they have guessed the random number. If they enter a number lower than the number generated, tell them that their number is too low. Do the same if they enter a number higher than the number generated. Once they have guessed the number, tell them how many guesses they entered.