4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (VB.NET)

4.2.1.1–4.2.1.2 - Data structures and multidimensional arrays (VB.NET)

Choose structures that organise related data, represent vectors and matrices with arrays, and write indexed VB.NET solutions. This route uses written code with no Run: incomplete: runnable support pending.

Choosing a data structure

A program's data structure determines how it groups, finds and changes its data.

Data structure

An organised collection of data together with a way to access and manipulate its elements.

A register might store one record per student; a seating plan groups seats by row and column; a print queue preserves arrival order. Choosing a structure starts with the operations the solution needs. If a weather station records one temperature every hour, an array permits direct access by hour and a loop can process the complete day. Separate variables such as hour0, hour1 and hour2 make the same operation awkward to repeat.

An array contains elements of one declared type, accessed by integer indices. Position is meaningful: hour 3 remains at index 3 even if its value changes. An array of records can hold several fields per element while retaining a single record type. A dictionary, by contrast, accesses a value through a key such as a station name. Neither choice is universally best; the needed relationships and operations justify it.

Vectors and matrices as arrays

The number of indices needed to locate an element is the array's number of dimensions.

VB.NET
Dim temperatures() As Double = {18.5, 20.0, 19.5}
Dim bookings(11, 19) As Boolean
bookings(2, 5) = True

VB.NET array bounds are inclusive: Dim bookings(11, 19) creates 12 rows and 20 columns, indexed from 0. It does not create an 11-by-19 array. In this example the convention is row first, column second; a program must use that convention consistently.

A one-dimensional numerical array naturally represents a vector, an ordered list of components. A two-dimensional numerical array represents a matrix, whose entries have row and column positions. An element of an nn-dimensional array is located by an ordered tuple of nn integers. In a three-dimensional temperature store, (day, station, hour) selects one reading; reversing these indices means a different location.

Length counts every element of the array. GetLength(0) counts rows, GetLength(1) counts columns, and GetUpperBound(0) gives the greatest valid row index. For bookings, these are 240, 12, 20 and 11 respectively. A rectangular array has the same number of columns in every row; an array of arrays is a different representation and is not needed for this seating plan.

Continue this lesson.

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

Create free account