Posted by : Sudhir Chekuri Saturday, 5 October 2013

VB.NET Arrays

Arrays are used to store multiple values of similar datatype under a single array.
Arrays are zero indexed.
Indexes are used to retrieve or store data in an array.
There are three types of arrays.
1. Single dimensional array.
2. Multi dimensional array.
3. Jagged array

VB.NET Single dimensional array program

Module Module1
    Sub Main()
        ' Create an array.
        Dim array(2) As Integer
        array(0) = 100
        array(1) = 10
        array(2) = 1

        For Each i As Integer In array
            Console.WriteLine(i)
        Next
        Console.ReadLine()

    End Sub
End Module

Output

100
10
1

VB.NET Single dimension array program

Module Module2

    Sub Main()
        Dim a() As Integer = New Integer() {1, 2, 3, 4, 5, 6, 7}
        'for loop
        Dim i As Integer
        For i = 0 To a.Length - 1 Step 1
            Console.Write(a(i) & "   ")
        Next

        Console.ReadLine()

    End Sub

End Module

Output

1 2 3 4 5 6 7

Two dimensional array program

Module Module2

    Sub Main()
        Dim a(,) As Integer = New Integer(,) {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
        Dim i As Integer = 0 'i for rows
        Dim j As Integer = 0 'j for columns
        'while loop
        While (i < 3)
            While (j < 3)
                Console.Write(a(i, j) & "   ")
                j += 1
            End While
            Console.WriteLine()
            j = 0
            i += 1

        End While
        Console.ReadLine()

    End Sub

End Module

Output

1 2 3
4 5 6
7 8 9

Jagged array example program

Module Module2

    Sub Main()
        Dim a()() As Integer = New Integer(4)() {}
        a(0) = New Integer() {1, 2, 3, 4, 5}
        a(1) = New Integer() {3, 4}
        a(2) = New Integer() {1, 2, 3}
        a(3) = New Integer() {1}
        Dim i As Integer
        Dim j As Integer
        'for loop
        For i = 0 To a.Length - 1 Step 1
            For j = 0 To a(i).Length - 1 Step 1
                Console.Write(a(i)(j) & "   ")
            Next
            Console.WriteLine()
        Next
        Console.ReadLine()
    End Sub

End Module

Output

1 2 3 4 5
3 4
1 2 3
1

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Followers

Total Pageviews

Powered by Blogger.

Blog Archive

- Copyright © 2013 DevStudent - Metrominimalist - Powered by Blogger - Designed by Johanes Djogan -