Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Arrays

A fixed-size array holds a set number of values of one type. Its bounds are written in the declaration, and a brace list can fill it there too.

'' A fixed-size array: its bounds are part of the declaration.
dim as int32 primes( 0 to 4 ) = { 2, 3, 5, 7, 11 }
print "primes go from"; lbound( primes ); " to"; ubound( primes )
print "the third prime is"; primes( 2 )

'' The lower bound can be anything; "..." lets the list set the upper.
dim as ustring days( 1 to ... ) = { "Mon", "Tue", "Wed" }
print "days 1 to"; ubound( days ); ": "; days( 1 ); " "; days( 3 )

'' A single number is the upper bound, so this has 4 elements, 0 to 3.
dim as float64 readings( 3 )
readings( 3 ) = 9.5
print "readings:"; readings( 0 ); readings( 1 ); readings( 2 ); readings( 3 )

'' One set of braces per dimension.
dim as int32 grid( 1 to 2, 1 to 3 ) = { { 1, 2, 3 }, { 4, 5, 6 } }
print "grid is"; ubound( grid, 1 ); " by"; ubound( grid, 2 ); _
      ", grid( 2, 3 ) ="; grid( 2, 3 )

'' Walking an array by index.
dim as int32 total = 0
for i as int32 = lbound( primes ) to ubound( primes )
    total += primes( i )
next
print "sum of primes:"; total

Output

primes go from 0 to 4
the third prime is 5
days 1 to 3: Mon Wed
readings: 0 0 0 9.5
grid is 2 by 3, grid( 2, 3 ) = 6
sum of primes: 28

primes( 0 to 4 ) has five elements, numbered 0 to 4. An element is reached with parentheses, primes( 2 ), and lbound and ubound give the lowest and highest index, so a loop over them visits every element whatever the bounds are.

The lower bound can be any integer, days( 1 to ... ) starts at 1, and ... as the upper bound takes the size from the list. A single number in the declaration is the upper bound with 0 as the lower, so readings( 3 ) has four elements. Elements that no initialiser fills start at zero.

An array can have more than one dimension. Each dimension gets its own pair of bounds and its own level of braces, and ubound( grid, 2 ) asks about the second dimension.

Arrays that grow and shrink, passing arrays to procedures, and bounds checks are in the Arrays section.

Activities

  1. Declare dim as int32 squares( 1 to 10 ), fill it in a loop, and print the last element.
  2. Change days to hold all seven days and print the number of elements as ubound( days ) - lbound( days ) + 1.