Array
a collection
the "problem" with dealing with a collection as a bunch of separate variables.
1) unweildy
2) not easily changable to diff number of variable
Dim score(29) As Double
Dim student(29) As String
score(0) = 87
score(1) = 92
If you write programs involving large arrays
a good idea is to test using small arrays first
For i As Integer = 0 To 29
lstBox.Items.Add(score(i))
Next
a new loop!
For Each x in score
lstBox.Items.Add(x)
Next
we can make the array a class-level variable
and fill it in the Form_Load event
Dim teamName(3) As String = {"Packers", "Packers", "Jets", "Chiefs"}
often, we will use loops to iterate thru an array.
easier way: use for each loop
harder way: for i = 0 to whatever the upper bound is
problem: 29 is a "magic number". makes code hard to read. introduces errors. let us say i change to 60 students!
for i = 0 to UBound(scores)
scores(i) = 90
next
for i = 0 to scores.GetUpperBound(0)
scores(i) = 90
next
Dim scores() As Double
realize that scores, or any array, is a reference type
ReDim scores(29)
ReDim scores(n)
dynamic memory allocation
Dim scores(3) As Integer
scores(0) = 58
scores(1) = 78
scores(2) = 100
scores(3) = 98
ReDim scores(4)
' alternatively
ReDim Preserve scores(4)
will preserve the values
No comments:
Post a Comment