ThelineHELP
MY
COMPUTER HAS GONE
BERSERK ! was
printed
5 times, then
NO IT'S
UNDER
CONTROL. The FOR-NEXT loop created
in lines 8
and
20
caused the Computer to
cycle
through lines
8, 10
and
20
exactly 5
times,
then
continue
through the
rest
of
the program.
Each time
the Computer hit line
2(9
it
saw
"NEXT
N."
The word NEXT caused
the value
of N to
be
increased
(or STEPped) by exactly
1,
and
the
Computer
unconditionally
sent
back to
the
FOR N
=
statement
that
began the
loop. The
NEXT
statement
is
conditional
on
N
being less than
5,
because line 8 says FOR N
=
1 TO 5.
After the 5th pass through the loop, the built-in test fails, the loop is broken and
the pro-
gram
execution
moves
on.
The FOR-NEXT statement harnessed the endless loop!
The STEP function
There are times when
it
is
desirable
to
increment the
FOR-NEXT
loop by some value other
than one. The STEP
function allows
that.
Change line
8 to read
8 FOR
N =
1
TO
5
STEP
2
. . . and RUN.
Line
10
was
printed
only
3
times
(when N=l, N=3 and N=5). On the first pass through the
program, when NEXT N was hit, it incremented {or STEPped) the value
of N by 2 instead
of
1. On
the
second
pass through the
loop
N equalled
3.
On the third
pass through N equal-
led 5.
FOR-NEXT loops can be stepped by any whole number, even negative numbers. Why one
would
want to step
with
negative numbers
might
seem rather vague at this time, but that
too will
be understood
with
time. In the
meantime,
change the following
line
8
FOR N =
5 TO 1 STEP
-1
. . . and
RUN.
Five passes
through
the
loop
stepping
down from 5 to 1 is exactly the same as stepping
up
from 1 to
5.
Line
10
still
got
printed
5 times.
Modifying
the
FOR-NEXT
loop
Suppose
we
wanted
to print both lines
10
and
30
five times, alternating between
them. How
would
you change the program to accomplish it? Go ahead and make the change.
46