1. Lesson 7 of 8 Visual Basic Programming
1 of 3
Lesson 7: Mastering Arrays
Author: Kasun Ranga Wijeweera
Email: krw19870829@gmail.com
Date: 2020 April 10
Look at the code segment given below.
Dim num As Integer
num = 7
The variables that have been discussed so far can hold a single
value at a time. An array is a variable that can hold more than one
value at a time. Look at the code segment given below.
Dim nums (2) As Integer
nums (0) = 34
nums (1) = 58
nums (2) = 26
The array nums can hold three values. It can be graphically
represented as given below.
0 1 2
34 58 26
The index of each value is shown in red color. The value in 0th
index is 34, the value in 1st
index is 58, and the value in 2nd
index is
26.
2. Lesson 7 of 8 Visual Basic Programming
2 of 3
In order to declare an array that can hold three values, the code
segment Dim nums (2) As Integer was used. The maximum index of
the array should be specified within parenthesis.
Each value in the array can be displayed using the code segment
given below.
MessageBox.Show (“First Value: ” & nums (0))
MessageBox.Show (“Second Value: ” & nums (1))
MessageBox.Show (“Third Value: ” & nums (2))
Arrays can hold other types of data as well. An example for a
string array is given below.
Dim blood (3) As String
blood (0) = “Plasma”
blood (1) = “Red Blood Cells”
blood (2) = “White Blood Cells”
blood (3) = “Platelets”
0 1 2 3
Plasma Red Blood Cells White Blood Cells Platelets
Look at the code segment given below.
Dim nums () As Integer
Dim n As Integer
n = 10
ReDim nums (n)
3. Lesson 7 of 8 Visual Basic Programming
3 of 3
An array can be declared with empty parenthesis if the number
of values in the array is unknown at the beginning. Later using the
keyword ReDim, the number of values in the array can be specified.
Multidimensional arrays can also be declared. For an example, a
two-dimensional integer array is given below.
0 1 2 3
0 54 32 64 21
1 87 57 98 75
2 49 17 67 35
Dim array (2, 3) As Integer
Dim row, col As Integer
array (0, 0) = 54
array (0, 1) = 32
array (0, 2) = 64
array (0, 3) = 21
array (1, 0) = 87
array (1, 1) = 57
array (1, 2) = 98
array (1, 3) = 75
array (2, 0) = 49
array (2, 1) = 17
array (2, 2) = 67
array (2, 3) = 35
For row = 0 To 2
For col = 0 To 3
MessageBox.Show (array (row, col))
Next col
Next row