Array

From C64-Wiki
Jump to: navigation, search

An array is a group of variables that all share the same name. The specific variable in the array is referenced by using its array index. Array variables can be of type integer, float or string.

Examples of array variables:

A(2), A(6), NM$(8), I%(4,6), X(8,5,5)

As can be seen, an array can have two or more index variables (two or more dimensions). In C64 BASIC. arrays can have as many as 255 dimensions altogether. The total number of elements in an array is found by multiplying the maximum index numbers of each dimension together.

If an array is to contain more than 10 variables (also known as elements) or to be multi-dimensional then a DIM statement must be used to set aside memory for the variables. Arrays with 10 or fewer elements are automatically DIMensioned the first time one of the elements is referenced.

Use of arrays means that a programmer doesn't have to think of unique names for a bunch of similar variables. However, the real power in using arrays is that a variable can be used as an array index. This can make for much shorter code.

If one were to input 9 names without using arrays the code might look like follows:

100 INPUT "STUDENT 1";S1$
110 INPUT "STUDENT 2";S2$
120 INPUT "STUDENT 3";S3$
130 INPUT "STUDENT 4";S4$
140 INPUT "STUDENT 5";S5$
150 INPUT "STUDENT 6";S6$
160 INPUT "STUDENT 7";S7$
170 INPUT "STUDENT 8";S8$
180 INPUT "STUDENT 9";S9$

Using an array of strings, the same code would be as follows:

100 FOR I=1 TO 9
110 PRINT "STUDENT";I;:INPUT S$(I)
120 NEXT I

In fact, the same amount of code would be used to input 100 or 1000 names.

As a matter of fact, the DIM statement can also be used with a variable which makes code that uses arrays very flexible (although arrays can only be DIMensioned once). The following code would be impossible without the use of arrays:

100 INPUT "HOW MANY STUDENTS";N:DIM S$(N)
110 FOR I=1 TO N
120 PRINT "STUDENT";I;:INPUT S$(I)
130 NEXT I

Arrays are even more powerful than this because not only can variables be used as an array index, but the array index could be a calculation which might even include another array element.

Being able to reference an array element with statements like

A(A(X)) or A(2*N-3*A(I))

is an extremely powerful and flexible tool for the programmer.

The section on Linked lists shows how arrays can be used to point into arrays.