For / next / step – Remote Processing CAMBASIC User Manual

Page 83

Advertising
background image

Comm ands - 50

FOR / NEXT / STEP

Statements

SYNTAX:

FOR variable = n TO m [STEP z]
.
.
.
NEXT

PURPOSE:

To perfor m a loop oper ation a given number of times.

REMARK S:

n and m are positive (including zer o ) numbe rs and the optional z may be negative or positive, but
not 0.

n is the initial value of the counter. m is the final value of the counter. The pr ogram lines following
the FO R statem ent are e xecuted until the NEX T statem ent is encounte red. Then the c ounter is
incremented by the amount specified by the STEP value z. If z is not specified, the increm ent is
assumed to be 1 (one). A check is performed to see if the value of the counter is now greater than
the final value m. If it is not greater, CAMBASIC branches back to the statement after the FOR
statement and the process is repeated. If it is greater, execution continues with the statement
following the NEXT statement. This is a FOR/ NEX T loop.

If z is negative, the test is reversed. The counter is decr emented each time through the loop, and the
loop is executed until the counter is less than the final value.

The body of the loop is executed once if n is already greater than m when the STEP value is positive,
or if n is less than m when the STEP value is negative. If z is zero, an er ror will be displayed.

FOR/ NEXT loops may be nested, that is, one FOR/ NEXT loop may be placed inside another
FOR /N EXT loop. When loo ps are ne sted, each loop m ust have a uniq ue varia ble name as its
counter. T he NEXT statement for the inside loop must appear before the NEXT for the outside
loop.

EXAMPLE:

10 J=10 : K=30
20 FOR I=1 TO J STEP 2
30 PRINT I ;
40 K = K + 10
50 PRINT K
60 NEXT

1

40

3

50

5

60

7

70

9

80

ERROR:

< NEXT w/o FOR> – if a NEXT is encountered without a corresponding FOR
< Data out of range> – if z = 0

Advertising