VB.NET For Loop - For...Next Statement in Visual Basic 2008
Unlike the other two loops, the For. . .Next loop requires that you know the number of times that the statements in the loop will be executed. The For. . .Next loop has the following syntax:
The keywords in the square brackets are optional. The arguments counter, start, end, and increment are all numeric. The loop is executed as many times as required for the counter to reach (or exceed) the end value.
In executing a For. . .Next loop, Visual Basic does the following:
The For. . .Next loop in Listing 3.4 scans all the elements of the numeric array data and calculates their average.
Listing 3.4: Iterating an Array with a For. . .Next Loop
The single most important thing to keep in mind when working with For. . .Next loops is that the loop's ending value is set at the beginning of the loop. Changing the value of the end variable in the loop's body won't have any effect. For example, the following loop will be executed 10 times, not 100 times:
You can, however, adjust the value of the counter from within the loop. The following is an example of an endless (or infinite) loop:
This loop never ends because the loop's counter, in effect, is never increased. (If you try this, press Ctrl + Break to interrupt the endless loop.)
The increment argument can be either positive or negative. If start is greater than end, the value of increment must be negative. If not, the loop's body won't be executed, not even once. VB 2008 allows you to declare the counter in the For statement. The counter variable ceases to exist when the program bails out of the loop:
The i variable is used as the loop's counter and it's not visible outside the loop. The last statement won't even compile; the editor will underline it with a wiggly line and will generate the error message Name 'i' is not declared.
Manipulating the Loop's Counter
Manipulating the counter of a For. . .Next loop is strongly discouraged. This practice will most likely lead to bugs such as infinite loops, overflows, and so on. If the number of repetitions of a loop isn't known in advance, use a Do. . .Loop or a While. . .End While structure. To jump out of a For. . .Next loop prematurely, use the Next For statement.
Table of Contents
W3computing.com Copyright 2011 © All Rights Reserved