Arrays
and
For
Loops
Method 4
is
clearly
the
best
so
far,
because
it
can deal equally
well
with 4 or 40 or •
400 items by
Just
changing
the
number 4 and adding more
DATA
Items.
You
can
use
as
many
DATA
statements
as
you
need.
In
its
simplest form
the
FOR loop
is
rather
like
the
simplest form
of
REPeal
loop.
The
two can be compared:
100 REPeat
greeting
110 PRINT
"HeLLo"
120
END
REPeat
greeting
100
FOR
greeting
=1
TO
40
110
PRINT
"HeLLo"
120
END
FOR
greeting
Program 5
Both
these
loops would
work.
The REPeal loop would print
'Hello'
endlessly (stop
it
with the BREAK sequence) and the FOR loop would print
'Hello'
Just
forty
times.
Notice that the name
of
the FOR loop
is
also a variable, greeting, whose value varies
from 1
to
40
in
the
course
of
running the program.
This
variable
IS
sometimes called
the loop variable or the control variable
of
the
loop.
Note
the
structure
of
both loops takes the
form:
Opening statement
Content
Closing statement
However,
certain structures
have
allowable short forms
for
use
when there
are
only one •
or a
few
statements
in
the
content
of
the
loop.
Short forms
of
the FOR loop are allowed
so
we
could write
the
program
in
the most economical form
of
all.
100
RESTORE
140 :
CLS
110
DIM
high
st$(4.3)
120
FOR
number = 1
TO
4 :
READ
high_st$(number)
130
FOR
number = 1
TO
4:
PRINT 1
high
st$(number)
1
140
DATA
"VAL",
"HAL",
"MEL",
"DELli
Colons serve
as
end-of-statement symbols instead
of
ENTER and the ENTER symbols
of
lines
120
and
130
serve
as
END FOR
statements.
There
is
an
even
shorter
way
of
writing the above program.
To
print out the contents
of the array
high_st$
we
can replace line
130
by:
130 PRINT I
high_st$
I
This
uses
an
array slicer which
we
will
discuss later
in
chapter
13.
We
have introduced the concept
of
an array
of
string variables
so
that the only numbers
involved would
be
the
subscripts
in
each variable
name.
Arrays
may
be string or numeric, •
and the following examples illustrate the numeric
array.
Program 1 Simulate the
thrOWing
of
a pair
of
dice four hundred
times.
Keep a record
of
the number
of
occurrences
of
each possible score
from
2
to
12.
100 REMark DICEl
110
LET
two =
O:three
=
O:four
=
O:five
=
O:six
= 0
120
LET
seven =
O:eight
=
O:nine
=
O:ten
=
O:eLeven
=
O:twelve
=0
130
FOR
throw
= 1
TO
400
140
LET
diel
=RND(l
TO
6)
150
LET
die2
=RND(l
TO
6)
160
LET
score
=
di
el
+
di
e2
170
IF
score
= 2
THEN
LET
two = two + 1
180
IF
score
=3
THEN
LET
three
=
three
+
190
IF
score
= 4
THEN
LET
four
=
four
+ 1
200
IF
score
=5
THEN
LET
five
=
five
+ 1
210
IF
score
=6
THEN
LET
six
=
six
+ 1
220
IF
score
= 7
THEN
LET
seven
= seven +
230 I F
score
=8
THEN
LET
ei
ght
=
ei
ght
+
240
IF
score
= 9
THEN
LET
nine
=
nine
+ 1
250 I F
score
=10
THEN
LET
ten
=
ten
+ 1
260
IF
score
=
11
THEN
LET
eleven
=eLeven + 1
270
IF
score
=12
THEN
LET
twelve
=
twelve
+ 1
280
END
FOR
throw
290
PRINT!
two!
three!
four!
five!
six
300
PRINT!
seven!
eight!
nine!
ten!
eLeven
I
tweLve
30
12/84