TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to VBNET

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
An example. Consider a For-loop that goes from 0 to (and including) 5. We can optionally place an Exit For inside this loop for added control over iteration.

Step 1: We use the lower bound 0 and the upper bound 5 in this For-loop statement. The two bounds are inclusive (0 and 5 will be reached).

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

Exit

Step 3: We print the current index of the For loop on each iteration. Because we exit at 3, we only print 0, 1 and 2.

VB.NET program that uses For-Loop, Exit For Module Module1 Sub Main() ' Step 1: specify a loop goes from 0 to 5. For value As Integer = 0 To 5 ' Step 2: exit condition if the value is 3. If value = 3 Then Exit For End If ' Step 3: print the current index of the loop. 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.Array

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.

Part 1: We iterate from 0 to 3 inclusive in the outer For-loop. Inside this loop, we have a nested loop.

Part 2: This is a decrementing loop—we specify its Step as -1, so it counts down.

Part 3: We try to exit the inner loop. When 2 for-loops are nested, and we have an Exit For statement, the inner loop is exited.

VB.NET program that uses nested For-loops, Exit For Module Module1 Sub Main() ' Part 1: outer for-loop. For value As Integer = 0 To 3 Console.WriteLine("OUTER LOOP: {0}", value) ' Part 2: inner for-loop. For value2 As Integer = 5 To 0 Step -1 Console.WriteLine("INNER LOOP: {0}", value2) ' Part 3: exit condition. If value2 = 3 Then ' ... Exit the inner 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.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf