Sunteți pe pagina 1din 3

Arrays

An array is a data structure used to hold a set of related data.


For example: A collection of temperature readings, a set of weight readings, the
days of the week.
An array is a consecutive group of memory locations that all have the same
variable name and contain data of the same data type.
Arrays have upper and lower bounds and the elements have to lie within those
bounds.
To declare an array give array name, the lower and upper bound for index
and the data type.
Dim a(1 to 5) as Integer

'Declare an array called a to hold 5 integers

Each element in the array is referenced using the array name and an index.
Value in array element

Array a

Array element at index 3

a[1]
a[2]
a[3]
a[4]
a[5]

11
12
4
16
3

First value is in a(1)

Element value
Last value is in a(5)

In code, to access each element of the array, that is, to access each value in the array, use a
For loop. Use the loop variable as the index value in the array.
For i = 1 to 5
lstOutput.additem ( a(i) )
next

2 D arrays
Arrays can have multiple dimensions.
You can use a two-dimensional array to represent a matrix or a table. For example, the
following table that describes the distances between the cities can be represented using a twodimensional array.

Dim distance( 1 to 7, 1 to 7) as Integer


Msgbox( distance( 2 ,3) ) displays 214
A common use of multidimensional arrays is to represent tables of values consisting of
information arranged in rows and columns.
To identify a particular table element, we must specify two indexes: The first (by convention)
identifies the element's row and the second (by convention) identifies the element's column.
matrix( row, col )
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays.

Use a nested FOR loop to iterate over a 2D array.


Dim matrix( 1 to rows, 1 to cols) 'matrix is a 2d array
for i = 1 to rows
for j = 1 to cols
Process matrix( i,j)
next j
next i
To access each element in the array, use two indices, the first for row number and the second
for the column number.
2

matrix( i, j)

row

col

In a nested loop, The inner loop executes to completion on each


iteration of outer loop.
For example:
' a is a 2D array with 4 rows and 3 columns

Dim a(1 to 4, 1 to 3) as integer

' Assume that array a has been initialised with a set of values for each element in the array.
for i = 1 to 4 ' # of rows
for j = 1 to 3 ' # of columns
lstOutput.additem( a(i,j) )

Inner loop

next j
next i
a(3,2)

Column

1
Row

1
2
3
4

a(i,j)

1
2
3
1
2
3
1
2
3
1
2
3

a(1,1)
a(1,2)
a(1,3)
a(2,1)
a(2,2)
a(2,3)
a(3,1)
a(3,2)
a(3,3)
a(4,1)
a(4,2)
a(4,3)

Iteration
of outer loop

S-ar putea să vă placă și