You are currently viewing VB .NET Looping: Everything You Need to Know

VB .NET Looping: Everything You Need to Know

In Visual Basic .NET (VB .NET), looping is an essential concept that allows you to execute a block of code repeatedly. Whether you need to iterate over a collection of data, perform a set of calculations, or control the flow of your program, understanding loops and loop control statements is crucial. This article explores the different types of loops available in VB .NET, along with code examples and detailed explanations to help you master looping in your programming endeavors.

The For Loop

The For loop is a commonly used looping construct in VB .NET. It allows you to repeat a block of code for a specified number of times or iterate over a collection. The syntax of a For loop is as follows:

For variable As datatype = start To end [Step increment]

    ' Code to be repeated
	
Next

Here’s an example that demonstrates a simple For loop that prints the numbers 1 to 10:

Module Scratchpad

    Public Sub Main()

        For counter As Integer = 1 To 10

            Console.WriteLine("The current value of counter is {0}.", counter)

        Next

    End Sub

End Module

The loop variable counter is initialized to 1 and incremented by 1 on each iteration. Increment by 1 is the default if you don’t provide the step value. If you want to increment by any value other than 1, you need to provide the step value, as demonstrated in an example below, that prints the numbers 1 to 10 by increments of 2 using the For loop:

Module Scratchpad

    Public Sub Main()

        For counter As Integer = 1 To 10 Step 2

            Console.WriteLine("The current value of counter is {0}.", counter)

        Next

    End Sub

End Module

The loop continues until the value of counter reaches 10, inclusively. The Console.WriteLine(“The current value of counter is {0}.”, counter) statement prints the value of counter on each iteration.

The For Each Loop

The For Each loop is useful when you want to iterate over each element of a collection, such as an array or a list. It automatically handles the iteration logic, allowing you to focus on processing each item individually. The syntax of a For Each loop is as follows:

For Each element As datatype In collection

    ' Code to be repeated
	
Next

Here’s an example that demonstrates a For Each loop iterating over an array of programming languages:

Module Scratchpad

    Public Sub Main()

        Dim languages() As String = {"C", "Dart", "F#", "Swift", "Visual Basic .NET"}

        ' Iterating over the languages array
        For Each language As String In languages

            ' Print language to the console
            Console.WriteLine(language)

        Next

    End Sub

End Module

The For Each loop iterates over each element of the languages array. The loop variable language holds the current element value on each iteration. The Console.WriteLine(language) statement prints each language in the array.

The While Loop

The While loop allows you to repeat a block of code while a certain condition is true. It is useful when you don’t know the number of iterations in advance. The syntax of a While loop is as follows:

While condition

    ' Code to be repeated
    
End While

Here’s an example that demonstrates printing numbers 1 to 10 using a While loop:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        While counter <= 10

            ' Print current value of counter to the console
            Console.WriteLine("The current value of counter is {0}.", counter)

            ' Add 1 to counter
            counter += 1

        End While

    End Sub

End Module

The loop continues as long as the condition counter <= 10 is true. The loop body prints the value of counter and increments it by 1 in each iteration.

Do While/Until Loop

The Do While and Do Until loops are used when you want to repeat a block of code while or until a specific condition is met. The syntax of a Do While loop is as follows:

Do While condition

    ' Code to be repeated
	
Loop

Similarly, the syntax of a Do Until loop is as follows:

Do Until condition

    ' Code to be repeated
	
Loop

Here’s an example that demonstrates printing numbers 1 to 10 using a Do While loop:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        Do While counter <= 10

            Console.WriteLine("The current value of counter is {0}.", counter)

            counter += 1

        Loop

    End Sub

End Module

The loop starts with the initial value of counter as 1. The loop continues as long as the condition counter <= 10 evaluates to true. The loop body prints the value of counter and increments it by 1 in each iteration.

Here’s an example that demonstrates printing numbers 1 to 10 using a Do Until loop:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        Do Until counter > 10

            Console.WriteLine("The current value of counter is {0}.", counter)

            counter += 1

        Loop

    End Sub

End Module

The loop starts with the initial value of the counter as 1. The loop continues as long as the condition “counter > 10” evaluates to false. Unlike the Do While loop, the Do Until loop executes its block of code when the condition is false. The loop body prints the value of the counter and increments it by 1 in each iteration.

Do Loop While/Until

Additionally, VB .NET provides the Do Loop While/Until loop, which is similar to the Do While/Until loop but with a different placement of the condition. The syntax of the Do Loop While loop is as follows:

Do

    ' Code to be repeated
	
Loop While condition

Similarly, the syntax of the Do Loop Until loop is as follows:

Do

    ' Code to be repeated
	
Loop Until condition

Here’s an example that demonstrates printing numbers 1 to 10 using a Do Loop While loop:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        Do

            Console.WriteLine("The current value of counter is {0}.", counter)

            counter += 1

        Loop While counter <= 10

    End Sub

End Module

The loop starts with the initial value of the counter as 1. The loop body prints the value of the counter and increments it by 1 in each iteration. The loop continues as long as the condition counter <= 10 evaluates to true.

Similarly, you can use the Do Loop Until loop by modifying the condition:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        Do

            Console.WriteLine("The current value of counter is {0}.", counter)

            counter += 1

        Loop Until counter > 10

    End Sub

End Module

The loop continues until the condition counter > 10 evaluates to true. The loop body prints the value of the counter and increments it by 1 in each iteration.

The Do Loop While/Until loops are useful when you want the loop to execute at least once before evaluating the condition. It ensures that the loop body is executed before checking the condition for the first time.

Loop Control Statements

In addition to the various loop types, VB .NET provides loop control statements that allow you to modify the flow of a loop. Some commonly used control statements include:

Exit For

The “Exit For” statement is used to terminate the execution of a For loop prematurely. Here’s an example that demonstrates how to use the “Exit For” statement to terminate a For loop when the loop variable number becomes 6:

Module Scratchpad

    Public Sub Main()

        For number As Integer = 1 To 10


            If number = 6 Then

                Exit For

            End If

            Console.WriteLine("The current value of counter is {0}.", number)

        Next

    End Sub

End Module

The For loop iterates from 1 to 10. The loop body prints the value of counter. When counter is equal to 6, the “Exit For” statement is executed, terminating the loop prematurely. This means that the loop will not continue iterating beyond the number 6.

By using the “Exit For” statement strategically, you can control the flow of your program and stop the execution of a For loop based on a specific condition.

Exit While

The “Exit While” statement is used to prematurely terminate the execution of a While loop. Here’s an example that demonstrates how to use the “Exit While” statement to terminate a While loop when the counter becomes 6:

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        While counter <= 10

            If counter = 6 Then

                Exit While

            End If

            ' Print the current value of counter
            Console.WriteLine("The current value of counter is {0}.", counter)

            ' Add 1 to counter
            counter += 1

        End While

    End Sub

End Module

The loop will terminate when the counter reaches 6. Before terminating, it will print the current value of the counter using the Console.WriteLine statement.

Continue For

The “Continue For” statement is used to skip the remaining statements within a For loop and proceed to the next iteration. It allows you to bypass specific iterations based on certain conditions. Here’s an example that demonstrates how to use the “Continue For” statement within a For loop:

Module Scratchpad

    Public Sub Main()

        For number As Integer = 1 To 10


            If number Mod 2 = 0 Then

                ' Skip number divisible by 2
                Continue For

            End If

            ' Print the odd numbers
            Console.WriteLine(number)

        Next


    End Sub

End Module

The For loop iterates from 1 to 10. The condition number Mod 2 = 0 checks if the current value of number is even. If the condition is true, the “Continue For” statement is encountered, causing the loop to skip the remaining statements and proceed to the next iteration. As a result, only the odd numbers are printed using the Console.WriteLine statement.

The “Continue For” statement is a powerful tool for controlling the flow within a For loop. It allows you to selectively execute certain code based on specific conditions and skip iterations when necessary.

Continue While

The “Continue While” statement in Visual Basic .NET skips the remaining statements in a While loop and proceeds to the next iteration based on a specific condition.

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        While counter <= 10

            If counter Mod 2 = 0 Then
            
                counter += 1
                
                Continue While
                
            End If

            ' Print the odd numbers
            Console.WriteLine(counter)

            counter += 1

        End While

    End Sub

End Module

The While loop iterates as long as the condition counter <= 10 is true. The If statement checks if the current value of counter is even by evaluating the condition counter Mod 2 = 0. If the condition is true, the code within the If block is executed. This skips the remaining statements within the loop and proceeds to the next iteration. By doing so, only the odd numbers are printed using the Console.WriteLine statement.

Continue Do

The “Continue Do” statement is used within a Do loop to immediately transfer control to the loop condition, bypassing any remaining statements within the loop body. It enables you to skip specific iterations of the loop based on certain conditions.

Module Scratchpad

    Public Sub Main()

        Dim counter As Integer = 1

        Do While counter <= 10

            If counter Mod 2 = 0 Then

                counter += 1

                Continue Do

            End If

            ' Print the odd numbers
            Console.WriteLine(counter)

            counter += 1

        Loop

    End Sub

End Module

The Do loop continues as long as the condition counter <= 10 is true. Within the loop body, the If statement checks if the current value of counter is even by evaluating the condition counter Mod 2 = 0. If the condition is true, indicating an even number, the code within the If block is executed. Within the block, the counter is incremented by 1, and the “Continue Do” statement is encountered. This causes the loop to immediately transfer control to the loop condition, skipping any remaining statements within the loop body. Therefore, even numbers are skipped, and only odd numbers are printed using the Console.WriteLine statement.

By using the “Continue Do” statement in combination with conditional logic, you can selectively skip iterations within a Do loop based on specific conditions. This allows for precise control over which iterations are executed, enabling you to handle different scenarios effectively.

Conclusion

We have explored the different types of loops available in VB .NET, including the For loop, For Each loop, Do While/Until loop, and While/Wend loop. We have also covered loop control statements that enable you to control the execution flow within loops. By mastering these looping concepts and utilizing them effectively in your code, you will be equipped to solve a wide range of programming problems.

I hope you found this information informative. If you would like to receive more content, please consider subscribing to our newsletter!

Leave a Reply