VB.NET For Loop Examples

For loop

You want to execute a block of statements a certain number of times in your VB.NET program. Ideal for this purpose, the For loop requires you provide a top index, a bottom index, and also allows an optional step. The For loop is a powerful and expressive way to iterate through numbers.

These VB example programs use the For loop. One loop increments; another decrements.

For example

First, this example uses the lower bound 0 and the upper bound 5 in the For loop statement. Please remember that the two bounds are inclusive, meaning all the numbers including 0 and 5 will be reached. In addition, this example demonstrates the Exit For statement; this statement breaks out of the enclosing For loop.

Program that uses For [VB.NET]

Module Module1
    Sub Main()
	' This loop goes from 0 to 5.
	For value As Integer = 0 To 5
	    ' Exit condition if the value is three.
	    If (value = 3) Then
		Exit For
	    End If
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

0
1
2

For Step example

Steps

In this example, we want to decrement the counter variable instead of increment it: in other words, we go down not up. We start at 10 and then continue down in steps of 2 to 0. The Step keyword is used near the end of the For statement and it is the delta each loop iteration will have upon the counter variable. So if you want to decrement by 1 each time, you can use -1; if you want to increment by 1, use 1.

Program that uses For Step [VB.NET]

Module Module1
    Sub Main()
	' This loop uses Step to go down 2 each iteration.
	For value As Integer = 10 To 0 Step -2
	    Console.WriteLine(value)
	Next
    End Sub
End Module

Output

10
8
6
4
2
0

Summary

The VB.NET programming language

As one of the core looping constructs in the VB.NET programming language, the For loop provides a way to explicitly specific the loop bounds. Because of this specification, the For loop can lead to more robust code, as fewer careless bugs caused by incorrect loop boundaries may occur. For another looping construct, please read about the For Each loop.

For Each Loop Examples VB.NET Tutorials
.NET