|
B.5 Arrays
|
Sheerpower supports arrays of reals, strings, and booleans. By default,
Sheerpower arrays are one-origin. This means that the first element of an
array is element number one. This can be overridden by the
option base
0 statement.
The
dim statement is used to define an array:
dim ages(5) // five real elements: 1, 2, 3, 4, and 5
dim names$(5) // five string elements.
dim degrees(-50 to 100) // 151 elements from -50 to 100
dim dice(5) // five dice
for idx = 1 to 5
dice(idx) = rnd(6) // assign each die a random number between 1 and 6
print 'dice#'; idx;' value '; dice(idx)
next idx
Most arrays are single dimensioned. However, multi-dimensional arrays are
supported. For example
dim weekly_hours(7,24) which would represent 7
days a week, 24 hours a day.
To increase the size of an existing array, let's say from 5 to 10 elements,
use the
redim statement. And in the example below, let's also use a
variable
max_ages to both determine the initial and new size of the
array:
max_ages = 5
dim ages(max_ages) // five real elements: 1, 2, 3, 4, and 5
max_ages = 10
redim ages(max_ages) // Now we have 10 elements
If we don't know how large of an array we need, the syntax for creating a dynamically
expanding array is:
dim cash(0) // this is how we create a dynamically expanding array
cash(0) = 10.99
cash(0) = 20.50
print 'Cash elements:';size(cash)
print
Note: Although arrays are pretty easy to use, nowadays using
cluster
arrays is preferred since they are just as fast and easy to use and much more
versatile. See
Cluster arrays for details.