Arrays
Prerequisites: For and For Each loops
An array holds a fixed number of values of the same type, accessed by a zero-based index in parentheses:
Module Program
Sub Main()
Dim scores() As Integer = {70, 85, 92}
Console.WriteLine(scores(0))
Console.WriteLine(scores.Length)
scores(1) = 88
Console.WriteLine(String.Join(", ", scores))
Dim names(2) As String ' upper bound 2: three elements
names(0) = "Ada"
names(1) = "Grace"
names(2) = "Linus"
Console.WriteLine(names.Length & " " & UBound(names))
End Sub
End Module
70
3
70, 88, 92
3 2
Watch out: Dim names(2) As String gives the upper bound (the last
index), not the length — so it creates three elements, 0 to 2. This is
different from C#, where new string[2] has two.
Looping and common operations
Module Program
Sub Main()
Dim numbers = {5, 3, 8, 1, 9}
For i = 0 To numbers.Length - 1
Console.Write($"{i}:{numbers(i)} ")
Next
Console.WriteLine()
Array.Sort(numbers)
Console.WriteLine(String.Join(" ", numbers))
Array.Reverse(numbers)
Console.WriteLine(String.Join(" ", numbers))
Console.WriteLine(Array.IndexOf(numbers, 8))
Console.WriteLine(numbers.Contains(4))
Console.WriteLine($"{numbers.Sum()} {numbers.Max()} {numbers.Average()}")
End Sub
End Module
0:5 1:3 2:8 3:1 4:9
1 3 5 8 9
9 8 5 3 1
1
False
26 9 5.2
Sum, Max, Average, and Contains come from LINQ, which VB
imports automatically — Level 2 covers it in depth.
Resizing with ReDim
Module Program
Sub Main()
Dim items() As String = {"a", "b"}
ReDim Preserve items(3)
items(2) = "c"
items(3) = "d"
Console.WriteLine(String.Join(",", items))
ReDim items(1)
Console.WriteLine(items(0) Is Nothing)
End Sub
End Module
a,b,c,d
True
ReDim Preserve resizes and keeps the contents; plain ReDim starts
over. Resizing copies the whole array, so when a collection grows often,
use a List(Of T) instead (Level 2).
Multidimensional arrays
Module Program
Sub Main()
Dim grid(2, 3) As Integer ' 3 rows, 4 columns
For r = 0 To 2
For c = 0 To 3
grid(r, c) = r * 10 + c
Next
Next
Console.WriteLine(grid(2, 3))
Console.WriteLine(grid.GetLength(0) & " x " & grid.GetLength(1))
Dim board(,) As Char = {{"X"c, "O"c}, {"O"c, "X"c}}
Console.WriteLine(board(1, 0))
End Sub
End Module
23
3 x 4
O
Practice
Store seven daily temperatures in an array, then print the average (one decimal), the highest value, and how many days were above 20.
Show solution
Module Program
Sub Main()
Dim temps = {18, 21, 25, 19, 23, 17, 22}
Dim warmDays = 0
For Each t In temps
If t > 20 Then warmDays += 1
Next
Console.WriteLine($"Average: {temps.Average():F1}")
Console.WriteLine($"Highest: {temps.Max()}")
Console.WriteLine($"Days above 20: {warmDays}")
End Sub
End Module
Average: 20.7
Highest: 25
Days above 20: 4