For Loop in VB.net

By: Ramlak Emailed: 1786 times Printed: 2623 times    

The For loop is probably the most popular of all Visual Basic loops. The Do loop doesn't need aloop index, but the For loop does; a loop index counts the number of loop iterations as the loop executes. Here's the syntax for the For loop—note that you can terminate a For loop at any time with Exit For:

For index = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next [index]

The index variable is originally set to start automatically when the loop begins. Each time through the loop, index is incremented by step (step is set to a default of 1 if you don't specify a value) and when index equals end, the loop ends.

Here's how to put this loop to work; in this case, I'm displaying "Hello from Visual Basic" four times (that is, intLoopIndex will hold 0 the first time; 1, the next; followed by 2; and then 3, at which point the loop terminates):

Module Module1
    Sub Main()
        Dim intLoopIndex As Integer
        For intLoopIndex = 0 To 3
            System.Console.WriteLine("Hello from Visual Basic")
        Next intLoopIndex
    End Sub
End Module

Here's what you see when you run this code:

Hello from Visual Basic
Hello from Visual Basic
Hello from Visual Basic
Hello from Visual Basic
Press any key to continue

If I were to use a step size of 2:

For intLoopIndex = 0 To 3 Step 2
    System.Console.WriteLine("Hello from Visual Basic")
Next intLoopIndex

I'd see this result:

Hello from Visual Basic
Hello from Visual Basic
Press any key to continue
Tip 

Although it's been common practice to use a loop index after a loop completes (to see how many loop iterations were executed), that practice is now discouraged by people who make it their business to write about good and bad programming practices.

Most Viewed Articles (in VB.net )

Latest Articles (in VB.net)

Comment on this tutorial