VB.Net - For...Next Loop

Advertisements


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.

The syntax for this loop construct is:

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

Flow Diagram:

for loop in VB.Net

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

When the above code is compiled and executed, it produces the following result:

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

If you want to use a step size of 2, for example, you need to display only even numbers, between 10 and 20:

Module loops
   Sub Main()
      Dim a As Byte
      ' for loop execution 
      For a = 10 To 20 Step 2
          Console.WriteLine("value of a: {0}", a)
      Next
      Console.ReadLine()
   End Sub
End Module

When the above code is compiled and executed, it produces the following result:

value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20


Advertisements
Advertisements