VB.NET tutorial: Arrays-One-Dimensional Array


VB.NET Arrays

Array is a collection of values of the same type and name. There are two common types of array--one-dimensional array and two-dimensional array.

One-Dimensional Array

Dim array_name() As DataType
Example:
Dim arr() As Integer
 

Allocating One-dimensional array


array_name=new Datatype(size){}
Example:
arr=new Integer(2){}
 

Initialize One-dimensional array


array_name=new Datatype(size){val1,val2,val3,…}
or
array_name(index0)=val1
array_name(index1)=val2
array_name(index2)=val3
………….
Example:
 
Module Module1

 

    Sub Main()

        'Declaring and allocating the 1D-array

        Dim arr() As Integer

        arr = New Integer(2) {1, 2, 3}

        'Or

        'arr = New Integer(2) {}

        'arr(0) = 1

        'arr(1) = 2

        'arr(2) = 3
 

        'Accessing the array elements

        For Each i In arr

            Console.WriteLine(i)

        Next

        Console.ReadLine()

    End Sub
 
End Module
 


Accessing one-dimensional array elements with for loop
Example:
Module Module1

 

    Sub Main()

        'Declaring and allocating the 1D-array

        Dim arr() As Integer

        arr = New Integer(2) {3, 2, 1}
  'sor the array

        Array.Sort(arr)

 

        'Accessing the array elements with for loop

        For i = 0 To arr.Length – 1 'Or To arr.GetUpperBound(0)

            Console.WriteLine(arr(i))

        Next

        Console.ReadLine()                

 

    End Sub
 
 
End Module
 
Note: Length is used to get the length of the array. Length-1 equals to GetUpperBound.To sort an array, use Array.Sort(array_name) statement.


Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.