Arrays
An array stores a fixed-size sequential collection of elements of
the same type. An array is used to store a collection of data, but it is often
more useful to think of an array as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.
Creating
Arrays in VB.Net
1.Module
Module1
Sub Main()
' Create an array.
Dim array(2) As Integer
array(0) = 100
array(1) = 10
array(2) = 1
For Each element As Integer In
array
Console.WriteLine(element)
Next
End Sub
End
Module
Output
100
10
1
2.Integer array
2
Module
Module1
Sub Main()
' Create array of three integers.
Dim array() As Integer = {10, 30,
50}
For Each element As Integer In
array
Console.WriteLine(element)
Next
End Sub
End
Module
Output
10
30
50
String array
Module
Module1
Sub Main()
' Create array of maximum index 3.
Dim array(3) As String
array(0) = "dot"
array(1) = "net"
array(2) = "perls"
array(3) = CStr(2010)
' Display.
For Each element As String In array
Console.WriteLine(element)
Next
End Sub
End
Module
Output
dot
net
perls
2010
Array argument
Module
Module1
Sub Main()
Dim array() As Integer = {5, 10, 20}
' Pass array as argument.
Console.WriteLine(Example(array))
End Sub
''' <summary>
''' Receive array parameter.
''' </summary>
Function Example (ByVal array() As Integer)
As Integer
Return array(0) + 10
End Function
End
Module
Output
15
Jagged Array
A jagged array is uneven in shape. It is an array of arrays. For example, it one array element should be four elements long. Another should be 400 elements long. In this situation a jagged array is extremely efficient.
Eg:-' Create jagged array with maximum index of 2.
Dim jagged()() As Integer = New Integer(2)() {}
' Create temporary array and place in index 0.
Dim temp(2) As Integer
temp(0) = 1
temp(1) = 2
temp(2) = 3
jagged(0) = temp
' Create small temporary array and place in index 1.
Dim temp2(0) As Integer
jagged(1) = temp2
' Use array constructor and place result in index 2.
jagged(2) = New Integer() {3, 4, 5, 6}
' Loop through top-level arrays.
For i As Integer = 0 Tojagged.Length - 1
' Loop through elements in subarrays.
Dim inner As Integer() = jagged(i)
For a As Integer = 0 Toinner.Length - 1
Console.Write(inner(a))
Console.Write(" "c)
Next
Console.WriteLine()
Next
End Sub
End Module
Output
1 2 3
0
3 4 5 6
0 comments
Post a Comment