Lesson 10: Mastering Arrays in VB2022

Understanding data collections and structured storage in Visual Basic programming

Key Takeaway

Arrays are essential data structures that allow you to store multiple values of the same type under a single variable name. They provide efficient access to elements using index positions and are fundamental for managing collections of data in your applications.

Welcome to Lesson 10 of our Visual Basic 2022 Tutorial! In this lesson, you'll learn how to work with arrays - powerful data structures that allow you to store and manage collections of data efficiently. Arrays are essential for handling multiple values without declaring numerous individual variables.

Learning Objectives

  • Understand the purpose and benefits of using arrays
  • Declare and initialize one-dimensional arrays
  • Work with multidimensional arrays
  • Resize arrays dynamically with ReDim
  • Utilize common array methods and properties
  • Apply arrays in practical programming scenarios
  • Sort and search arrays efficiently

10.1 Understanding Arrays

Arrays are named storage locations that hold multiple values of the same type. They allow you to work with collections of data efficiently without needing to create numerous individual variables.

Indexed Access

Elements are accessed via zero-based index positions

Fixed Size

Arrays have a fixed size once created (unless resized)

Multidimensional

Can represent tables with rows and columns

Dynamic

Can be resized during program execution

10.1.1 Array Declaration

Arrays can be declared using several approaches in VB.NET:

ArrayDeclaration.vb
' Basic array declaration
Dim numbers(4) As Integer ' 5 elements (0 to 4)

' Declaration with initialization
Dim fruits() As String = {"Apple", "Banana", "Cherry"}

' Explicit size declaration
Dim matrix(2, 3) As Integer ' 3 rows, 4 columns

' Using New keyword
Dim temperatures As Double() = New Double(4) {}

Best Practice

Always initialize arrays with meaningful values. Use the Length property instead of hard-coding sizes to make your code more maintainable.

10.2 Array Dimensions

VB.NET supports arrays with different dimensions:

One-Dimensional Arrays

A list of items similar to a single row or column:

[0]
10
[1]
20
[2]
30
[3]
40

Declaration: Dim myArray(3) As Integer

Two-Dimensional Arrays

A table of items with rows and columns:

Col 0 Col 1 Col 2
Row 0 A B C
Row 1 D E F

Declaration: Dim matrix(1, 2) As String

MultiDimArray.vb
Private Sub BtnDisplay_Click(sender As Object, e As EventArgs) Handles BtnDisplay.Click
    ' Declare and initialize a 2D array
    Dim matrix(,) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
    
    ' Display matrix values
    For row As Integer = 0 To matrix.GetLength(0) - 1
        Dim rowText As String = ""
        For col As Integer = 0 To matrix.GetLength(1) - 1
            rowText &= matrix(row, col) & " "
        Next
        ListBox1.Items.Add(rowText)
    Next
End Sub

Output:

1 2 3
4 5 6
7 8 9

10.3 Dynamic Arrays

Dynamic arrays let you determine the array size at runtime. Use ReDim to resize arrays during execution.

1 Declaration

Declare an array without specifying dimensions:

DynamicDeclaration.vb
Dim dynamicArray() As String

2 Resizing

Use ReDim to set the size at runtime:

Resizing.vb
' Initial sizing
ReDim dynamicArray(4) ' 5 elements

' Resize while preserving existing values
ReDim Preserve dynamicArray(9) ' Now 10 elements

3 Practical Example

Dynamically sized array based on user input:

DynamicExample.vb
Private Sub BtnGenerate_Click(sender As Object, e As EventArgs) Handles BtnGenerate.Click
    Dim count As Integer = Integer.Parse(txtCount.Text)
    Dim squares() As Integer
    
    ' Resize array based on user input
    ReDim squares(count - 1)
    
    ' Populate the array
    For i As Integer = 0 To squares.Length - 1
        squares(i) = (i + 1) * (i + 1)
        ListBox1.Items.Add($"Square of {i+1} = {squares(i)}")
    Next
End Sub

10.4 Sorting and Searching Arrays

VB.NET provides built-in methods for common array operations:

ArrayOperations.vb
Private Sub BtnSortSearch_Click(sender As Object, e As EventArgs) Handles BtnSortSearch.Click
    ' Create and initialize an array
    Dim names() As String = {"Zoe", "Alice", "Bob", "Charlie"}
    
    ' Display original array
    ListBox1.Items.Add("Original Array:")
    For Each name In names
        ListBox1.Items.Add(name)
    Next
    
    ' Sort the array
    Array.Sort(names)
    ListBox1.Items.Add("")
    ListBox1.Items.Add("Sorted Array:")
    For Each name In names
        ListBox1.Items.Add(name)
    Next
    
    ' Reverse the array
    Array.Reverse(names)
    ListBox1.Items.Add("")
    ListBox1.Items.Add("Reversed Array:")
    For Each name In names
        ListBox1.Items.Add(name)
    Next
    
    ' Search for an element
    Dim index As Integer = Array.IndexOf(names, "Bob")
    ListBox1.Items.Add("")
    ListBox1.Items.Add($"Index of 'Bob': {index}")
End Sub

Output:

Original Array:
Zoe
Alice
Bob
Charlie

Sorted Array:
Alice
Bob
Charlie
Zoe

Reversed Array:
Zoe
Charlie
Bob
Alice

Index of 'Bob': 2

Lesson Summary

In this lesson, we've covered essential concepts about arrays in VB2022:

Array Declaration

Use the Dim keyword to declare arrays with specific dimensions

Initialization

Initialize arrays with values at declaration or later

Multidimensional

Create tables with two or more dimensions

Dynamic Arrays

Resize arrays during runtime with ReDim

Array Methods

Use built-in methods like Sort, Reverse, and IndexOf

These skills form the foundation for working with collections of data in VB2022. In the next lesson, we'll explore mathematical operations in depth.

Exercises

Practice what you've learned with these exercises:

Exercise 1: Temperature Analyzer

Create a program that:

  1. Stores daily temperatures for a week in an array
  2. Calculates and displays the average temperature
  3. Finds and displays the highest and lowest temperatures
  4. Displays all temperatures above average

Exercise 2: Student Gradebook

Build an application that:

  1. Uses a 2D array to store student grades (students × assignments)
  2. Calculates each student's average grade
  3. Finds the class average for each assignment
  4. Identifies the highest and lowest performing students

Exercise 3: Dynamic Inventory System

Implement a solution that:

  1. Allows users to add products to an inventory array
  2. Uses dynamic arrays to resize as products are added
  3. Provides search functionality to find products by name
  4. Sorts products alphabetically for display

Next Lesson

Ready to learn about mathematical operations? Continue to Lesson 11: Math Operations in VB2022.

Related Resources

VB6 Tutorial

Mastering VB6 Programming

Explore Tutorials

Visual Basic Examples

Practical VB code samples for real-world applications

View Examples

Excel VBA Tutorial

Learn how to automate Excel by creating VBA macros

Learn More