Indexed Arrays

Indexed arrays are arrays that store a set of values in a sequence of positions which are specified by an index, which is an integer number. PBL uses zero-based arrays, meaning that the index of the first position of the array is zero rather than one. Zero-based arrays are used in Java and Visual Basic as well.

Declaration

Indexed arrays are declared using square brackets:
ages as Int[]

The code above declares an indexed array named ages, which is of type Int.

Initializing an array

You can use in-line arrays for initialization, specifying the values separated by commas:
ages as Int[]
ages = [23, 42, 29]

The code above initializes the empty array ages, with the integer values 23, 42, and 29.

You can add array elements at the end of the array, but must not skip any index values. That is, if the array has six elements, with indexes ranging from 0 to 5, the next assigned value must be with index 6:
ages as Int[]
codes = [505, 607, 404, 405, 307, 806]

codes[6] = 306
If you skip an index value, an Index out of bounds error is thrown.

Accessing elements

The elements of an indexed array can be accessed by the index:
ages as Int[]
ages = [23, 42, 29]

display ages[0]

If you pass an index which is higher than the last available index (in the example, the last index is 2), an Array index out of bounds error results.

Expressions are allowed in the index, so long as they result in an integer within the array bounds:
codes as Int[]
codes = [505, 607, 404, 405, 307, 806]
I = 2

display codes[1 + 2]
display codes[i]
display codes[i * 2]

Changing Array Values

You can change the value of any element in the array by specifying its index. This example uses a string array:
Names as String[]
names = ["Bill", "Ed", "Alfred"]

names[1] = "Edward"
display names