VB For Loop


It repeats a group of statements a specified number of times and a loop index counts the number of loop iterations as the loop executes.

Syntax

For counter [ As datatype ] = start To end [ Step step ]
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ counter ]

Example

Module loops
   Sub Main()
      Dim a As Byte
      ' for loop execution 
      For a = 10 To 20
          Console.WriteLine("value of a: {0}", a)
      Next
      Console.ReadLine()
   End Sub
End Module
Output
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

For Each...Next Loop

It repeats a group of statements for each element in a collection. This loop is used for accessing and manipulating all elements in an array or a VB.Net collection.

Syntax

For Each element [ As datatype ] In group
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ element ]
Example
Module loops
   Sub Main()
      Dim anArray() As Integer = {1, 3, 5, 7, 9}
      Dim arrayItem As Integer
     'displaying the values
      For Each arrayItem In anArray
          Console.WriteLine(arrayItem)
      Next
      Console.ReadLine()
   End Sub
End Module
Output
1
3
5
7
9

Share this article on