An array is a list of values.
Here is an example of an array.
p = [2, 3, 5, 7, 11]
This array contains five numbers, so p.length
is 5. Places in
an array are counted from zero, so the first value is treated
as the "0th" value p[0]
(the value is 2) and the last value is
the "4th" value p[4]
(the value is 11).
write p.length write "0th:", p[0] write "4th:", p[4]
Notice that what we might normally call the "5th" value is counted as the 4th in a computer array that starts with 0.
for
and in
can be used to repeat some code for each
value in an array. For example:
for x in p
write x, "is prime"
Here x
is a looping variable and takes on each
value in the array, one at a time, while the part of the
program in the loop body is repeated.
We can use any name for a looping variable.
Read more about for
on the for reference page.