Visual Basic .NET - For Loop

The for loop is a control statement in VB.NET that allows for repeated execution of a block of statements, based on the initial value, final value, and the increment or decrement value of a loop counter. The syntax for the for loop in VB.NET is:

For counter As DataType = startValue To endValue [Step incrementValue]
    ' statements to be executed
Next [counter]

where:

  • counter: a variable used to keep track of the number of iterations through the loop
  • DataType: the data type of the loop counter variable
  • startValue: the initial value of the loop counter
  • endValue: the final value of the loop counter
  • incrementValue: the amount by which the loop counter is incremented or decremented (optional)

Here are a few examples of for loops in VB.NET:

Example : A simple for loop that counts from 1 to 10 by 1.

For i As Integer = 1 To 10
    Console.WriteLine(i)
Next

Example : A for loop that counts backwards from 10 to 1 by 2.

For i As Integer = 10 To 1 Step -2
    Console.WriteLine(i)
Next

Example : A for loop that iterates through each element of an array.

Dim myArray() As Integer = {1, 2, 3, 4, 5}
For i As Integer = 0 To myArray.Length - 1
    Console.WriteLine(myArray(i))
Next

In the first example, the loop counter i starts at 1 and counts up to 10 by 1 on each iteration. In the second example, the loop counter i starts at 10 and counts down to 1 by 2 on each iteration. In the third example, the loop counter i is used to access each element of the myArray array using the i variable as the index.

The for loop is useful when you know exactly how many times you want to execute a block of statements.