Arrays
An array holds many values of one type under one name, and you reach each one by its index. tiko arrays carry their bounds with them, a first and a last index, rather than a length. There are two kinds:
- a fixed array, whose bounds are written in its declaration and never change;
- a dynamic array, which starts empty and is sized while the program runs.
'' An array is many values of one type under one name, reached by index.
'' A fixed array: its bounds are written in the declaration.
dim as int32 days( 1 to 12 ) = { 31, 28, 31, 30, 31, 30, _
31, 31, 30, 31, 30, 31 }
print "months"; lbound( days ); " to"; ubound( days )
print "days in June:"; days( 6 )
dim as int32 total = 0
for m as int32 = lbound( days ) to ubound( days )
total += days( m )
next
print "days in the year:"; total
'' Elements start at zero (an empty string for text) until assigned.
dim as float64 rainfall( 0 to 2 )
rainfall( 1 ) = 12.5
print "rainfall:"; rainfall( 0 ); rainfall( 1 ); rainfall( 2 )
'' A dynamic array has no size until redim gives it one.
dim as ustring names( )
print "names starts with"; ubound( names ) - lbound( names ) + 1; " elements"
redim names( 1 to 3 )
names( 1 ) = "Ada" : names( 2 ) = "Grace" : names( 3 ) = "Edsger"
print "now"; ubound( names ) - lbound( names ) + 1; ": " & names( 2 )
Output
months 1 to 12
days in June: 30
days in the year: 365
rainfall: 0 12.5 0
names starts with 0 elements
now 3: Grace
lbound( a ) and ubound( a ) are the first and last valid index. A loop
written between them works for any array, whatever its bounds, so it never
needs a count remembered somewhere else. The number of elements is
ubound( a ) - lbound( a ) + 1.
days( 1 to 12 ) is indexed by month, so days( 6 ) is June with no
arithmetic. A brace list fills the elements in index order. Elements that are
never assigned are zero, or an empty string for text; there is no such thing
as an uninitialised element.
A single number in the declaration is the upper bound, and the lower bound
is 0: dim as int32 a( 10 ) has eleven elements, 0 to 10. Write both bounds,
a( 0 to 9 ), and the declaration cannot be misread.
dim as ustring names( ), with empty parentheses, declares a dynamic array.
An empty array's ubound is below its lbound, so its count is 0 and a loop
over it runs zero times. Dynamic arrays covers redim and the
rest.
Activities
- Print every month with 31 days by its number.
- Declare
dim as int32 a( 5 )and print itslbound,uboundand count.