For in Visual Basic .NET
Imports System
Module ForLoops
Sub Main()
' The most basic type, with a single condition.
Dim i As Integer = 1
While i <= 3
Console.WriteLine(i)
i += 1
End While
' A classic initial/condition/after For loop.
For j As Integer = 0 To 2
Console.WriteLine(j)
Next
' Another way of accomplishing the basic "do this
' N times" iteration is using a For Each loop.
For Each index As Integer In Enumerable.Range(0, 3)
Console.WriteLine($"range {index}")
Next
' While True will loop repeatedly
' until you Exit While or Return from
' the enclosing function.
While True
Console.WriteLine("loop")
Exit While
End While
' You can also Continue to the next iteration of
' the loop.
For Each n As Integer In Enumerable.Range(0, 6)
If n Mod 2 = 0 Then
Continue For
End If
Console.WriteLine(n)
Next
End Sub
End ModuleIn Visual Basic .NET, we use different looping constructs to achieve similar functionality to the original example:
The basic condition-only loop is implemented using a
Whileloop.The classic three-part loop is implemented using a
Forloop with aToclause.The range-based loop is implemented using a
For Eachloop withEnumerable.Range.The infinite loop is implemented using
While Truewith anExit Whilestatement to break out of it.The
continuefunctionality is achieved usingContinue Forwithin aFor Eachloop.
To run this program, save it as ForLoops.vb and compile it using the Visual Basic compiler:
$ vbc ForLoops.vb
$ mono ForLoops.exe
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5Visual Basic .NET provides various looping constructs that can be used in different scenarios. The For loop is commonly used when you know the number of iterations in advance, while While and Do loops are used when the number of iterations is not known beforehand. The For Each loop is particularly useful for iterating over collections or ranges.