Discovering Visual Basic .NET: Repeating Code

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:

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: