For Next: Difference between revisions
(→Syntax) |
|
(No difference)
|
Latest revision as of 13:29, 10 April 2014
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.
Syntax
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
Best Practices
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.
For example, it is impossible to tell how many times the following loop will execute, because the user may change the value of the loop counter each time the loop executes
00010 for i = 1 to 10 00020 print "Enter a value" 00030 input i 00040 next i
Loop Performance
In loops, avoid calculations for which the result never changes—such calculations should typically be placed before the loop.