Skip to content

Array Index


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             7

One can access each piece of data separately by pointing to the Index of the array element:

start GeSHi

vb
    Print myArray(5)

end GeSHi

Printing the data contained in the fifth element of myArray results in an output of:

9

To change the contents of an array, use it like any other Variable:

start GeSHi

    myArray(3) = 0

end GeSHi

To print the contents of myArray(3), use the command:

start GeSHi

vb
    Print myArray(3)

end GeSHi

Which results in an output of:

0

Array elements can be indexed using another Variable. In this example we set all elements in our array to zero:

start GeSHi

vb
    Dim a As Integer
    For a = 1 To 10
      myArray(a) = 0
    Next a

end GeSHi

To change a random array element to a random value:

start GeSHi

vb
    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) = Value

end GeSHi

Examples

start GeSHi

vb
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 Sub

end GeSHi

See also

Back to DocToc

Translated from FreeBASIC official docs. Contact us for removal if infringed.
FreeBASIC is an open-source project, not affiliated with Microsoft