Get up to 80 % extra points for free! More info:

Lesson 11 - Multidimensional arrays in VB.NET

In the previous exercise, Solved tasks for Visual Basic .NET lesson 10, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on multidimensional arrays in VB.NET instead of a thorough-full lesson? Here it is:

Shortened initialization of a 2D array:

Dim cinema(,) As Integer = New Integer(,) {
    { 0, 0, 0, 0, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 1, 1, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 0, 0, 1 }
}

Writing 1 at the position (1, 0):

cinema(1, 0) = 1

Reading the value (now 1) at the position (1, 0):

Console.WriteLine(cinema(1, 0))

Printing the whole 2D array:

For j As Integer = 0 To cinema.GetLength(0) - 1
    For i As Integer = 0 To cinema.GetLength(1) - 1
        Console.Write(cinema(j, i))
    Next
    Console.WriteLine()
Next

Declaring an empty 2D array of a given size:

Dim cinema(4, 4) As Integer

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Visual Basic .NET lesson 10, we learned how to use the Split() and Join() String methods. Today's tutorial is basically a bonus when it comes to VB.NET basic constructs. We'll discuss what we call multidimensional arrays. Essentially, you could skip directly to the object-oriented programming course; however, I highly recommend that you finish this course first, so you could understand the remaining techniques. After all, this is still just the basics.

We've already worked with a one-dimensional array which we can imagine as a row of boxes in computer memory.

Array structure in Visual Basic .NET - Visual Basic (VB.NET) Basic Constructs

(An array of eight numbers can be seen in the image)

Although it's not too common, you may sometimes encounter multidimensional arrays. Especially, when it comes to game applications.

Two-dimensional array

A good representation of a 2-dimensional array is a grid because technically, it is one. A practical application for 2-dimensional arrays would be to use them to store the available seats in a cinema. Here's a visual representation of what I'm referring to:

The 2d array structure in Visual Basic .NET - Visual Basic (VB.NET) Basic Constructs

(We can see the available seats of a cinema in the picture )

Of course, the cinema would be bigger in real life, but this array is just fine as an example. 0 means the seat is available, 1 stands for one that isn't. Later, we could also add 2 for reserved seats and so on. It would be more appropriate to create our own data type (called enumerable) for these states, but we'll get into that later. For now, we'll work with numbers.

In VB.NET, we declare a 2D array like this:

Dim cinema(4, 4) As Integer

The first number indicates the number of columns, the second is the number of rows, we could treat it the other way around as well, for example, matrices in mathematics have the number of rows come first.

All numeric arrays in VB.NET are automatically initialized with zeros if we specify their length, guaranteed. We've just created a table full of zeros.

Filling the data

Let's fill the cinema room with 1s now as you can see in the picture above. Since we'll be lazy as good programmers should be, we'll use For loops to create a row of 1s :) To access an item of a 2D array we have to enter two coordinates.

cinema(2, 2) = 1 ' center
For i As Integer = 1 To 3 ' fourth row
    cinema(i, 3) = 1
Next
For i As Integer = 0 To 4 ' the last row
    cinema(i, 4) = 1
Next

The output

We'll print the array using a loop as we did before. We'll need 2 loops for the 2d array, the first one will iterate over columns and the second one over rows). As proper programmers, won't specify the number of rows and columns directly into the loop because it may change in the future. Visual Basic .NET provides the 2D array Length property as it was with the 1D array, but it returns the total number of items in the array, so in our case 25. We'll use the GetLength() method which accepts a dimension, 0 for columns and 1 for rows, as a parameter and returns the number of items in this dimension. The first dimension is the number of columns, the second is the number of rows.

We'll nest the loops in order so the outer loop would iterate over the rows and the inner one over the columns of the current row. After printing a row, we must break a line. Both loops must have a different control variable:

For j As Integer = 0 To cinema.GetLength(1) - 1
    For i As Integer = 0 To cinema.GetLength(0) - 1
        Console.Write(cinema(i, j))
    Next
    Console.WriteLine()
Next

The result:

Console application
00000
00000
00100
01110
11111

N-dimensional arrays

Sometimes, it may be useful to create an array of even more dimensions. We can all at least imagine a 3D array. Adding on the cinema analogy, we'll say ours has multiple floors, or generally more rooms. The visualization could then look like this:

The 3D array structure in Visual Basic .NET - Visual Basic (VB.NET) Basic Constructs

We can create a 3D array the same way we created the 2D array:

Dim cinemas(4, 4, 2) As Integer

The code above creates the 3D array you saw in the picture. We can access it through the indexer, parentheses brackets, as before, but now we have to enter 3 coordinates.

cinemas(3, 2, 1) = 1 ' the second-floor cinema, the third row, the fourth seat

If we pass 2 as the parameter of the GetLength() method, we'll get the number of "floors".

An array of arrays

Many programming languages don't support multi-dimensional arrays, VB.NET is an exception. Technically, we could still create multi-dimensional arrays in the one's that don't support them since all a 2D array is nothing more than an array of arrays. We can imagine the situation as creating an array of five items (1st row) and each item of the row would also contain an array representing a column.

Its declaration would look something like this:

Dim cinema()() As Integer = New Integer(4)() {}

An advantage to declaring 2D arrays this way is that we can store as large of an array as we want in each row/column. In some cases, we don't even have to "waste" memory for the whole table and we can create a jagged array.

Jagged arrays of arrays in Visual Basic .NET - Visual Basic (VB.NET) Basic Constructs

The disadvantage of this approach is that we need to initialize the array ourselves. The first row of five cells exists, but we'd have to insert the individual columns into it ourselves (we'll insert all the columns with 5 items for now):

For i As Integer = 0 To cinema.Length - 1
        cinema(i) = New Integer(4) {}
Next

VB.NET also doesn't make it any easier to retrieve the number of rows and columns of these arrays. We have to determine the array size like this:

Dim cols As Integer = cinema.Length
Dim rows As Integer = 0
If cols <> 0 Then
        rows = cinema(0).Length
End If

Notice how it's necessary to retrieve the number of columns first. If it is 0, we can't access the first column to determine its length (number of rows in the column).

The values of the array can be accessed using 2 indexers:

cinema(4)(2) = 1 ' we occupy a seat at the 5th column and the 3rd row

(Using a single indexer would return the entire column at the given index)

Shortened initialization of multidimensional arrays

I'll also mention that even multidimensional arrays can be initialized with values directly (the code creates and initializes a crowded cinema room as you can see in the picture):

Dim cinema(,) As Integer = New Integer(,) {
    { 0, 0, 0, 0, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 1, 1, 1 },
    { 0, 0, 0, 1, 1 },
    { 0, 0, 0, 0, 1 }
}

(The array in this code is rotated since we define columns which are declared as rows here).

We can use a similar initialization even for jagged arrays (the code below creates the jagged array from the picture):

Dim jaggedArray()() As Integer = New Integer(4)() {
    New Integer() {15, 2, 8, 5, 3},
    New Integer() {3, 3, 7},
    New Integer() {9, 1, 16, 13},
    New Integer() {},
    New Integer() {5}
}

In conclusion, I would like to add that some people who can't use objects properly, use 2D arrays to store multiple sets of data of a single entity. e.g. imagine that we want to store the length, width, and height of five cell phones. Although you may think that a 3D array would be best for the situation, it can be pulled off with an ordinary 1D array (specifically a list of objects of the Phone type). We'll go over all of that in the object-oriented programming course. If you feel like you could still use some more practice, go ahead and give the exercises for this lesson a shot.

In the next lesson, Mathematical functions in VB.NET - The Math library, we'll look at basic math functions and finish the basic constructs course.


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 42x (54.24 kB)
Application includes source codes in language VB.NET

 

Previous article
Solved tasks for Visual Basic .NET lesson 10
All articles in this section
Visual Basic (VB.NET) Basic Constructs
Skip article
(not recommended)
Mathematical functions in VB.NET - The Math library
Article has been written for you by Michal Zurek
Avatar
User rating:
1 votes
Activities