For loops
A For
loop is a control structure that allows you to execute a block of code repeatedly for a fixed number of times. The basic syntax for a For
loop in VB is as follows:
For cntr As Integer = start To end Step stepValue 'code to execute Next
In this syntax, cntr
is the loop variable that is used to control the loop. The loop will start with the value of start
and end with the value of end
, incrementing the variable by stepValue
each iteration the loop executes. The stepValue
is optional and defaults to 1
if not specified.
Here’s an example of VB.NET code that will loop over a range of numbers and prints each number to the console:
For x As Integer = 1 To 7 Console.WriteLine(x) Next
This code will assign the numbers 1
through 7
to the variable x
and then print it to the console.
A For
loop can also have a custom step value, for example:
For cntr As Integer = 1 To 20 Step 2 ...