Creating Arrays

Array variables must be created before they are used.  This creation occurs when an array element is given a value via an assignment or an input.  The array is created up to the highest indexed element given a value.  This is often done in a counting loop from one to some upper limit, so the array initially has one element, then two, then three, and so on as the loop is repeated and the index increases.   

 

A run-time error will occur if the program attempts to access an array element whose index is higher than the index of any elements previously assigned a value.

 

However, the array elements may be assigned values in any order, with some indexes left out.  In this case, the highest index used still defines the upper limit of the array's size, but the entries in the array not assigned a value by the program will default to a value of 0.  For example, an assignment of the form:

 

values[7] <- 3

 

results in a values  array that looks like this:  

 

1

2

3

4

5

6

7

0

0

0

0

0

0

3

 

A second assignment

 

values[9] <- 6

 

expands the array and makes it look like this:

 

1

2

3

4

5

6

7

8

9

0

0

0

0

0

0

3

0

6

 

 

One convenient side effect of this behavior is that the programmer can initialize an entire array to 0 with a single assignment statement.  For example, to initialize an array of 100 elements to 0, the single assignment

 

values[100] <- 0

 

can be used in place of a counting loop that contains an assignment and executes it 100 times.

 

Creating Two-Dimensional Arrays

 

When creating two-dimensional arrays, the size of the array in both dimensions is determined by the highest index assigned a value in that dimension.  Again, a single assignment like

 

numbers[3,4] <- 13

 

results in a two-dimensional numbers array that looks like this:

 

 

1

2

3

4

1

0

0

0

0

2

0

0

0

0

3

0

0

0

13