VB6 Tutorial 51: Multi-dimensional arrays

By | 2018-05-24

An array can be multi-dimensional that means, it can have more than one dimension. A list of data is represented in a one-dimensional array where a multi-dimensional array represents a table of data.

An array can be two dimensional, three dimensional and so on. We generally don’t need an array of more than two dimensions, it is enough to use one and two dimensional arrays. You can use a higher dimensional array when the program is too complex. A two dimensional array takes the row-column form.

Declaration

Dim value(5, 5) As Integer      'two dimensional

… or …

Dim value(1 to 5, 1 to 5) As Double
Dim number(6, 9, 8) As Integer  'three dimensinal

Initialization

To initialize the array elements, you first need to recognize the array elements. For example, the array ‘value(2, 2)’ has 9 elements. They are value(0,0), value(0,1), value(0,2), value(1,0), value(1,1), value(1,2), value(2,0), value(2,1), value(2,2). For the initialization, you may wish to use For Loop or initialize each element like variables. Using For Loop is a better choice as it reduces the number of lines of code. But sometimes, separately initializing each element like a variable is much more convenient. And it also depends on the type of program you are writing .

Addition of 2D matrices

Example

Private Sub cmdSum_Click()
    Dim matrix1(1, 1) As Integer, matrix2(1, 1) As Integer
    Dim sum(1, 1) As Integer

    'initializiation of matrix1
    matrix1(0, 0) = Val(Text1.Text)
    matrix1(0, 1) = Val(Text2.Text)
    matrix1(1, 0) = Val(Text3.Text)
    matrix1(1, 1) = Val(Text4.Text)

    'initializiation of matrix2
    matrix2(0, 0) = Val(Text5.Text)
    matrix2(0, 1) = Val(Text6.Text)
    matrix2(1, 0) = Val(Text7.Text)
    matrix2(1, 1) = Val(Text8.Text)

    'Summation of two matrices
    For i = 0 To 1
        For j = 0 To 1
            sum(i, j) = matrix1(i, j) + matrix2(i, j)
        Next j
    Next i

    'Displaying the result
    Print "The resultant matrix"
    For i = 0 To 1
        For j = 0 To 1
            Print sum(i, j);
       
        Next j
        Print ""
    Next i
End Sub

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.