|
FOR
Abbreviation: F <SHIFT+O>
TYPE: Statement
FORMAT: FOR <variable> = <start> TO <limit>
[ STEP <increment> ]
Action: This is a special BASIC statement that lets you easily
use a variable as a counter. You must specify certain parameters:
the floating-point variable name, its starting value, the limit
of the count, and how much to add during each cycle.
Here is a simple BASIC program that counts from 1 to 10, PRINTing
each number and ENDing when complete, and using no FOR statements:
100 L = 1
110 PRINT L
120 L = 1 + 1
130 IF L <= 10 THEN 110
140 END
Using the FOR statement, here is the same program:
100 FOR L = 1 TO 10
110 PRINT L
120 NEXT L
130 END
As you can see, the program is shorter and easier to understand
using the FOR statement.
When the FOR statement is executed, several operations take
place. The <start> value is placed in the <variable>
being used in the counter. In the example above, a I is placed
in L.
When the NEXT statement is reached, the
<increment> value is added to the <variable>. If a
STEP was not included, the <increment> is set to + 1. The
first time the program above hits line 120, 1 is added to L, so
the new value of L is 2.
Now the value in the <variable> is compared to the <limit>.
If the <limit> has not been reached yet, the program G0es
TO the line after the original FOR statement. In this case, the
value of 2 in L is less than the limit of 10, so it GOes TO line
110.
Eventually, the value of <limit> is exceeded by the <variable>.
At that time, the loop is concluded and the program continues
with the line following the NEXT statement.
In our example, the value of L reaches 11, which exceeds the limit
of 10, and the program goes on with line 130.
When the value of <increment> is positive, the <variable>
must exceed the <limit>, and when it is negative it must
become less than the <limit>.
NOTE: A loop always executes at least once.
EXAMPLES of FOR...TO...STEP...Statement:
100 FOR L = 100 TO 0 STEP -1
100 FOR L = PI TO 6* {pi} STEP .01
100 FOR AA = 3 TO 3
|