3.2.6 - One-dimensional arrays (VB.NET)
Organise values by index and process them with VB.NET loops. Native code answers are written without Run; the optional Python demonstration uses a list to explore indexed changes.
Indexed collections
A data structure organises related data so a program can store, locate and process it consistently.
One-dimensional array
An indexed collection of elements of the same type, accessed using one index.
A shop's weekly sales can use one array rather than seven unrelated variable names. An index identifies a position; the element is the value stored at that position. Native VB.NET arrays normally begin at index 0 and use parentheses for access:
Dim sales() As Integer = {12, 9, 14, 8}
Console.WriteLine(sales(1))
sales(1) = 11
The first output is 9, the second element. The update replaces that element with 11; the other three remain unchanged.
| Index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| Value before update | 12 | 9 | 14 | 8 |
| Value after update | 12 | 11 | 14 | 8 |
When specifying space, VB.NET's number is the upper bound, not the element count. Dim values(6) As Integer creates seven elements indexed 0–6, initially zero. To create exactly six, use Dim values(5) As Integer, indexed 0–5. values(6) is invalid for that six-element array. An initialiser such as {12,9,14,8} determines a four-element array, so its last index is 3.
Use sales.Length for the element count. A fixed-size native array does not automatically grow when an out-of-range index is used. An array is useful when items have the same role, such as temperatures or scores; later records group fields with different roles and types.
Traversing and changing an array
Traversing an array means visiting its elements in a deliberate order to apply processing.
Dim sales() As Integer = {12, 9, 14, 8}
Dim total As Integer = 0
For index As Integer = 0 To sales.Length - 1
total = total + sales(index)
Next
Console.WriteLine(total)
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account