Home

Introduction to Arrays

 

A Series of Similar Items

 

Introduction

Imagine you want to create a program that would use a series of numbers. In math, we represent such a series as follows: X1, X2, X3, X4, X5. In computer programming, it is better to consider such a list vertically as representing items of the same category. For example, if the series were made of names, you would illustrate it as follows:

Alex
Gaston
Hermine
Jerry

In the Visual Basic programming language, so far, to use a series of items, we were declaring a variable for each item. If the list was made of numbers, we would declare variables for such numbers as follows:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number1 As Double = 12.44
        Dim number2 As Double = 525.38
        Dim number3 As Double = 6.28
        Dim number4 As Double = 2448.32
        Dim number5 As Double = 632.04

	Return 0
    End Sub

End Module

Instead of using individual variables that share the same characteristics, you can group them in an entity like a regular variable but called an array: an array is a series of items of the same kind. It could be a group of numbers, a group of cars, a group of words, etc. As long as the items are of the same type but are considered in the same group, the ensemble is called an array.

 

Practical Learning: Introducing Arrays

  1. Start Notepad
  2. In the empty file, type the following:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
    
        End Sub
    End Class
  3. To save the file, on the main menu, click File -> Save
  4. Select the VBasic folder if you had created it in the first lesson. Otherwise select a folder of your choice or a drive letter and display it in the Save In combo box
  5. Click the Create New Folder button Create New Folder again
  6. Type DeptStore1 and press Enter twice or display the new folder in the Save In combo box
  7. Save the file as Exercise.vb and click Save
  8. To test the application, open the Command Prompt and change to the folder in which you created the VBasic file
  9. Type vbc Exercise.vb and press Enter
 

Array Creation

Before creating an array, you must first decide what type its items will be made of. Is it a group of numbers, a group of chairs, a group of buttons on a remote controls? This information allows the compiler to know how much space each item of the group will require. This is because each item of the group will occupy its own memory space, just like any of the variables we have used so far.

After deciding about the type of data of the items that make up the series, you must use a common name to identify them. The name is simply the same type you would use for a variable as we have used so far. The name allows you and the compiler to identify the portion of memory where the items are located.

Thirdly, you must specify the number of items that will constitute the group. For the compiler to be able to allocate an adequate amount of space for the items of the list, once it knows how much space each item will require, it needs to know the number of items so an appropriate and large enough amount of space can be reserved. The number of items of an array is included in parentheses, as in (5). The actual number of items is 1 higher than the number you specify. Based on this, you can declare an array that contains 5 items as follows:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number(4) As Double

        Return 0
    End Sub

End Module
 

Practical Learning: Creating an Array

  1. To create an array, declare the following variable:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim deptStoreItemName(5) As String
        End Sub
    End Class
  2. Save the file
 

Introduction to the Array Class

By their concept, arrays are a concept built-in most computer languages. In the same way, arrays have always been part of the VBasic language. The .NET Framework also provides its own support of arrays. This is done through a class called Array. This implies that, to create an array, you have various options: either you can use the built-in theory of arrays introduced above or you can use the Array class.

In the above sections, we saw that, to create an array, you must specify its name and its type. 

To support the creation of an array, the Array class is equipped with the CreateInstance() method that is overloaded with various versions. One of the versions of this method uses the following syntax:

Overloads Public Shared Function CreateInstance(ByVal elementType As Type, _
                                                ByVal length As Integer) As Array

The first argument is used to specify the type of array you want to create. Since it is declared as Type, you can use the typeof operator to cast your type. The second argument specifies the number of items of the list. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)
    End Sub
End Class

This declaration creates an array of 5 strings.

 

Using Arrays

 

Initializing an Array

When creating an array, each item of the series is referred to as a member of the array. Once the array variable has been declared, each one of its members is initialized with a 0 value. Most, if not all, of the time, you will need to change the value of each member to a value of your choice. This is referred to as initializing the array. To initialize an array, you can access each one of its members and assign it a desired but appropriate value.

In math, if you create a series of values as X1, X2, X3, X4, and X5, each member of this series can be identified by its subscript number. In this case the subscripts are 1, 2, 3, 4, and 5. This subscript number is also called an index. In the case of an array also, each member can be referred to by an incremental number called an index. A VBasic array is zero-based. This means that the first member of the series has an index of 0, the second has an index of 1. In math, the series would be represented as X0, X1, X2, X3, and X4. In VBasic, the index of a member of an array is written in its own parentheses. This is the notation you would use to locate each member. One of the actions you can take would consist of assigning it a value. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number(4) As Double

        number(0) = 12.44
        number(1) = 525.38
        number(2) = 6.28
        number(3) = 2448.32
        number(4) = 632.04

	Return 0
    End Sub

End Module

In the same way, you had created an array using the CreateInstance() method of the Array class, you can access each member using its index in its parentheses to initialize it. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"
    End Sub
End Class

There is another technique you can use to initialize an array. In this case, declare the array variable without specifying the number of its members. Then, on the right side of the data type, type the assignment operator followed by the opening curly bracket "{" and ending with a closing curly bracket "}". Between the curly brackets, enter the members of the array separated by commas. Here are two examples:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number() As Double = { 12.44, 525.38, 6.28, 2448.32, 632.04 }
     Dim lstItemsNames() As String = {"Women Coat", "Men Jacket", "Teen Jeans", _
    				"Women Bathing Suit", "Children Playground Dress"}

	Return 0
    End Sub

End Module
 

Practical Learning: Initializing an Array

  1. To initialize the array, change the program as follows:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim deptStoreItemName(5) As String
    
            deptStoreItemName(0) = "Women's Khaki Pants"
            deptStoreItemName(1) = "Diagonal-stripped Dress"
            deptStoreItemName(2) = "Teen Ultimate Cargo Short"
            deptStoreItemName(3) = "Women Swirl Slingback Shoes"
            deptStoreItemName(4) = "Athletic Long Bra"
        End Sub
    End Class
  2. Save the file
 

Access to Members of an Array

Once an array has been initialized, that is, once its members hold the necessary values, you can access and use these values. The main technique used to use an array consists of accessing each member or the necessary member based on its index. Remember that an array is zero-based. You can access the first member using an index of 0. The second member has an index of 1, and so on. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"

        Console.WriteLine("Item 1: {0}", lstItemsNames(0))
        Console.WriteLine("Item 2: {0}", lstItemsNames(1))
        Console.WriteLine("Item 3: {0}", lstItemsNames(2))
        Console.WriteLine("Item 4: {0}", lstItemsNames(3))
        Console.WriteLine("Item 5: {0}", lstItemsNames(4))
        Console.WriteLine()
    End Sub
End Class

This would produce:

Item 1: Women Coat
Item 2: Men Jacket
Item 3: Teen Jeans
Item 4: Women Bathing Suit
Item 5: Children Playground Dress

To access the members of an array, you can also use the GetValue() method of the Array class. This class is equipped with a version corresponding to each version of the CreateInstance() and the SetValue() methods. For example, to access the values stored in a one-dimensional array, you can call call this version:

Overloads Public Function GetValue(ByVal index As Integer) As Object

The argument is the zero-based index of the member whose value you want to access. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"

        Console.WriteLine("Item 1: {0}", lstItemsNames.GetValue(0))
        Console.WriteLine("Item 2: {0}", lstItemsNames.GetValue(1))
        Console.WriteLine("Item 3: {0}", lstItemsNames.GetValue(2))
        Console.WriteLine("Item 4: {0}", lstItemsNames.GetValue(3))
        Console.WriteLine("Item 5: {0}", lstItemsNames.GetValue(4))
        Console.WriteLine()
    End Sub
End Class

If you pass an invalid value, the computer would throw an IndexOutOfRangeException exception.

 

Practical Learning: Accessing the Members of an Array

  1. To access the array and use its members, change the program as follows:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim deptStoreItemName(5) As String
    
            deptStoreItemName(0) = "Women's Khaki Pants"
            deptStoreItemName(1) = "Diagonal-stripped Dress"
            deptStoreItemName(2) = "Teen Ultimate Cargo Short"
            deptStoreItemName(3) = "Women Swirl Slingback Shoes"
            deptStoreItemName(4) = "Athletic Long Bra"
    
            Console.WriteLine(" - Department Store -")
            Console.WriteLine("Item 1: {0}", deptStoreItemName(0))
            Console.WriteLine("Item 2: {0}", deptStoreItemName(1))
            Console.WriteLine("Item 3: {0}", deptStoreItemName(2))
            Console.WriteLine("Item 4: {0}", deptStoreItemName(3))
            Console.WriteLine("Item 5: {0}", deptStoreItemName(4))
        End Sub
    End Class
  2. Save it and switch to the Command Prompt
  3. Type vbc Exercise.vb to compile the program
  4. After compiling, type exercise to execute
     
    - Department Store -
    Item 1: Women's Khaki Pants
    Item 2: Diagonal-stripped Dress
    Item 3: Teen Ultimate Cargo Short
    Item 4: Women Swirl Slingback Shoes
    Item 5: Athletic Long Bra
  5. Return to Notepad
 

For Each Member of a Collection

One of the most regular operations performed on a list consists of "scanning" it or "iterating through" it. Iterating through a list, such as an array, consists of accessing or examining each one of its members, for any reason. To support this operation, VBasic provides the For Each... Next conditional operator. Its formula is:

For Each Member In Collection
    Statement(s)
Next

The loop will execute the Statement(s) for each Member of the series, array or Collection. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim numbers(4) As Double

        numbers(0) = 12.44
        numbers(1) = 525.38
        numbers(2) = 6.28
        numbers(3) = 2448.32
        numbers(4) = 632.04

        Console.WriteLine("Number of members: {0}", number.Length)

        Dim n As Double
        For Each n In numbers
            Console.WriteLine("Number: {0}", n)
        Next

	Return 0
    End Sub

End Module

In the above example, we first declared a variable called n for use in the For Each... Next condition. VBasic allows you to declare such a variable while defining the condition. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number(4) As Double

        number(0) = 12.44
        number(1) = 525.38
        number(2) = 6.28
        number(3) = 2448.32
        number(4) = 632.04

        Console.WriteLine("Number of members: {0}", number.Length)

        For Each n As Double In number
            Console.WriteLine("Number: {0}", n)
        Next

	Return 0
    End Sub

End Module
 

Practical Learning: Using For Each

  1. To use the For Each... Next operator, change the program as follows:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim deptStoreItemName(7) As String
    
            deptStoreItemName(0) = "Women's Khaki Pants"
            deptStoreItemName(1) = "Diagonal-stripped Dress"
            deptStoreItemName(2) = "Teen Ultimate Cargo Short"
            deptStoreItemName(3) = "Women Swirl Slingback Shoes"
            deptStoreItemName(4) = "Athletic Long Bra"
            deptStoreItemName(5) = "Men's Trooper Cargo Short"
            deptStoreItemName(6) = "Women's Hydro Training Shoes"
            deptStoreItemName(7) = "Teen Strapless Dress"
    
            Console.WriteLine(" - Department Store -")
            Dim strItem As String
            Dim i As Int16 = 1
    
            For Each strItem In deptStoreItemName
                Console.WriteLine("Item #{0}: {1}", i, strItem)
                i += 1
            Next
        End Sub
    End Class
  2. Save it and switch to the Command Prompt
  3. Type vbc Exercise.vb to compile the program
  4. After compiling, type Exercise to execute
     
    - Department Store -
    Item #1: Women's Khaki Pants
    Item #2: Diagonal-stripped Dress
    Item #3: Teen Ultimate Cargo Short
    Item #4: Women Swirl Slingback Shoes
    Item #5: Athletic Long Bra
    Item #6: Men's Trooper Cargo Short
    Item #7: Women's Hydro Training Shoes
    Item #8: Teen Strapless Dress
  5. Return to Notepad
 

The Length of an Array

Once an array has been created, you can use it as you see fit. We saw that, when creating an array, you must specify the number of its members, and you must do this if you are not initializing the array. At some point in your program, you may want to know the number of members of an array you are using. All of the arrays used in VBasic derive from a class called Array. This class provides a property called Length. To find out how many members an array has, you can access its Length property. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim number(4) As Double

        number(0) = 12.44
        number(1) = 525.38
        number(2) = 6.28
        number(3) = 2448.32
        number(4) = 632.04

        Console.WriteLine("Number of members: {0}", number.Length)

	Return 0
    End Sub

End Module

This would produce:

Number of members: 5

If you create an array using the CreateInstance() method of the Array class using the above version, you must pass a constant integer as the second argument. Here is an example:

Private Sub Form1_Load(ByVal sender As System.Object, _
			ByVal e As System.EventArgs) _
			Handles MyBase.Load
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)
End Sub

If the array exists already, to find out the number of items it contains, you can access its Length property. Alternatively, you can call the Array.GetLength() method. Its syntax is:

Public Function GetLength(ByVal dimension As Integer) As Integer

For a single dimensional array as those declared above, you must pass the argument as 0. This method returns a 32-bit integer that represents the number of items in the array. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)
        Dim i As Integer

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"

        For i = 0 To lstItemsNames.GetLength(0) - 1
            Console.WriteLine("Item {0}: {1}", i + 1, lstItemsNames.GetValue(i))
        Next
        Console.WriteLine()
    End Sub
End Class
 

Arrays of Arrays

 

A Two-Dimension Array

The arrays we used in the above sections were made of a uniform series, where all members constituted a simple list, like a column of names on a piece of paper. Also, all items fit in one list. In some cases, you may want to divide the list in delimited sections. For example, if you create a list of names, you may want part of the list to include family members and another part of the list to include friends. Instead of creating a second list, you can add a second dimension to the list. In other words, you would like to create a list of a list, or one list inside of another list, although the list is still made of items with common characteristics.

A multi-dimensional array is a series of lists so that each list contains its own list. For example, if you create two lists of names, you would have an array of two lists. Each array or list would have its own list or array. The most basic multi-dimensional array is an array of an array, also referred to as two-dimensional.

To create a two-dimensional array, declare the array variable as we did earlier but add a comma in the parentheses. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

         Dim Number(2, 4) As Double

	Return 0
    End Sub

End Module

In this declaration, the Number variable contains three lists (remember that a VBasic array contains Dimension+1 members). Each of the three lists contains 5 items (4+1). This means that the first list contains 5 items, the second list contains 5 items also. Therefore, the whole list is made of 15  items (3*5=15). Because the variable is declared as Double, each of the 15 items is a double-precision number.

To initialize a two-dimensional array, you can access each member of the array and assign it a value. The external list is zero-based. In other words, the first list has an index of 0, the second is 1, etc. Internally, each list is zero-based and behaves exactly like a one-dimensional array. To access a member of the list, type the name of the variable followed by its parentheses. In the parentheses, type the index of the list, a comma, and the internal index of the member whose access you need. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim Number(2, 4) As Double

        Number(0, 0) = 12.44
        Number(0, 1) = 525.38
        Number(0, 2) = -6.28
        Number(0, 3) = 2448.32
        Number(0, 4) = 632.04
        Number(1, 0) = -24.02
        Number(1, 1) = 508.28
        Number(1, 2) = 683.44
        Number(1, 3) = 36.32
        Number(1, 4) = 8622.42
        Number(2, 0) = -224.54
        Number(2, 1) = 1528.38
        Number(2, 2) = 385.75
        Number(2, 3) = -46.48
        Number(2, 4) = 126.59

	Return 0
    End Sub

End Module

To iterate through a two-dimension array, you can use two For...To...Next conditions. In the first first, you can create an identifier that would be used for the external array. The second condition would be used for the internal array. Here is an example:

Imports System

Module Exercise

    Function Main() As Integer

        Dim Number(2, 4) As Double

        Number(0, 0) = 12.44
        Number(0, 1) = 525.38
        Number(0, 2) = -6.28
        Number(0, 3) = 2448.32
        Number(0, 4) = 632.04
        Number(1, 0) = -24.02
        Number(1, 1) = 508.28
        Number(1, 2) = 683.44
        Number(1, 3) = 36.32
        Number(1, 4) = 8622.42
        Number(2, 0) = -224.54
        Number(2, 1) = 1528.38
        Number(2, 2) = 385.75
        Number(2, 3) = -46.48
        Number(2, 4) = 126.59

        For i As Int16 = 0 To 2   ' As Double In Number.GetLowerBound(0)
            For j As Int16 = 0 To 4
                Console.WriteLine("Number({0}, {1}): {2}", i, j, Number(i, j))
            Next
        Next

	Return 0
    End Sub

End Module

This would produce:

Number(0, 0): 12.44
Number(0, 1): 525.38
Number(0, 2): -6.28
Number(0, 3): 2448.32
Number(0, 4): 632.04
Number(1, 0): -24.02
Number(1, 1): 508.28
Number(1, 2): 683.44
Number(1, 3): 36.32
Number(1, 4): 8622.42
Number(2, 0): -224.54
Number(2, 1): 1528.38
Number(2, 2): 385.75
Number(2, 3): -46.48
Number(2, 4): 126.59

If you want to use the Array.CreateInstance() method to create a two-dimensional array, you can use the following version of the method:

Overloads Public Shared Function CreateInstance( _
   ByVal elementType As Type, _
   ByVal length1 As Integer, _
   ByVal length2 As Integer _
) As Array

The second number of the declaration and the third argument of the current CreateInstance() method specify the number of items that each list would contain. In the above declaration, the number 3 means that each array will be made of three items.

Based on this, here is an example of declaring a two-dimensional array using the CreateInstance() method:

Private Sub Form1_Load(ByVal sender As System.Object, _
		       ByVal e As System.EventArgs) Handles MyBase.Load
        Dim lstItemsNames(2, 3) As String
        Dim lstItemsNumbers As Array = Array.CreateInstance(GetType(String), 2, 3)
End Sub

To know the total number of items that an array contains, you can access its Length property. To know the number of items that a particular list contains, call the Array.GetLength() method and pass the number corresponding to the array. To know the number of items in the first list, pass the argument as 0. To know the number of items in the second list, pass the argument as 1.

 

Practical Learning: Using a 2D Array

  1. To use a two-dimension array, change the file as follows:
     
    Imports System
    
    Public Class Exercise
        Public Shared Sub main()
            Dim ItemName(2, 4) As String
    
            ' Women
            ItemName(0, 0) = "Tweed Boxed Jacket"
            ItemName(0, 1) = "Swirl Slingback Shoes"
            ItemName(0, 2) = "Hydro Training Shoes"
            ItemName(0, 3) = "Diagonal-stripped Dress"
            ItemName(0, 4) = "Athletic Long Bra"
            ' Men
            ItemName(1, 0) = "Cotton Knit Pants"
            ItemName(1, 1) = "Trooper Cargo Short"
            ItemName(1, 2) = "Multi-Stripe Shirt"
            ItemName(1, 3) = "Three-Button Coat"
            ItemName(1, 4) = "Canvas Jacket"
            ' Teens
            ItemName(2, 0) = "Legend Fit Jeans"
            ItemName(2, 1) = "Ultimate Cargo Short"
            ItemName(2, 2) = "Strapless Dress"
            ItemName(2, 3) = "Mini Skirt"
            ItemName(2, 4) = "Stripe Halter Dress"
    
            Console.WriteLine("=-= Department Store - Inventory =-=")
    
            Console.WriteLine(" - Women Accessories -")
            For a As Byte = 0 To 4
                Console.WriteLine("Item {0}: {1}", a + 1, ItemName(0, a))
            Next
            Console.WriteLine()
    
            Console.WriteLine(" - Men Accessories -")
            For a As Byte = 0 To 4
                Console.WriteLine("Item {0}: {1}", a + 1, ItemName(1, a))
            Next
            Console.WriteLine()
    
            Console.WriteLine(" - Teens Accessories -")
            For a As Byte = 0 To 4
                Console.WriteLine("Item {0}: {1}", a + 1, ItemName(2, a))
            Next
            Console.WriteLine()
        End Sub
    End Class
  2. Save the file
  3. At the Command Prompt, compile the application and execute it. This would produce:
     
    =-= Department Store - Inventory =-=
     - Women Accessories -
    Item 1: Tweed Boxed Jacket
    Item 2: Swirl Slingback Shoes
    Item 3: Hydro Training Shoes
    Item 4: Diagonal-stripped Dress
    Item 5: Athletic Long Bra
    
     - Men Accessories -
    Item 1: Cotton Knit Pants
    Item 2: Trooper Cargo Short
    Item 3: Multi-Stripe Shirt
    Item 4: Three-Button Coat
    Item 5: Canvas Jacket
    
     - Teens Accessories -
    Item 1: Legend Fit Jeans
    Item 2: Ultimate Cargo Short
    Item 3: Strapless Dress
    Item 4: Mini Skirt
    Item 5: Stripe Halter Dress
  4. Return to Notepad
 

The Dimensions of an Array

We have seen that the square brackets are used to specify to the compiler that you are declaring an array. If you are creating a one-dimensional array, we saw that you can type a number in the square bracket. If you are creating a two-dimensional array, you type two numbers separated by a comma in the second pair of square brackets. Each number, whether it is one, two, or more is a place holder for what is referred to a dimension. In other words, a one dimensional array has a dimension of one. A two-dimensional array has a dimension of 2.

To find out the dimension of an array, the Array class, which is the parent of all arrays, provides the Rank property. Therefore, to know the dimension of an existing array, you can access its Rank.

 

Multidimensional Array Creation

Besides the single or two-dimensional, you can create multidimensional arrays by specifying the number of commas in the square brackets and specifying the numbers. To create a multidimensional array, add as many commas in the square brackets as you judge them necessary. Here is an example of a three-dimensional array initialized:

Imports System

Public Class Exercise

    Public Shared Sub main()
        Dim number(,,) As Double = {{{12.44, 525.38, -6.28, 2448.32, 632.04}, _
                                     {-378.05, 48.14, 634.18, 762.48, 83.02}, _
                     {64.92, -7.44, 86.74, -534.6, 386.73}}, _
                                     {{48.02, 120.44, 38.62, 526.82, 1704.62}, _
                     {56.85, 105.48, 363.31, 172.62, 128.48}, _
                     {906.68, 47.12, -166.07, 4444.26, 408.62}}}

        Console.WriteLine("Number of items {0}", number.Length)
        Console.WriteLine("Number of items {0}", number.Rank)
    End Sub
End Class

In this example, we are creating 2 groups of items. Each of the two groups is made of three lists. Each list contains 5 numbers. This would produce:

Number of items 30
Number of items 3

If you want to use the Array.CreateInstance() method to create a multidimensional array, you can call the following version of the method:

Overloads Public Shared Function CreateInstance( _
   ByVal elementType As Type, _
   ByVal ParamArray lengths() As Integer _
) As Array

With this version of the method, the second argument specifies the number of arrays that the variable will hold.

If you want to find out the total number of items that an array contains, access its Length property. To get the number of items that a particular list contains, you can call the Array.GetLength() method and pass the number corresponding to the array.

To know the number of lists that an array variable contains, you can access its Rank property.

 

Access to Members of a Multidimensional Array

To locate each member of a multidimensional array, type the name of the array followed by the opening parenthesis, followed by the 0-based first dimension, followed by a comma. Continue with each dimension and end with the closing parenthesis. Here is an example:

Imports System

Public Class Exercise

    Public Shared Sub main()

        Dim number(,,) As Double = {{{12.44, 525.38, -6.28, 2448.32, 632.04}, _
                                                              {-378.05, 48.14, 634.18, 762.48, 83.02}, _
                     {64.92, -7.44, 86.74, -534.6, 386.73}}, _
                                                       {{48.02, 120.44, 38.62, 526.82, 1704.62}, _
                     {56.85, 105.48, 363.31, 172.62, 128.48}, _
                     {906.68, 47.12, -166.07, 4444.26, 408.62}}}

        Console.WriteLine("Number(0)(0)(0) = {0}", number(0, 0, 0))
        Console.WriteLine("Number(0)(0)(1) = {0}", number(0, 0, 1))
        Console.WriteLine("Number(0)(0)(2) = {0}", number(0, 0, 2))
        Console.WriteLine("Number(0)(0)(3) = {0}", number(0, 0, 3))
        Console.WriteLine("Number(0)(0)(4) = {0}" & vbCrLf, number(0, 0, 4))

        Console.WriteLine("Number(0)(1)(0) = {0}", number(0, 1, 0))
        Console.WriteLine("Number(0)(1)(1) = {0}", number(0, 1, 1))
        Console.WriteLine("Number(0)(1)(2) = {0}", number(0, 1, 2))
        Console.WriteLine("Number(0)(1)(3) = {0}", number(0, 1, 3))
        Console.WriteLine("Number(0)(1)(4) = {0}" & vbCrLf, number(0, 1, 4))

        Console.WriteLine("Number(0)(2)(0) = {0}", number(0, 2, 0))
        Console.WriteLine("Number(0)(2)(1) = {0}", number(0, 2, 1))
        Console.WriteLine("Number(0)(2)(2) = {0}", number(0, 2, 2))
        Console.WriteLine("Number(0)(2)(3) = {0}", number(0, 2, 3))
        Console.WriteLine("Number(0)(2)(4) = {0}" & vbCrLf, number(0, 2, 4))

        Console.WriteLine("Number(1)(0)(0) = {0}", number(1, 0, 0))
        Console.WriteLine("Number(1)(0)(1) = {0}", number(1, 0, 1))
        Console.WriteLine("Number(1)(0)(2) = {0}", number(1, 0, 2))
        Console.WriteLine("Number(1)(0)(3) = {0}", number(1, 0, 3))
        Console.WriteLine("Number(1)(0)(4) = {0}" & vbCrLf, number(1, 0, 4))

        Console.WriteLine("Number(1)(1)(0) = {0}", number(1, 1, 0))
        Console.WriteLine("Number(1)(1)(1) = {0}", number(1, 1, 1))
        Console.WriteLine("Number(1)(1)(2) = {0}", number(1, 1, 2))
        Console.WriteLine("Number(1)(1)(3) = {0}", number(1, 1, 3))
        Console.WriteLine("Number(1)(1)(4) = {0}" & vbCrLf, number(1, 1, 4))

        Console.WriteLine("Number(1)(2)(0) = {0}", number(1, 2, 0))
        Console.WriteLine("Number(1)(2)(1) = {0}", number(1, 2, 1))
        Console.WriteLine("Number(1)(2)(2) = {0}", number(1, 2, 2))
        Console.WriteLine("Number(1)(2)(3) = {0}", number(1, 2, 3))
        Console.WriteLine("Number(1)(2)(4) = {0}" & vbCrLf, number(1, 2, 4))

        Console.WriteLine("Number of items {0}", number.Length)
        Console.WriteLine("Number of items {0}", number.Rank)

        Console.WriteLine()
    End Sub
End Class

This would produce:

Number(0)(0)(0) = 12.44
Number(0)(0)(1) = 525.38
Number(0)(0)(2) = -6.28
Number(0)(0)(3) = 2448.32
Number(0)(0)(4) = 632.04

Number(0)(1)(0) = -378.05
Number(0)(1)(1) = 48.14
Number(0)(1)(2) = 634.18
Number(0)(1)(3) = 762.48
Number(0)(1)(4) = 83.02

Number(0)(2)(0) = 64.92
Number(0)(2)(1) = -7.44
Number(0)(2)(2) = 86.74
Number(0)(2)(3) = -534.6
Number(0)(2)(4) = 386.73

Number(1)(0)(0) = 48.02
Number(1)(0)(1) = 120.44
Number(1)(0)(2) = 38.62
Number(1)(0)(3) = 526.82
Number(1)(0)(4) = 1704.62

Number(1)(1)(0) = 56.85
Number(1)(1)(1) = 105.48
Number(1)(1)(2) = 363.31
Number(1)(1)(3) = 172.62
Number(1)(1)(4) = 128.48

Number(1)(2)(0) = 906.68
Number(1)(2)(1) = 47.12
Number(1)(2)(2) = -166.07
Number(1)(2)(3) = 4444.26
Number(1)(2)(4) = 408.62

Number of items 30
Number of items 3
 

Operations on Arrays

 

Adding Items to an Array

There are two main techniques you can use to initialize an array. You can create its list of items when declaring the array. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim Numbers() As Double = {12.44, 525.38, 6.28, 2448.32, 632.04}

        For Each n As Double In Numbers
            Console.WriteLine("Number: {0}", n)
        Next
    End Sub
End Class

Another technique is to first declare the array, then initialize each of its members. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim Numbers() As Double = {12.44, 525.38, 6.28, 2448.32, 632.04}
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"

        Console.WriteLine("Item 1: {0}", lstItemsNames(0))
        Console.WriteLine("Item 2: {0}", lstItemsNames(1))
        Console.WriteLine("Item 3: {0}", lstItemsNames(2))
        Console.WriteLine("Item 4: {0}", lstItemsNames(3))
        Console.WriteLine("Item 5: {0}", lstItemsNames(4))
        Console.WriteLine()

        For Each n As Double In Numbers
            Console.WriteLine("Number: {0}", n)
        Next
    End Sub
End Class

This would produce:

Item 1: Women Coat
Item 2: Men Jacket
Item 3: Teen Jeans
Item 4: Women Bathing Suit
Item 5: Children Playground Dress

Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04

Here is an example for a two-dimensional array:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim Numbers() As Double = {12.44, 525.38, 6.28, 2448.32, 632.04}
        Dim lstItemsNames As Array = Array.CreateInstance(GetType(String), 5)

        lstItemsNames(0) = "Women Coat"
        lstItemsNames(1) = "Men Jacket"
        lstItemsNames(2) = "Teen Jeans"
        lstItemsNames(3) = "Women Bathing Suit"
        lstItemsNames(4) = "Children Playground Dress"

        Console.WriteLine("Item 1: {0}", lstItemsNames(0))
        Console.WriteLine("Item 2: {0}", lstItemsNames(1))
        Console.WriteLine("Item 3: {0}", lstItemsNames(2))
        Console.WriteLine("Item 4: {0}", lstItemsNames(3))
        Console.WriteLine("Item 5: {0}", lstItemsNames(4))
        Console.WriteLine()

        For Each n As Double In Numbers
            Console.WriteLine("Number: {0}", n)
        Next
        Console.WriteLine()

        Dim storeItems(2, 3) As String

        storeItems(0, 0) = "Women Coat"
        storeItems(0, 1) = "Women Bathing Suit"
        storeItems(0, 2) = "Quilted Down Jacket"
        storeItems(1, 0) = "Men Jacket"
        storeItems(1, 1) = "Children Playground Dress"
        storeItems(1, 2) = "Boys Trousers"

        Console.WriteLine("Item 1: {0}", storeItems(0, 0))
        Console.WriteLine("Item 2: {0}", storeItems(0, 1))
        Console.WriteLine("Item 3: {0}", storeItems(0, 2))
        Console.WriteLine("Item 4: {0}", storeItems(1, 0))
        Console.WriteLine("Item 5: {0}", storeItems(1, 1))
        Console.WriteLine("Item 6: {0}", storeItems(1, 2))
        Console.WriteLine()
    End Sub
End Class

This would produce:

Item 1: Women Coat
Item 2: Men Jacket
Item 3: Teen Jeans
Item 4: Women Bathing Suit
Item 5: Children Playground Dress

Number: 12.44
Number: 525.38
Number: 6.28
Number: 2448.32
Number: 632.04

Item 1: Women Coat
Item 2: Women Bathing Suit
Item 3: Quilted Down Jacket
Item 4: Men Jacket
Item 5: Children Playground Dress
Item 6: Boys Trousers

The Array class also provides its own support for adding items to an array. This is done using the Array.SetValue() that is overloaded with various versions. To add a new item to a single-dimensional array, you can use the following syntax:

Overloads Public Sub SetValue(ByVal value As Object, ByVal index As Integer)

The first argument is the value to add to the list. The second argument is the index of the item to be added. The first item has index 1 the second item has index 2, and so on. Here is an example:

Imports System

Public Class Exercise
    Public Shared Sub main()
        Dim storeItems(3) As String

        storeItems.SetValue("Women Coat", 0)
        storeItems.SetValue("Women Bathing Suit", 1)
        storeItems.SetValue("Quilted Down Jacket", 2)
        storeItems.SetValue("Men Jacket", 3)

        For Each str As String In storeItems
            Console.WriteLine("Item: {0}", str)
        Next
        Console.WriteLine()
    End Sub
End Class

This would produce:

Item: Women Coat
Item: Women Bathing Suit
Item: Quilted Down Jacket
Item: Men Jacket

The Array class provides a SetValue() version for each corresponding CreateInstance() method we reviewed earlier.

Practical Learning Practical Learning: Adding Items to an Array

  1. To populate the array, change the Load event as follows:
     
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            lstItemsInStore = Array.CreateInstance(GetType(StoreItem.CStoreItem), 6)
    
            Dim anItem As StoreItem.CStoreItem
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "724372"
            anItem.ItemName = "Women Coat"
            anItem.Size = "Large"
            anItem.UnitPrice = 225.55
            lstItemsInStore.SetValue(anItem, 0)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "624376"
            anItem.ItemName = "Men Jacket"
            anItem.Size = "Medium"
            anItem.UnitPrice = 175.75
            lstItemsInStore.SetValue(anItem, 1)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "274952"
            anItem.ItemName = "Teen Jeans"
            anItem.Size = "14"
            anItem.UnitPrice = 24.5
            lstItemsInStore.SetValue(anItem, 2)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "497852"
            anItem.ItemName = "Women Bathing Suit"
            anItem.Size = "Petite"
            anItem.UnitPrice = 34.65
            lstItemsInStore.SetValue(anItem, 3)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "749752"
            anItem.ItemName = "Children Playground Dress"
            anItem.Size = "12"
            anItem.UnitPrice = 75.05
            lstItemsInStore.SetValue(anItem, 4)
    
            anItem = New StoreItem.CStoreItem
            anItem.ItemNumber = "394085"
            anItem.ItemName = "Boys Trousers"
            anItem.Size = "8"
            anItem.UnitPrice = 17.95
            lstItemsInStore.SetValue(anItem, 5)
    End Sub
  2. Save all
 

The Arrangement of the List

When a new item is added to the array, it assumes the last position. If you want, you can re-arrange the list in a consecutive order. If the list is a one-dimensional array made of strings, you can arrange it in alphabetical order. If it is made of numbers, you can order them in increment or decrement order. If the list is a two, three, or multi-dimensional array, you can arrange it based on a list-part of your choice. To support the ability to re-organize the list, the Array class is equipped with the Sort() method that is overloaded with as many versions as you can possibly need.

To arrange a single-dimensional array in a consecutive order, you can call the following version of the Array.Sort() method:

Overloads Public Shared Sub Sort(ByVal array As Array)

To reverse the sequence of items of a one-dimensional array, you can call the Array.Reverse() method. Its syntax is:

Overloads Public Shared Sub Reverse(ByVal array As Array)

Looking for an Item in an Array

When using a list, you may want to know whether a particular item exists in the list. There are usually two ways to perform this operation. You usually can use a loop to scan a list. With this approach, you navigate through the list by visiting the index of each item and checking the value of that index. Another solution consists of writing a function to perform the search. The Array class provides its own support of both solutions using various methods that can be used to perform this operation.

The Array.IndexOf() method scans a list by accessing the index of each item. This method is overloaded with three versions. To apply it on a single-dimensional array, use the following version:

Overloads Public Shared Function IndexOf( _
   ByVal array As Array, _
   ByVal value As Object _
) As Integer

This method visits each member of the array, looking for the value. Once it finds value in the array, it stops and returns the index where the first occurrence of value was found. The IndexOf() method actually looks for the first occurrence of an item in an array. If you prefer to get the last occurrence of that item in the array, you can call the Array.LastIndexOf() method. It also is overloaded in three versions.

 

The Bounds of an Array

To better manage an array, the compiler must always be able to locate its highest and its lowest members. This is particularly important because an array must have a fixed size (by the way, using some gymnastic, an array can grow or shrink).

The lowest member of an array can be located using the Array.GetLowerBound() method. Its syntax is:

Public Function GetLowerBound(ByVal dimension As Integer) As Integer

The highest member of an array can be located using the Array.GetUpperBound() method. Its syntax is:

Public Function GetUpperBound(ByVal dimension As Integer) As Integer

In both cases, the dimension argument is the rank of the array. For a single-dimensional array, as those we have always used so far, this parameter must have the value of 0;

 
 

Home Copyright © 2005-2012 FunctionX Next