An array is used to store many similar types of data using a single variable name.
The array should be pictured as a container with many compartments.
The container has one name, but each of the compartments is numbered.
In order to refer to the value stored in a single compartment, we must use the container name
( the variable ) along with the compartment number ( called the index or subscript )
i.e. An array called numbers could be visualized in memory as follows:
numbers
|
subscript/index ->
element ->
numbers(4) would refer to the value in position 4 of the array called numbers ( it’s –3 here ) numbers(4) is known as a subscripted variable in this situation
The subscripts (indices) for an array are numbered starting at zero, unless you specify otherwise
Arrays are dimensioned by:
i) using the highest index needed for the array or
ii) giving the range of the indices (lowest to highest).
i.e.
dim numbers(10) as integer – would set aside space for 11 elements in an array called ‘numbers’ (positions 0 – 10)
dim prices(5 to 10) as single – would set aside space for 6 elements in an array called ‘prices”. Here the compartments would be numbered from 5 to 10.
Filling an array
You can enter elements one at a time by compartment number like this: num(1)=3 nam(5)=”Fred”
Or Because the name stays the same and only the index changes,
we can use a For / Next loop to enter all of the elements in an array.
i.e. for x = 1 to 10 for x = 1 to 10
input ”Enter a number”, num(x) num(x) = int(rnd* 100 ) + 1
next x next x
The 1st structure allows the user to enter 10 different values and have them stored in separate compartments numbered 1 –10, while the other uses random numbers for elements of the array.
Without an array, you can only store one value at a time under the variable num
Whenever we need to access the items in the array, we would again use a for/next loop.
i.e.
for a = 1 to 10
total = total + num(a)
print num(a);
next a
print
print “The total of all the values is “; total