<< 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.
ExitStep 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.
ArrayTip: 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.
ConsoleVB.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.
ListVB.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 StringVB.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.
IteratorA 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.
Related Links:
- VB.NET Nullable
- VB.NET Convert Char Array to String
- VB.NET Object Array
- VB.NET File.ReadAllText, Get String From File
- VB.NET Compress File: GZipStream Example
- VB.NET Console.WriteLine (Print)
- VB.NET File.ReadLines Example
- VB.NET AddressOf Operator
- VB.NET Recursion Example
- VB.NET Recursive File Directory Function
- VB.NET Regex, Read and Match File Lines
- VB.NET Regex.Matches Quote Example
- VB.NET Regex.Matches: For Each Match, Capture
- VB.NET Convert String, Byte Array
- VB.NET File Size: FileInfo Example
- VB.NET File Handling
- VB.NET String.Format Examples: String and Integer
- VB.NET SyncLock Statement
- VB.NET TextInfo Examples
- VB.NET Array.Copy Example
- VB.NET HtmlEncode, HtmlDecode Examples
- VB.NET HtmlTextWriter Example
- VB.NET Stack Type
- VB.NET Func, Action and Predicate Examples
- VB.NET Function Examples
- VB.NET GoTo Example: Labels, Nested Loops
- VB.NET Array.Find Function, FindAll
- VB.NET HttpClient Example: System.Net.Http
- VB.NET DataColumn Class
- VB.NET DataGridView
- VB.NET DataSet Examples
- VB.NET DataTable Select Function
- VB.NET DataTable Examples
- VB.NET Attribute Examples
- VB.NET OpenFileDialog Example
- VB.NET Benchmark
- VB.NET BinaryReader Example
- VB.NET BinarySearch List
- VB.NET BinaryWriter Example
- VB.NET Regex.Replace Function
- VB.NET Regex.Split Examples
- VB.NET Regex.Match Examples: Regular Expressions
- VB.NET Convert ArrayList to Array
- VB.NET Array Examples, String Arrays
- VB.NET ArrayList Examples
- VB.NET Boolean, True, False and Not (Return True)
- VB.NET Nothing, IsNothing (Null)
- VB.NET Directive Examples: Const, If and Region
- VB.NET Do Until Loops
- VB.NET Do While Loop Examples (While)
- VB.NET Array.Resize Subroutine
- VB.NET Chr Function: Get Char From Integer
- VB.NET Class Examples
- VB.NET IndexOf Function
- VB.NET Insert String
- VB.NET Interface Examples (Implements)
- VB.NET 2D, 3D and Jagged Array Examples
- VB.NET Enum.Parse, TryParse: Convert String to Enum
- VB.NET Remove HTML Tags
- VB.NET Remove String
- VB.NET Event Example: AddHandler, RaiseEvent
- VB.NET Excel Interop Example
- VB.NET StartsWith and EndsWith String Functions
- VB.NET Initialize List
- VB.NET Number Examples
- VB.NET Optional String, Integer: Named Arguments
- VB.NET Replace String Examples
- VB.NET Exception Handling: Try, Catch and Finally
- VB.NET Enum Examples
- VB.NET Enumerable.Range, Repeat and Empty
- VB.NET Dictionary Examples
- VB.NET Double Type
- VB.NET LSet and RSet Functions
- VB.NET LTrim and RTrim Functions
- VB.NET Alphanumeric Sorting
- VB.NET PadLeft and PadRight
- VB.NET String.Concat Examples
- VB.NET String
- VB.NET Math.Abs: Absolute Value
- VB.NET Array.IndexOf, LastIndexOf
- VB.NET Remove Duplicate Chars
- VB.NET If Then, ElseIf, Else Examples
- VB.NET ParamArray (Use varargs Functions)
- VB.NET Integer.Parse: Convert String to Integer
- VB.NET ThreadPool
- VB.NET Process Examples (Process.Start)
- VB.NET TimeZone Example
- VB.NET Path Examples
- VB.NET ToArray Extension Example
- VB.NET ToCharArray Function
- VB.NET Stopwatch Example
- VB.NET Button Example
- VB.NET StreamReader ReadToEnd Function
- VB.NET ByVal Versus ByRef Example
- VB.NET StreamReader Example
- VB.NET StreamWriter Example
- VB.NET String.Compare Examples
- VB.NET Cast: TryCast, DirectCast Examples
- VB.NET String Constructor (New String)
- VB.NET String.Copy and CopyTo
- VB.NET Math.Ceiling and Floor: Double Examples
- VB.NET Math.Max and Math.Min
- VB.NET WebClient: DownloadData, Headers
- VB.NET Math.Round Example
- VB.NET Math.Truncate Method, Cast Double to Integer
- VB.NET Reverse String
- VB.NET Structure Examples
- VB.NET Sub Examples
- VB.NET Substring Examples
- VB.NET Convert Dictionary to List
- VB.NET Convert List and Array
- VB.NET Convert List to String
- VB.NET Convert Miles to Kilometers
- VB.NET Property Examples (Get, Set)
- VB.NET Remove Punctuation From String
- VB.NET Queue Examples
- VB.NET Const Values
- VB.NET Remove Duplicates From List
- VB.NET IComparable Example
- VB.NET ReDim Keyword (Array.Resize)
- VB.NET Contains Example
- VB.NET IEnumerable Examples
- VB.NET IsNot and Is Operators
- VB.NET String.IsNullOrEmpty, IsNullOrWhiteSpace
- VB.NET ROT13 Encode Function
- VB.NET StringBuilder Examples
- VB.NET Image Type
- VB.NET Val, Asc and AscW Functions
- VB.NET String.Empty Example
- VB.NET String.Equals Function
- VB.NET VarType Function (VariantType Enum)
- VB.NET With Statement
- VB.NET WithEvents: Handles and RaiseEvent
- VB.NET String Length Example
- VB.NET ToList Extension Example
- VB.NET ToLower and ToUpper Examples
- VB.NET TextBox Example
- VB.NET ToString Overrides Example
- VB.NET ToTitleCase Function
- VB.NET Convert String Array to String
- VB.NET Iterator Example: Yield Keyword
- VB.NET Mid Statement
- VB.NET Mod Operator (Odd, Even Numbers)
- VB.NET Convert String to Integer
- VB.NET Module Example: Shared Data
- VB.NET Integer
- VB.NET Keywords
- VB.NET Lambda Expressions
- VB.NET LastIndexOf Function
- VB.NET String Join Examples
- VB.NET Multiple Return Values
- VB.NET MustInherit Class: Shadows and Overloads
- VB.NET Namespace Example
- VB.NET KeyValuePair Examples
- VB.NET Environment.NewLine: vbCrLf
- VB.NET Levenshtein Distance Algorithm
- VB.NET Shared Function
- VB.NET Shell Function: Start EXE Program
- VB.NET Sleep Subroutine (Pause)
- VB.NET Sort Dictionary
- VB.NET Exit Statements
- VB.NET LINQ Examples
- VB.NET List Examples
- VB.NET Extension Method
- VB.NET Select Case Examples
- VB.NET MessageBox.Show Examples
- VB.NET Timer Examples
- VB.NET TimeSpan Examples
- VB.NET BackgroundWorker
- VB.NET String Between, Before and After Functions
- VB.NET CStr Function
- VB.NET DataRow Field Extension
- VB.NET DataRow Examples
- VB.NET DateTime Format
- VB.NET Char Examples
- VB.NET DateTime.Now Property (Today)
- VB.NET DateTime.Parse: Convert String to DateTime
- VB.NET DateTime Examples
- VB.NET Decimal Type
- VB.NET HashSet Example
- VB.NET Hashtable Type
- VB.NET Fibonacci Sequence
- VB.NET XmlWriter, Create XML File
- VB.NET File.Copy: Examples, Overwrite
- VB.NET File.Exists: Get Boolean
- VB.NET Path.GetExtension: File Extension
- VB.NET Tuple Examples
- VB.NET Trim Function
- VB.NET TrimEnd and TrimStart Examples
- VB.NET Word Count Function
- VB.NET Word Interop Example
- VB.NET For Loop Examples (For Each)
- VB.NET XElement Example
- VB.NET Truncate String
- VB.NET Sort Number Strings
- VB.NET Sort Examples: Arrays and Lists
- VB.NET SortedList
- VB.NET SortedSet Examples
- VB.NET Split String Examples
- VB.NET Uppercase First Letter
- VB.NET XmlReader, Parse XML File
- VB.NET ZipFile Example
- VB.NET Array.Reverse Example
- VB.NET Random Lowercase Letter
- VB.NET Byte Array: Memory Usage
- VB.NET Byte and Sbyte Types
- VB.NET Char Array
- VB.NET Random String
- VB.NET Random Numbers
- VB.NET Async, Await Example: Task Start and Wait
- VB.NET Choose Function (Get Argument at Index)
- VB.NET Sort by File Size
- VB.NET Sort List (Lambda That Calls CompareTo)
- VB.NET List Find and Exists Examples
- VB.NET Math.Sqrt Function
- VB.NET Loop Over String: For, For Each
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