For Next: Difference between revisions
No edit summary |
No edit summary |
||
Line 37: | Line 37: | ||
00020 print counter | 00020 print counter | ||
00030 next counter | 00030 next counter | ||
====COMMON ERROR==== | |||
Although the value of the LOOP COUNTER VARIABLE can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors. | |||
<noinclude> | <noinclude> | ||
[[Category:Control Structures]] | [[Category:Control Structures]] | ||
</noinclude> | </noinclude> |
Revision as of 15:35, 20 February 2012
FOR counter = initial_value to final_value [STEP step_value] [loop body] NEXT counter
A FOR LOOP allows you to specify that an application should repeat a statement or set of statements until a counter reaches its final_value.
The loop body may consist of zero or more statements. However, the use of at least one statement in the loop body is encouraged for clarity.
The optional numeric step_value following the STEP keyword specifies by how much to increase or decrease the counter variable with each execution of the FOR LOOP. If the STEP keyword is absent and step_value isn't specified, then the default value of +1 is used. If step_value is negative, then the counter variable is decreased with each execution of the loop.
Although it is not required to indent the body of a FOR LOOP, it is highly recommended to indent it for readability.
Examples
This example prints integers from 1 to 100:
00010 for counter = 1 to 100 00020 print counter 00030 next counter
The same effect may be achieved by this program:
00010 for counter = 1 to 100 step 1 ! this is redundant, since the default value of 1 is used anyway. 00020 print counter 00030 next counter
This program prints numbers from 100 to 1 in descending order:
00010 for counter = 100 to 1 step -1 00020 print counter 00030 next counter
This program prints EVEN numbers from 2 to 100 in ascending order:
00010 for counter = 2 to 100 step 2 00020 print counter 00030 next counter
COMMON ERROR
Although the value of the LOOP COUNTER VARIABLE can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.