Loop Statements
Part:
1
2
3
This chapter describes:
- "For ... Next" Statements
- "For ... Next" Statement Example
- "While" Statements
- "While" Statement Example
- "Do ... Loop" Statements
"For ... Next" Statements
"For ... Next" is probably the most commonly used loop statement in VB. Here is its syntax:
For loop_variable = initial_value To final_value [Step interval]
statement_block (multiple statements)
Next
where "loop_variable" is a temporary variable used to control the loop, "initial_value" is the
initial value to be assigned to the loop variable, "final_value" is the upper bound to stop
the loop, and "interval" is the interval that controls how the loop variable to be updated
at each iteration. Note that if "interval" is not specified, "1" will be used as the interval.
If you want to know exactly how the "For ... Next" statement will be executed, here is
my understanding:
Step 1: "intial_value" is assigned to "loop_variable".
Step 2: Comparing the current value of "loop_variable" against the "final_value".
Step 3: If the current value of "loop_variable" is less than or equal to the "final_value", continue with Step 5.
Step 4: If the current value of "loop_variable" is greater than the "final_value", terminate the loop.
Step 5: Execute "statement_block" enclosed in the "For ... Next" loop.
Step 6: Update the "loop_variable" with the current value plus the "interval"
Step 7: Continue with Step 2.
Note that the above description is based positive "interval". If "interval" is a negative value,
the termination condition will be "the loop variable value is less than the final value.
If you want to terminate the loop early, you can use the "Exit For" statement, which will terminate the loop
immediately.
"For ... Next" Statement Example
To help you understand how "For ... Next" statements work, I wrote the following the example, loop_for.html:
<html>
<body>
<!-- loop_for.html
Copyright (c) 2006 by Dr. Herong Yang. http://www.herongyang.com/
-->
<pre>
<script language="vbscript">
document.writeln("")
For i = 3 To 30 Step 2
bIsPrime = True
For j = 2 To i\2
bIsPrime = i Mod j > 0
If Not bIsPrime Then Exit For
Next
If bIsPrime Then
document.writeln("Found a prime number: " & i)
End If
Next
</script>
</pre>
</body>
</html>
(Continued on next part...)
Part:
1
2
3
|