Repetition - FOR and DO loops in Visual Basic
Common features of all programming languages are:
Visual Basic manifests all of these. Examples:
Functions - built-in functions (e.g., IsNumeric(), Val(), Format()) or
user-defined functions
We are now focusing on repetition.
For...Next loops use a numeric variable as a counter to keep track of the number of times the loop actually
needs to run. This variable is called an index. A typical For loop:
Dim Index
For Index = 1 to 3
[ do something ]
Next
This will repeat any code between the For and Next statements three times. The value of variable Index will take the value 1, then 2, then 3 on the first, second, and third iteration of the loop, respectively.
The Do loop is an alternative way to repeat a block of code. The Do/While loop is common, and has this form:
Do
[ do something ]
Loop While [ condition ]
Note the Do loop, unlike the For loop, does not necessarily involve a built-in variable (For can't run without one). A Do loop equivalent to the above For loop is:
Dim Limit As Integer
Limit = 3
Do
[ do something ]
Limit = Limit - 1
Loop While Limit > 0
In both cases, when execution reaches the lower bound in the code (Next or Loop statement), a decision is made whether to repeat again based on a condition
(with For, whether the index variable has reached the stated maximum; with Do, or whether the condition coded in the Loop statement
remains true). If the decision is yes, the block of code inside the loop is repeated once again. If no, the loop has finished its job and the next statement below the loop gets executed.