10 FOR I=1 TO 5
20 FOR J=1 TO 3
30 PRINT I,J
40 NEXT I
50 NEXT J
It does not work because when the "NEXT I" is encountered, all knowledge of the J-loop is lost.
This happens because the J-loop is "inside" the I-loop.
209 MATRIX OPERATIONS
It is often convenient to be able to select any element in a table of numbers. BASIC allows this to
be done through the use of matrices.
A matrix is a table of numbers. The name of this table (the matrix name) is any legal variable name,
"A" for example. The matrix name "A" is distinct and separate from the simple variable "A," and
you could use both in the same program.
To select an element of the table, we subscript "A": that is, to select the I'th element, we enclose I
in parentheses "(I)" and then follow "A" by this subscript. Therefore, "A(I)" is the I'th element in
the matrix "A."
"A(1)" is only one element of matrix A, and BASIC must be told how much space so allocate for
the entire matrix. This is done with a "DIM" statement, using the format "DIM A(15)." In this
case, we have reserved space for the matrix index "I" to go from 0 to 15. Matrix subscripts always
start as 0; therefore, in the above example, we have allowed for 16 numbers in matrix A.
If "A(1)" is used in a program before is has been dimensioned, BASIC reserves space for 11 elements
(0 through 10).
A SORT PROGRAM
As an example of how matrices are used, try the following program so sort a list of 8 numbers, in
which you pick the numbers to be sorted:
10 DIM A(8) 110 A(I)=A(I+1)
20 FOR I=1 TO 8 120 A(I+1)=T
30 INPUT A(I) 130 F=1
50 NEXT I 140 NEXT I
70 F=0 150 IF F=1 THEN 70
80 FOR I=1 TO 7 160 FOR I=1 TO 8
90 IF A(I)<=A(I+1) THEN 140 170 PRINT A(I)
100 T=A(I) 180 NEXT I
When line 10 is executed, BASIC sets aside space for 9 numeric values, A(0) through A(8).
Lines 20 through 50 get the unsorted list from the user. The sorting itself is done by going through
the list of numbers and switching any two that are not in order. "F" is used to indicate if any
switches were made; if any were made, line 150 tells BASIC to go back and check some more.
If we did not switch any numbers, or after they are all in order, lines 160 through 180 will print
out the sorted list. Note that a subscript can be any expression.
210 SUBROUTINES
If you have a program that performs the same action in several different places, you could duplicate
the same statements for the action in each place within the program.
The "GOSUB" and "RETURN" statements can be used to avoid this duplication. When a "GOSUB"
is encountered, BASIC branches to the line whose number follows the "GOSUB." However, BASIC
remembers where it was in the program before it branches. When the "RETURN" statement is
encountered, BASIC goes back to the first statement following the last "GOSUB" that was
executed. Observe the following program:
10 PRINT "WHAT IS THE NUMBER";
30 GOSUB 100
40 T=N
50 PRINT "SECOND NUMBER";
70 GOSUB 100
80 PRINT "THE SUM IS"; T+N
90 STOP