To access a particular element in an array you use square brackets again, this time specifying the index (or position) of the element you want.
Indices start at zero for the first element of the array, one for the second element and, in general, (n-1) for the
DEF a:ARRAY PROC main() DEF i FOR i:=0 TO 9 a[i]:=i*i ENDFOR WriteF('The 7th element of the array a is \d\n', a) a[a]:=10 WriteF('The array is now:\n') FOR i:=0 TO 9 WriteF(' a[\d] = \d\n', i, a[i]) ENDFOR ENDPROC
This should all seem very straight-forward although one of the lines looks a bit complicated.
Try to work out what happens to the array after the assignment immediately following the first
In this assignment the index comes from a value stored in the array itself!
Be careful when doing complicated things like this, though: make sure you don't try to read data from or write data to elements beyond the end of the array.
In our example there are only ten elements in the array
a, so it wouldn't be sensible to talk about the eleventh element.
The program could have checked that the value stored at
a was a number between zero and nine before trying to access that array element, but it wasn't necessary in this case.
Here's the output this example should generate:
The 7th element of the array a is 36 The array is now: a = 0 a = 1 a = 4 a = 9 a = 10 a = 25 a = 36 a = 49 a = 64 a = 81
If you do try to write to a non-existent array element strange things can happen. This may be practically unnoticeable (like corrupting some other data), but if you're really unlucky you might crash your computer. The moral is: stay within the bounds of the array.
A short-hand for the first element of an array (i.e., the one with an index of zero) is to omit the index and write only the square brackets.
a is the same as
Go to the Next or Previous section, the Detailed Contents, or the Amiga E Encyclopedia.