Tuesday, May 6, 2008

2-Dimensional Arrays

We can declare 2-Dimensional arrays by using the following statement:

Dim arrayName(r,c) As Type

Where arrayName is the name of the array you have created and Type is the array's type. The subscripts r and c represent the Row and Column of the array.

So we could declare an array as type double to hold students' grades:

Dim grades(3,3) As Double
'Four students with four grades


This creates a 4x4 matrix with rows and columns starting at 0 and ending at 3:

0 1 2 3
+---+---+---+---+
0 | | | | |
+---+---+---+---+
1 | | | | |
+---+---+---+---+
2 | | | | |
+---+---+---+---+
3 | | | | |
+---+---+---+---+

We can set any cell in the array by issuing a call such as:

grades(1,1) = 90
grades(3,0) = 99
grades(1,0) = 100

With the above code our resulting matrix will look like:

0 1 2 3
+---+---+---+---+
0 | | | | |
+---+---+---+---+
1 |100| 90| | |
+---+---+---+---+
2 | | | | |
+---+---+---+---+
3 |99 | | | |
+---+---+---+---+

If we wanted to set all the cells to a particular value, such as 0 for example, we would have to use a nested loop:

For i As Integer=0 To 3
For j As Integer=0 To 3
grades(i,j) = 0
Next
Next


We can also declare the 2-dimensional array without a size as we can with regular arrays:

Dim arrayName(,) As Type
Dim array2(,) As Type = {{ROW0},{ROW1},{ROW2},...,{ROWm}}

ReDim arrayName(r,s)
ReDim Preserve arrayName(r,s)

Real Examples:

Dim grades(,) = {{99,50,80},{100,80,70},{90,88,90}}
ReDim Preserve grades(3,4)

GetUpperBound

There are two different GetUpperBound calls for 2-dimensional arrays:

arrayName.GetUpperBound(0)
arrayName.GetUpperBound(1)

The first call gives you the upperbound on the number of rows, while the second one gives you the upperbound on the number of columns.

No comments: