Visual Basic .NET/Loop statements
There are several kinds of looping structures in VB.NET.
Loops allow you to repeat an action for a number of times or until a specified condition is reached.
Do...Loop Until loop
[edit | edit source]A Do...Loop Until loop is a loop that runs until the loop's condition is true, the condition being checked after each iteration of the loop.
Sample:
Do
' Loop code here
Loop Until condition
Do...Loop While loop
[edit | edit source]A Do...Loop While loop runs until the loop's condition becomes false. Its condition is checked after each iteration of the loop.
Sample:
Do
' Loop code ube
Loop While condition
Do Until...Loop loop
[edit | edit source]A Do Until...Loop loop is almost the same as a Do...Loop Until loop. The only difference is that it has the condition's check at the beginning of each iteration of the loop.
Sample:
Do Until condition
' Loop code here
Loop
Do While...Loop loop
[edit | edit source]Likewise, a Do While...Loop loop is almost the same as a Do...Loop While loop. And like the Do Until...Loop loop, the condition's check is at the beginning of each iteration.
Sample:
Do While condition
' Loop code here
Loop
For x as Integer = 1 To 10 console.writeline("x")
For loop
[edit | edit source]A For loop iterates a certain number of times, the value of the counter variable changing each iteration. The For loop is the most well-known looping statement and useful in many programs. A For loop looks like this this:
For a = 1 To 10
' Loop code here
Next
will loop 10 times, since on the first iteration, a would equal 1, the second iteration 2, etc.
A For loop such as this one:
For a = 10 To 1 Step -1
' Loop code here
Next
will loop 10 times, but the counter starts at 10 and goes down to 1.
A For loop like this one:
For a = 11 To 20
' Loop code here
Next
will also loop 10 times. The counter would start at 11 then stops when it reaches 20 .
For Each loop
[edit | edit source]A For Each loop iterates over every index of an array or other iterable object. It requires an object to iterate through, and a variable to hold an index's contents. The object to iterate must implement the IEnumerable
or IEnumerator
interfaces. The implementation of IList
by Array
allows arrays to be used as an object, because IList
inherits from IEnumerable
.
Sample:
Dim arr As Integer() = { 1, 2, 3 }
Dim i As Integer
For Each i In arr
' During each iteration of the For Each loop, i will assume one of three values:
' 1, 2, or 3 as integers.
Next i