For and For Each Loops
Prerequisites: If statements
For ... Next
A For loop counts from a start value to an end value (inclusive):
Module Program
Sub Main()
For i = 1 To 5
Console.Write(i & " ")
Next
Console.WriteLine()
For i = 10 To 0 Step -2
Console.Write(i & " ")
Next
Console.WriteLine()
For i = 0 To 1 Step 0.25
Console.Write(i & " ")
Next
Console.WriteLine()
End Sub
End Module
1 2 3 4 5
10 8 6 4 2 0
0 0.25 0.5 0.75 1
Stepsets the increment; a negative step counts down.- The loop variable's type is inferred from the start, end, and step
values — the last loop uses a
Double. - You can write
Next ito name the variable being closed, which helps in nested loops.
For Each ... Next
For Each visits every item in an array or collection:
Module Program
Sub Main()
Dim fruits = {"apple", "banana", "cherry"}
For Each fruit In fruits
Console.WriteLine("I like " & fruit)
Next
For Each ch As Char In "VB!"
Console.Write($"[{ch}]")
Next
Console.WriteLine()
End Sub
End Module
I like apple
I like banana
I like cherry
[V][B][!]
Exit For and Continue For
Module Program
Sub Main()
For Each n In {3, 8, -1, 12, 5}
If n < 0 Then
Console.WriteLine("negative found, stopping")
Exit For
End If
If n Mod 2 = 0 Then Continue For
Console.WriteLine($"odd: {n}")
Next
End Sub
End Module
odd: 3
negative found, stopping
Exit For leaves the loop; Continue For skips to the next item.
Nested loops
Module Program
Sub Main()
For row = 1 To 3
For col = 1 To 4
Console.Write((row * col).ToString().PadLeft(4))
Next col
Console.WriteLine()
Next row
End Sub
End Module
1 2 3 4
2 4 6 8
3 6 9 12
Common mistakes
Without As Type, a For Each variable first looks for an existing
name in scope — and VB has built-in functions called Day, Month,
Input, and more. This doesn't compile:
Module Program
Sub Main()
For Each day In {"Mon", "Tue"}
Console.WriteLine(day)
Next
End Sub
End Module
main.vb(3) : error BC30455: Argument not specified for parameter 'DateValue' of 'Public Overloads Function Day(DateValue As Date) As Integer'.
For Each day In {"Mon", "Tue"}
~~~
main.vb(4) : error BC30455: Argument not specified for parameter 'DateValue' of 'Public Overloads Function Day(DateValue As Date) As Integer'.
Console.WriteLine(day)
~~~
Pick another name (dayName) or declare the type explicitly:
For Each day As String In ....
Practice
Print the multiplication table of 7 from 7 x 1 = 7 to
7 x 10 = 70, but skip the line for 5 using Continue For.
Show solution
Module Program
Sub Main()
For i = 1 To 10
If i = 5 Then Continue For
Console.WriteLine($"7 x {i} = {7 * i}")
Next
End Sub
End Module
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70