In the previous article in this series, Discovering Visual Basic .NET: Making Decisions, you found out how to make your programs smarter by letting them make their own decisions. In the this article, I’ll introduce the topic of looping and show you how to get your program to execute several lines of code again and again.
VB.NET has two types of loops. The For…Next loop counts off a certain number of times and then quits. The Do…Loop uses a condition similar to an If…Then statement to determine whether or not it should continue looping each time.
Counting with For…Next
With the For…Next loop, you can easily execute some commands a set number of times while keeping track of how many times you’ve gone through the loop. Here’s an example:
Imports System Imports Microsoft.VisualBasic Module Santa Public Sub Main() Dim Num As Integer Console.WriteLine("Santa is watching you,") For Num = 1 To 3 Console.WriteLine("...and you,") Next Console.WriteLine("...and especially you!") End Sub End Module
This code displays the same line seven times at seven different font sizes. The result looks like this:
Santa is watching you, ...and you, ...and you, ...and you, ...and especially you!
The For line marks the beginning of the loop. For also identifies the index variable (in this case, Num), the number of the first loop (1), and the number of the last loop (3). The index variable holds the number of the current loop.
The line that contains Next marks the end of the loop. Everything between the For line and the Next line is a part of the loop’s body—that is, the stuff that gets executed again and again. The first time through the loop, Num is set to 1. The second time, it’s set to 2, and the third time, 3.
You can use any Integer variable as an index variable in a For…Next loop. The index variable is simply assigned the loop value each time the For line is executed. Here’s an example showing the index value each time:
Imports System Imports Microsoft.VisualBasic Module Counting Public Sub Main() Dim Count As Integer Console.WriteLine("OK boys and girls, count with me!") For Count = 1 To 5 Console.WriteLine(Count) Next Console.WriteLine("Very good!") End Sub End Module
OK boys and girls, count with me! 1 2 3 4 5 Very good!
But remember that changing the index value yourself within the loop is never a good idea. The For loop really gets confused when you do that.
Most loops usually start with 1. But they don’t have to. You can create a loop like this:
For Items = 10 To 100
This loop sets the variable Items to 10 the first time through, to 11 the second time through, and so on, up to 100. This loop executes 91 times.
Here’s another example:
For Counter = 0 To 5
Again, the first time through, Counter is set to 0, then to 1, and so on, up to 5. This loop executes 6 times.
You can even do this:
For Coordinate = -5 To 5
The first time through, Coordinate is set to -5, then to -4, then on up through 0 and ending with 5. This loop executes 11 times (counting 0).
Watch Where You Step
By using the keyword Step with your For…Next loops, you can tell VB.NET what number the For loop counts by. Here’s an example:
For Num = 2 To 10 Step 2
In this loop, the first time through, Num is assigned 2, then 4, then 6, then 8, and finally 10. Here’s another example:
For Weeks = 0 To 35 Step 7
Weeks is assigned 0 the first time, then 7, then 14, 21, 28, and 35.
You can even step backward! You do that by specifying a negative number for the step value. Here’s an example:
Imports System Imports Microsoft.VisualBasic Module CountDown Public Sub Main() Dim CountDown As Integer For CountDown = 10 To 1 Step -1 Console.WriteLine(CountDown) Next Console.WriteLine("Blast Off!") End Sub End Module
10 9 8 7 6 5 4 3 2 1 Blast Off!
The VB.NET Do…Loop is a very different kind of looping structure from the For…Next loop. Do…Loop enables you to loop while a condition is true or while a condition is false (until it becomes true).
Do While and Do Until
A Do…Loop looks like this:
Imports System Imports Microsoft.VisualBasic Module Gumballs Public Sub Main() Dim Amount As Single Dim Quarters As Integer Amount = 3.85 Quarters = 0 Do Quarters = Quarters + 1 Amount = Amount - .25 Loop While Amount >= .25 Console.WriteLine("You can buy " & Quarters) Console.WriteLine("gumballs at $.25 each") End Sub End Module
You can buy 15 gumballs at $.25 each
As you might expect, the loop begins with Do and ends with Loop. Everything in between is the body of the loop.
You’ll notice in this example that Loop is immediately followed by the keyword While. This keyword indicates that a condition will follow and that the loop will continue executing as long as the condition remains true. When the condition is tested and is false, the loop stops repeating.
You can change the Do line to use Until, instead:
Loop Until Amount < .25
Until is the logical opposite of While. If you use Until, the loop continues as long as the condition remains false. When the condition is tested and is true, the loop stops repeating.
So, to change this program to use Until, I have to change the condition so that the program still works the same way.
The gumball counting program has just one problem.
Set Amount to .17. Now try running the program again:
You can buy 1 gumballs at $.25 each
Hmm. It still says you have enough to buy one gumball. And that’s not true. You don’t have $.25, so the result should be 0. Why did this happen?
Well, when While or Until appears on the Loop line at the bottom of the loop, you can always be sure that the body of the loop will be executed once. That’s because the condition after the While or Until isn’t checked until you get to the Loop line—after you’ve gone through all the lines in the body. This is called a bottom-tested loop.
In this case, it counts off one quarter and subtracts the .25 from Amount. Of course, Amount has a negative number at that point, but the quarter has already been added in.
To fix this, you can switch to a top-tested loop. It’s easy. Just move the While or Until and the condition to the top of the loop, after the Do keyword:
Imports System Imports Microsoft.VisualBasic Module Gumballs Public Sub Main() Dim Amount As Single Dim Quarters As Integer Amount = .17 Quarters = 0 Do Until Amount < .25 Quarters = Quarters + 1 Amount = Amount - .25 Loop Console.WriteLine("You can buy " > Quarters) Console.WriteLine("gumballs at $.25 each") End Sub End Module
This time, the condition is checked first thing, before the body of the loop ever executes. This loop is to execute until Amount is less than .25. In other words, after the value goes below .25, the loop should stop. And because Amount starts out at .17, the loop stops before it ever starts and none of the lines in the loop get executed. You simply jump over the entire loop and begin with whatever follows Loop:
You can buy 0 gumballs at $.25 each
So, is a top-tested loop always better than a bottom tested loop? Not necessarily. The best method depends on what you’re doing and how you want to set it up. In some cases, you want the loop to execute at least once. Use whatever works best for your situation.
Exit, Stage Left
You may discover, right in the middle of a loop, that you want to get out of the loop entirely—no matter what else is happening. VB.NET makes this possible with the Exit command:
For Count = 1 To 100 . . . If Temp > Threshold Then Exit For End If . . . Next
Usually, you find Exit For within an If…Then statement that checks for some special case why the loop needs to end. You can use Exit Do in exactly the same way to exit a Do…Loop.
In this installment, you discovered how to make your programs repeat themselves using loops. This is the last installment for this article series. I hope it has piqued your interest in programming with VB.NET and that it will provide a foundation for your future reading and experimentation with it.