Suppose you have a list of numbers, for instance the marks of ten people in a class. To store them in the computer you could set up a single variable for each person, but you would find them very awkward. You might decide to call the variable Bloggs 1, Bloggs 2, and so on up to Bloggs 10, but the program to set up these ten numbers would be rather long and boring to type in.
How much nicer it would be if you could type this:
5 REM this program will not
work
10 FOR n=1 TO 10
20 READ Bloggs n
30 NEXT n
40 DATA 10,2,5,9,16,3,11,1,0,6
Well, you can't!
However, there is a mechanism by which you can apply this idea, and it uses arrays. An array is a set of variables, its elements, all with the same name, and distinguished only by a number (the subscript) written in parentheses after the name. In our example the name could be b and the ten variables would then be b(1), b(2), and so on up to b(10).
The elements of an array are called subscripted variables, as opposed to the simple variables that you are already familiar with.
Before you can use an array, you must reserve some space for it inside the computer, and you do this using a DIM (for dimension) statement:
DIM b(10)
sets up an array called b with dimension 10 (i.e. there are 10 subscripted variables b(1),...,b(10)) and initialises the 10 values to 0. It also deletes any array called b that existed previously. (But not a simple variable. An array and a simple numerical variable with the same name can coexist, and there shouldn't be any confusion between them because the array variable always has a subscript). The subscript can be an arbitrary numerical expression, so now you can write:
5 DIM b(10)
10 FOR n=1 TO 10
20 READ b(n)
30 NEXT n
40 DATA 10,2,5,9,16,3,11,1,0,6
to read in the elements from a DATA list, or:
10 FOR %n=1 TO 10
20 INPUT %m(n)
30 NEXT %n
to INPUT the elements' values by hand. Note, that in the second example there is no DIM statement. That's because as discussed in Chapter 1, the second array is an integer array. Integer arrays come predimensioned to a fixed 64 elements numbered 0 to 63. Attempting
ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.