Array Index
- Source: https://www.freebasic.net/wiki/wikka.php?wakka=ProPgArrayIndex
- Last revised: 2019-10-03
An array index is the number used to access an Array of Variables created using the Dim command.
Description
The following examples illustrate the use of array elements.
If we have an array myArray with elements of 1 to 10, filled with random data:
Index Data
1 5
2 2
3 6
4 5
5 9
6 1
7 0
8 4
9 5
10 7One can access each piece of data separately by pointing to the Index of the array element:
start GeSHi
Print myArray(5)end GeSHi
Printing the data contained in the fifth element of myArray results in an output of:
9To change the contents of an array, use it like any other Variable:
start GeSHi
myArray(3) = 0end GeSHi
To print the contents of myArray(3), use the command:
start GeSHi
Print myArray(3)end GeSHi
Which results in an output of:
0Array elements can be indexed using another Variable. In this example we set all elements in our array to zero:
start GeSHi
Dim a As Integer
For a = 1 To 10
myArray(a) = 0
Next aend GeSHi
To change a random array element to a random value:
start GeSHi
Dim Index As Integer
Dim Value As Integer
index = Int(Rnd(1) * 10) + 1 'This line will simply return a random value between 1 and 10
Value = Int(Rnd(1) * 10) + 1 'This line will do the same
myArray(index) = Valueend GeSHi
Examples
start GeSHi
Declare Sub PrintArray()
Dim Numbers(1 To 10) As Integer
Dim Shared OtherNumbers(1 To 10) As Integer
Dim a As Integer
Numbers(1) = 1
Numbers(2) = 2
OtherNumbers(1) = 3
OtherNumbers(2) = 4
PrintArray ()
For a = 1 To 10
Print Numbers(a)
Next a
Print OtherNumbers(1)
Print OtherNumbers(2)
Print OtherNumbers(3)
Print OtherNumbers(4)
Print OtherNumbers(5)
Print OtherNumbers(6)
Print OtherNumbers(7)
Print OtherNumbers(8)
Print OtherNumbers(9)
Print OtherNumbers(10)
Sub PrintArray ()
Dim a As Integer
For a = 1 To 10
Print otherNumbers(a)
Next a
End Subend GeSHi
See also
- Arrays Overview
DimFunctionSub- Variables
- Variable Scope
Standard Data Type Limits
Back to DocToc