3.2.6 - Two-dimensional arrays (VB.NET)

3.2.6 - Two-dimensional arrays (VB.NET)

Use row and column indexes to represent and process a grid in VB.NET. Native answers are written without Run; the optional Python demonstration uses a list of rows.

Rows, columns and indexes

A two-dimensional array locates each element using two indexes rather than one.

Two-dimensional array

An indexed collection arranged in two dimensions, commonly interpreted as rows and columns.

A classroom seating grid or a table of daily readings needs two coordinates. Decide consistently that the first index means row and the second means column:

VB.NET
Dim readings(,) As Integer = {{2, 4, 6}, {1, 3, 5}}
Row indexColumn 0Column 1Column 2
0246
1135

readings(0,2) is 6; readings(1,0) is 1. Reversing the indexes changes the location, and readings(2,0) is outside this two-row array. To replace the 3, use readings(1,1) = 9.

Dim seats(1,2) As Boolean creates two rows and three columns, with six initially false elements. Each declared number is the highest allowed index in that dimension. GetLength(0) returns the first dimension's length, 2; GetLength(1) returns the second dimension's length, 3. Length is the total element count, 6, so it is unsuitable as a row bound.

Only one- and two-dimensional arrays are required here. Use a one-dimensional array when a single position identifies the data; use two dimensions when two coordinates naturally identify it. Supplied AQA pseudocode may show array[row][column]; native rectangular VB.NET syntax uses array(row,column).

Traversing a two-dimensional array

Nested iteration can visit every column of each row without missing or duplicating a grid cell.

VB.NET
Dim readings(,) As Integer = {{2, 4, 6}, {1, 3, 5}}
Dim total As Integer = 0
For row As Integer = 0 To readings.GetLength(0) - 1
    For column As Integer = 0 To readings.GetLength(1) - 1
        total = total + readings(row, column)
    Next
Next
Console.WriteLine(total)

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account