MSDN Documentation

VB.NET Loops

Loops are fundamental control flow structures that allow you to execute a block of code repeatedly. VB.NET provides several types of loops to suit different scenarios, enabling efficient iteration over collections, execution of tasks a specific number of times, or repeating until a condition is met.

Types of Loops in VB.NET

1. For...Next Loop

The For...Next loop is ideal when you know in advance how many times you want to repeat a block of code. It uses a counter variable that increments or decrements with each iteration.

Syntax:

For counter [ As datatype ] = start To end [ Step step ]
    ' Code to be executed
Next [ counter ]

Example:

Printing numbers 1 to 5

Sub PrintNumbers()
    For i As Integer = 1 To 5
        Console.WriteLine(i)
    Next
End Sub

The Step keyword can be used to increment or decrement the counter by a value other than 1.

2. For Each...Next Loop

The For Each...Next loop simplifies iterating over collections, such as arrays or lists. It automatically handles the progression through each element without needing to manage an index.

Syntax:

For Each element [ As datatype ] In collection
    ' Code to be executed for each element
Next [ element ]

Example:

Iterating through an array of strings

Sub ProcessNames()
    Dim names() As String = {"Alice", "Bob", "Charlie"}
    For Each name As String In names
        Console.WriteLine("Hello, " & name)
    Next
End Sub

3. Do...Loop

The Do...Loop statement allows for more flexible looping conditions. It can execute the loop body either before or after checking the condition.

Syntax (Do While):

Do While condition
    ' Code to be executed
Loop

Syntax (Do Until):

Do Until condition
    ' Code to be executed
Loop

Syntax (Do Loop While):

Do
    ' Code to be executed
Loop While condition

Syntax (Do Loop Until):

Do
    ' Code to be executed
Loop Until condition

Example:

Counting down using Do While

Sub CountDown()
    Dim count As Integer = 3
    Do While count >= 1
        Console.WriteLine(count)
        count -= 1
    Loop
End Sub

Executing at least once with Do Loop Until

Sub InputLoop()
    Dim input As String
    Do
        input = Console.ReadLine()
        Console.WriteLine("You entered: " & input)
    Loop Until input.ToLower() = "exit"
End Sub

4. While...End While Loop

The While...End While loop is similar to Do While, but it checks the condition *before* executing the loop body. If the condition is initially false, the loop body will never execute.

Syntax:

While condition
    ' Code to be executed
End While

Example:

Printing even numbers

Sub PrintEvenNumbers()
    Dim num As Integer = 0
    While num <= 10
        If num Mod 2 = 0 Then
            Console.WriteLine(num)
        End If
        num += 1
    End While
End Sub

Exiting Loops

You can use the Exit For and Exit Do statements to break out of a loop prematurely based on certain conditions.

Example with Exit For:

Finding the first occurrence

Sub FindFirstMatch()
    Dim numbers() As Integer = {10, 25, 5, 40, 15}
    Dim found As Boolean = False
    For Each num As Integer In numbers
        If num > 20 Then
            Console.WriteLine("Found number greater than 20: " & num)
            found = True
            Exit For ' Exit the loop
        End If
    Next
    If Not found Then
        Console.WriteLine("No number greater than 20 found.")
    End If
End Sub

Loop Control Statements

VB.NET also offers: