The Array Advantage

Authors

Publication

Pub Details

Date

Pages

See all articles from SYNC v4 n2

An array is just another kind of variable, right? Well, yes and no: an array is another kind of variable, but it is not just another variable.

There are arrays to store numbers, there are arrays to hold strings, and there are lots of things you can do with arrays that you cannot do with simple variables.

Numeric Arrays

A numeric array is like a row of boxes: each is able to hold any number you want to put into it. To tell the computer how many boxes you want to reserve, use a DIM statement, e.g., DIM B (5) tells the computer to reserve five memory cells. Each cell, or element, in the array is named by the variable any single letter) used with DIM and a subscript that indicates its place in the array.

B(1) B(2) B(3) B(4) B(5) 

are the subscripted variables for the array dimensioned above.

An array variable name on the TS2068 can be either upper or lower case. Because the computer considers upper and lower case letters interchangeable when it comes to variables, you still have only 26 different single-letter variables.

Filling the Boxes

When an array is dimensioned, all its cells are automatically filled with zeros. Type in, as direct commands:

DIM A(2) 
PRINT A(1),A (2)

You will get two zeros on the screen-the contents of the two “boxes.”

Placing a number into an array cell is like assigning a value to any other variable:

LET N(4) =17 

might appear in a program, while

INPUT L(3) 

would allow the cell to be filled while the program is running.

The subscripted variable that stands for an array element can be used in the same way that other variables are used, SO:

LET A (4) =B (4) *C (2) and PLOT X (3) , Y (3) 

are valid programming statements.

Listing 1

5 REM "ARRAY DEMO"
10 DIM A(10)
15 FOR N=1 TO 10
20 PRINT "WHAT DO YOU WANT IN CELL ";N
25 INPUT A(N)
30 NEXT N
35 CLS
40 FOR N=1 TO 10
45 PRINT "CELL ";N;" CONTAINS ";A(N)
50 NEXT N

The great advantage of arrays over regular variables is the ease with which values can be assigned and retrieved. Listing 1 demonstrates this. It will ask you to INPUT a value for each of ten cells, and then print them out on the screen. Compare this program to one you would have to write if you were using regular variables instead; without the FOR-NEXT loops that can be used with subscripted variables, your listing would be about ten times longer.

An Application

Listing 2 is a short game that shows how you might use an array. It is a simple “guess my number” game with two added features: a subroutine that checks if you are repeating yourself when giving an answer, and a recap of all your guesses at the end. You have ten tries to find the correct number between one and fifty.

Lines 10-50 constitute the basic guess- ing game. The subroutine at line 100 checks the current guess (G) against the contents of the array-each cell holds a prior guess. If a match is found, the player is informed, and the program returns to the INPUT line; if no match is found, the current guess is placed into the next available array cell. Lines 70-80 use a FOR-NEXT loop to print out all the wrong guesses.

Listing 2

5 REM "GUESS"
10 DIM A(10)
15 LET N=INT (RND*50)+1
20 FOR T=1 TO 10
25 SCROLL
30 PRINT "TAKE A GUESS"
35 INPUT G
40 IF G=N THEN GOTO 55
45 GOSUB 100
50 NEXT T
55 CLS
60 PRINT ("RIGHT " AND G=N)+("SORRY, " AND G<>N);"THE NUMBER WAS ";N
65 PRINT "YOUR GUESSES WERE:"
70 FOR N=1 TO 10
75 PRINT A(N)
80 NEXT N
85 STOP
100 FOR K=1 TO 10
105 IF G=A(K) THEN GOTO 130
110 IF G<>A(K) THEN NEXT K
115 LET A(T)=G
120 RETURN
130 SCROLL
135 PRINT "YOU TRIED THAT ALREADY"
140 GOTO 35

Another Dimension

The “rows of boxes” in the previous programs are single dimension arrays, because you are working with a single row of boxes. If you visualize rows of boxes on top of each other or information presented in rows and columns, you will be dealing with a two-dimensional array.

A two-dimensional array is dimensioned by two numbers with the DIM statement, and each element in the array is identified by two subscripts.

DIM Z(3,4)

dimensions an array with twelve cells (three rows of four boxes). The first element is named Z(1,1) and the last Z(3,4). It is easy to keep track of the element names if you think of the first number as referring to a row and the second to a column. Figure 1 shows just how the cells in this array are named.

Figure 1

Cell subscripts for two-dimensional array

1,11,21,31,4
2,12,22,32,4
3,13,23,33,4

While the “stack of boxes” is a helpful image in understanding two-dimensional arrays, keep in mind that the computer does not actually have memory cells in that configuration.

An Application

Any data that benefits from a row/column presentation is a candidate for a two-dimension array. The program in Listing 3 uses a two-dimensional array. The program in Listing 3 uses a two-dimensional array to keep track of the number of local and long distance calls made during the course of a week.

Listing 3

5 REM "CHART"
10 DIM P(2,7)
15 GOSUB 50
20 PRINT TAB 14;"LOCAL";TAB 21;"LONG"
25 PRINT ,,"MON",,"TUES",,"WED",,"THUR",,"FRI",,"SAT",,"SUN";AT 2,0
30 FOR X=1 TO 7
35 PRINT TAB 15;P(1,X);TAB 22;P(2,X)
40 NEXT X
45 STOP
50 FOR N=1 TO 2
55 FOR X=1 TO 7
60 LET R=INT (RND*20)
65 LET P(N,X)=R
70 NEXT X
75 NEXT N
80 RETURN

The array is set up as two rows of seven cells. (It could have been seven rows of two cells.) The subroutine at line 50 fills the array with random data. Lines 20 and 25 set up the screen, lines 30-45 print the data on the screen.

The effectiveness of a two-dimensional array is not immediately apparent, because this program could have been written with a single dimension array, or even with separate variables for all the data (although assigning variable values would not have been so simple.)

The importance of the two-dimensional array is evident when you want to manipulate the data. For instance, the total of local calls and long distance calls made during the week can be calculated with the following subroutine:

LET LOCAL=0
LET LONG=0
FOR N=1 TO 7
LET LOCAL=LOCAL+P(1,N)
LET LONG=LONG+P(2,N)
NEXT N

The first two lines of this subroutine are examples of variable initialization. Because we want to use LOCAL and LONG to store ever-increasing totals as the FOR-NEXT loop is performed, we use the statement

LET LONG=LONG+P (2, N)

and a similar one for LOCAL. Using these statements, however, without assigning initial values to the variables would result in an “undefined variable” error. This initialization procedure is used very often in games, where the variable that stores the score is initialized to zero. Array elements, remember, are automatically initialized to zero when you dimension the variable.

The latter part of this routine uses a FOR-NEXT loop to add the first column figures into LOCAL and the second column figures into LONG. The average local or long distance calls per day are then LOCAL/7 and LONG/T. Try adding the printout of these statistics to your display, as well as writing a subroutine to calculate the total number of calls per day, and all the calls made during the week.

Other Dimensions

Numeric arrays are not limited to two dimensions. You might want to add statistics to the “telephone” program for each week of the year. In that case,

DIM P(52,7,2)

would set up a three-dimensional array, which you could visualize as 52 pages of rows and columns.

Arrays of more that three dimensions are possible, although progressively more difficult to visualize:

DIM P(2,2,2,2,2)

sets up a five-dimensional array with 32 elements (rows, columns, pages, books, shelves?).

The overall number of elements you can dimension depends on the memory you have available.

Caveats

Some computers will stop a program with a “re-dimensioning” error if you use the same array name twice. A ZX/TS computer will do what it is told: it will dimension the same array over again, wiping out all your data in the process.

So, be careful where you place your DIM statement-keep it outside loops, as in the listings accompanying this article.

RUN will also wipe out the contents of an array, just as it erases regular variable values: use GOTO when you are working with a program with arrays!

String Arrays

String arrays are similar to numeric arrays in that a DIM statement is used to reserve memory space, and the use of subscripted variables makes the strings easy to store and retrieve.

However, string arrays have one major difference that calls for a more thorough study: for a string array, you have to indicate not only how many elements you want in the array (how many strings you want to store, but also how long the strings will be.

DIM N$(5,10)

will dimension an array that will hold five strings of ten characters each. If you use only one subscript when dimensioning a string array, e.g.,

DIM A$(10)

the computer will assume the number refers to the length of the string, and dimension an array of one element — and, yes, there are uses for a one-element string array!

While you can think of numeric arrays as rows of boxes, string arrays are more like a series of shelves, with only a certain amount of space on each shelf. Each string goes on one shelf, but each character of the string goes into one of the spaces on the shelf.

Once Upon a Time

This brings us to the story of Procrustes, a legendary (and, we hope, mythical Greek innkeeper who forced travelers to fit one of two beds either by stretching their bodies to the right length, or by chopping off that portion of the anatomy that might be hanging over the edge.

What has that to do with string arrays? Well, assignment to a string array is Procrustean: a string will be either padded out with spaces to fill the array “shelf,” or truncated to fit in. If we dimension a string array

DIM A$(3,6 )

and put the strings string, array, and storage on the three shelves, they would be stored as shown in Figure 2: string fits perfectly, array gets a space added to it, and storage has its last letter removed. Listing 4 demonstrates what is illustrated in this figure. It will load the three words into an array and then print out the array contents. A period is added to the printout of each stored string so you can see exactly where it ends.

So What?

Why is it important that you take this Procrustean assignment into consideration? There are a number of reasons. Dimensioning an array larger than you need uses up memory space. Saving room for a dozen 30-character strings is a waste if you are going to store only five-letter words. More importantly, (yes, there are more important things than saving space), if you are going to be checking an INPUT against the contents of a string array cell, you had better be aware of just what is stored in that cell. Run the program in Listing 5 and type in the words as you are instructed.

Figure 2

STRING
ARRAY
STORAG

Listing 4

 5 REM "STRING 1"
10 DIM A$(3,6)
15 LET A$(1)="STRING"
20 LET A$(2)="ARRAY"
25 LET A$(3)="STORAGE"
30 FOR N=1 TO 3
35 PRINT A$(N);"."
40 NEXT N

Listing 5

 5 REM "STRING 2"
10 DIM A$(2,5)
15 LET A$(1)="SHORT"
20 LET A$(2)="LONG"
25 FOR N=1 TO 2
30 PRINT "TYPE IN ";A$(N)
35 INPUT B$
40 IF B$=A$(N) THEN PRINT "RIGHT"
45 IF B$<>A$(N) THEN PRINT "WRONG"
50 NEXT N

When you type “SHORT” the computer will tell you that you are right, but, when you enter “LONG”, you will be wrong.

Since the array was dimensioned to hold strings of five characters, it padded out “LONG” with an extra space at the end. If you type in LONG with a space after it, the computer will consider it a correct answer.

This aspect of Procrustean assignment can wreak havoc in a question/answer game if you do not allow for it. By dimensioning an array of one element to hold the answer (I told you there would be a use for it), the answer will be padded out to match the answer in the array. Add/change

7 DIM N$(5)
35 INPUT N$

and run the program again.

Space Savers

If you are not sure just what dimensions to use in a program, try letting the user enter the figures that will be needed. For instance, at the start of an alphabet sort routine, you might use:

10 PRINT "HOW MANY WORDS?"
20 INPUT N
30 PRINT "LONGEST WORD?"
40 INPUT W$
50 DIM AS (N, LEN W$)

In this way, the array is kept to the exact number of elements needed, and the space in each cell is only as large as is necessary to store the longest word.

Another Application

Applications for string arrays are similar to those for numeric arrays in that they lend themselves to certain manipulations not possible with regular string variables. For instance, alphabetizing routines compare each string in an array with the others and rearrange their order until they have been sorted alphabetically; many word processing programs also use string arrays.

Another application that takes advantage of the Procrustean feature of ZX/TS string arrays is one that can save your display. If you have a game that includes a scoreboard, you may have room for only eight letters of the player’s name. Asking a player to type in only eight letters is asking for trouble, since many people take perverse pleasure in not following directions. You can foil that person in one of two ways: check the length of the INPUT string and loop back if it is more than eight letters, or simply dimension of single-element string array to store the player’s name. When it is printed out, only the first eight letters will be there.

Multi-Dimensional String Arrays

Setting up string arrays of more than one dimension is the same as setting up a multi-dimensional numeric array, except for the number that denotes the length of the strings. N$(3,4,5) dimensions a two-dimensional string array-three walls of four shelves with five spaces on each.

Bits and Pieces

Sinclair Basic has string-slicing functions that, while slightly non-standard, are easy to use, and they apply to strings inside arrays as well as to simple strings.

To pick a character out of an arrayed string, use A$ (3,4) where 3 is the array element and 4 is the fourth character of the string stored there.

A$ (3,2 TO)
A$ (3, TO 5)

will give everything from the second character to the end of the string, and the first five characters of the string respectively.

These slicers can also be written as:

A$ (3)(4)
A$ (3)(2 TO)
A$ (3) (TO 5)

What’s in a Name?

The same letter can be used to name both a number and a numeric array in the same program; if you use a string variable name for a string array, it cannot be used for a simple string variable. You can use the same letter for up to three things in a program: a numeric variable, a numeric array, and a string variable (simple or array).

Onward…

Now that you know all about arrays, you should be ready to write such programs as word processors… mailing lists … spreadsheets… household budgets…

Products

 

Downloadable Media

 

Image Gallery

Note: Type-in program listings on this website use ZMAKEBAS notation for graphics characters.

Scroll to Top