HomeSearch

VB.NET For Loop Examples (For Each)

Use For to increment or decrement with a Step. With For Each, enumerate an array.

For, For Each.

Again and again, a loop executes statements. It often has an upper and lower bound. The For-loop proceeds through a range of values. A step indicates the progression.

Another loop,

For-Each, requires a collection—it enumerates each item. Other loops, such as While, continue until a condition is met. If the end is not yet known, While is best.While, Do While

For example.

We use the lower bound 0 and the upper bound 5 in this For-loop statement. Please remember that the two bounds are inclusive.

Inclusive: This means all the numbers in the range, including 0 and 5, will be reached.

Also: We see the Exit For statement—this statement breaks out of the enclosing For-loop. Exit works in all loops and Subs.

Exit
VB.NET program that uses For-Loop, Exit For Module Module1 Sub Main() ' This loop goes from 0 to 5. For value As Integer = 0 To 5 ' Exit condition if the value is 3. If value = 3 Then Exit For End If Console.WriteLine("CURRENT FOR-INDEX: {0}", value) Next End Sub End Module Output CURRENT FOR-INDEX: 0 CURRENT FOR-INDEX: 1 CURRENT FOR-INDEX: 2

Step.

Here 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 continued own in steps of 2 to 0.

Also: The Step keyword is used near the end of the For-statement. A step is the delta each loop iteration will have.

So: If you want to decrement by 1 each time, you can use -1. If you want to increment by 1, use 1.

VB.NET program that uses For Step 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

Nested For.

In many programs, nested loops are essential. In a For-loop, we uniquely name the iteration variable. And we reference all iteration variables (row, column) in an inner block.
VB.NET program that uses nested loops Module Module1 Sub Main() ' Use a nested For-loop. For row As Integer = 0 To 2 For column As Integer = 0 To 2 Console.WriteLine("{0},{1}", row, column) Next Next End Sub End Module Output 0,0 0,1 0,2 1,0 1,1 1,2 2,0 2,1 2,2

For Each example.

Next, we consider the For-Each loop construct. We create a String array (of plant names). We enumerate each string in the array.Arrays

Tip: By using For-Each, we reduce errors in programs. We do not need to maintain the index (or mess it up) ourselves.

Here: We have a "fern" variable we can access in each iteration of the loop. We just pass it to Console.WriteLine.

Console
VB.NET program that uses For Each loop Module Module1 Sub Main() ' The input array. Dim ferns() As String = {"Psilotopsida", _ "Equisetopsida", _ "Marattiopsida", _ "Polypodiopsida"} ' Loop over each element with For Each. For Each fern As String In ferns Console.WriteLine(fern) Next End Sub End Module Output Psilotopsida Equisetopsida Marattiopsida Polypodiopsida

For Each, compared.

How does the For-Each loop compare to the For-loop? First, the For-loop construct may be faster in some cases.

However: As we see in this example, the For-loop has more complexity and is longer in the source code.

Tip: To use For, you need to declare an iteration variable and also specify the loop bounds.

VB.NET program that uses For Each and For Module Module1 Sub Main() ' The input array. Dim rabbits() As String = {"Forest Rabbit", _ "Dice's Cottontail", _ "Brush Rabbit", _ "San Jose Brush Rabbit"} ' Loop over each element with For Each. For Each rabbit As String In rabbits Console.WriteLine(rabbit) Next ' Blank line. Console.WriteLine() ' Use For-loop. For index As Integer = 0 To rabbits.Length - 1 Console.WriteLine(rabbits(index)) Next End Sub End Module Output Forest Rabbit Dice's Cottontail Brush Rabbit San Jose Brush Rabbit Forest Rabbit Dice's Cottontail Brush Rabbit San Jose Brush Rabbit

For Each, List.

Often we use For Each on a List. The loop works on anything that implements IEnumerable, which includes Lists and arrays. Here we enumerate an Integer List.List
VB.NET program that uses For Each on List Module Module1 Sub Main() ' Create new List of 5 Integers. Dim ids = New List(Of Integer)({100, 101, 120, 121, 123}) ' Enumerate all IDs. For Each id In ids Console.WriteLine($"FOR EACH, CURRENT ID = {id}") Next End Sub End Module Output FOR EACH, CURRENT ID = 100 FOR EACH, CURRENT ID = 101 FOR EACH, CURRENT ID = 120 FOR EACH, CURRENT ID = 121 FOR EACH, CURRENT ID = 123

For, String Chars.

The For and For-Each loops can be used on String variables. This gives us a way to check, or process, each character in the Object data.

For each: The For-Each loop can also be used on Strings. When you do not need the index, For-Each is a better, cleaner choice.

Loop Over String
VB.NET program that uses For loop on String Module Module1 Sub Main() Dim value As String = "cat" ' Start at zero and proceed until final index. For i As Integer = 0 To value.Length - 1 ' Get character from string. Dim c As Char = value(i) ' Test and display character. If c = "c" Then Console.WriteLine("***C***") Else Console.WriteLine(c) End If Next End Sub End Module Output ***C*** a t

Adjacent indexes.

Often in For-loops, we need adjacent indexes. We can start at the second index (1) and then access the previous element each time, getting all pairs.

Tip: With this For-loop, we could check for duplicates in a sorted array, or repeated values in any array.

VB.NET program that uses For, adjacent indexes Module Module1 Sub Main() Dim value As String = "abcd" ' Start at one so the previous index is always valid. For i As Integer = 1 To value.Length - 1 ' Get adjacent characters. Dim c As Char = value(i - 1) Dim c2 As Char = value(i) Console.WriteLine(c & c2) Next End Sub End Module Output ab bc cd

Long, non-integer indexes.

The For-loop supports non-integer indexes like Long, Short and UShort. Char is not supported. Here we use For with a Long index.
VB.NET program that uses Long index Module Module1 Sub Main() ' Loop over last three Longs. For d As Long = Long.MaxValue To Long.MaxValue - 2 Step -1 Console.WriteLine(d) Next End Sub End Module Output 9223372036854775807 9223372036854775806 9223372036854775805

Nested For, Exit For.

Let us revisit nested "For" loops with a more complex example. Here we have a loop that decrements inside a loop that increments.

Exit For: When 2 for-loops are nested, and we have an Exit For statement, the immediately enclosing loop (not an outer loop) is exited.

VB.NET program that uses nested For-loops, Exit For Module Module1 Sub Main() ' Outer for-loop. For value As Integer = 0 To 3 Console.WriteLine("OUTER LOOP: {0}", value) ' Inner for-loop. For value2 As Integer = 5 To 0 Step -1 Console.WriteLine("INNER LOOP: {0}", value2) If value2 = 3 Then ' Exit for exits the enclosing loop, not an outer loop. Console.WriteLine("EXIT INNER FOR") Exit For End If Next Next End Sub End Module Output OUTER LOOP: 0 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 1 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 2 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR OUTER LOOP: 3 INNER LOOP: 5 INNER LOOP: 4 INNER LOOP: 3 EXIT INNER FOR

Notes, For Each.

In the C# language, you are not allowed to assign to the iteration variable in a foreach-loop. The VB.NET language has no such restriction.

Warning: If you assign the iteration variable, the behavior of your program may not be as expected.

Overall: For-Each can reduce mismanagement of loop bounds in a For-loop or other kind of loop.

GoTo.

Some looping constructs are more complex. For example, nested For-loops can occur. And to break out of a nested loop, a GoTo statement (which targets a label) is useful.GoTo

Iterator, yield.

A function can be marked as an Iterator. In an Iterator, we yield values. We call an Iterator in a loop and it sequentially returns new values.Iterator

A review.

The For-loop is a core looping construct in the VB.NET language. It provides a way to explicitly specify the loop bounds. And thus it often leads to more robust code.

Meanwhile,

For Each helps us avoid coding errors by not using the index at all. Boundaries are clear, well-defined. Errors are often caused by incorrect loop boundaries.
Home
Dot Net Perls
© 2007-2019 Sam Allen. All rights reserved. Written by Sam Allen, info@dotnetperls.com.