Visual Basic 2010 (Console) Guide
One-Dimensional Arrays

An array is an ordered set of values of a single type. Each element in the array shares the same name but a different index or subscript. This is a number which indicates the position of the element in the array. In Visual Basic, the first element of an array has the subscript, 0.

When we declare an array, we also specify the size of the array.

Dim names(3) As String
names(0) = "Pinky"
names(1) = "Perky"
names(2) = "Bob"
names(3) = "Bill"

The following example creates an array of strings and initialises the array,

Dim names() As String = {"Pinky", "Perky", "Bob", "Bill"}

Reading Each Element In An Array

The fact that arrays use a single variable name and a unique index to represent the information stored makes it easy to use loops to process them.

For example,

Dim names() As String = {"Pinky", "Perky", "Bob", "Bill"}
For count = 0 To 3
   Console.WriteLine("{0}. {1}", count, names(count))

You can also use the foreach loop to do this.

Dim names() As String = {"Pinky", "Perky", "Bob", "Bill"}
For Each itm As String In names
   Console.WriteLine("{0}. {1}", Array.IndexOf(names, itm), itm)

Array Class Methods

There is a .NET class called Array. Just like the string class, there are a series of useful methods. For the most part, you would need to look these up as and when you need to. The following methods might prove useful in the future,

Array.Clear(array, start, length)Sets the specified range of elements to 0, false or Nothing depending on the data type
Array.Copy(source, destination, n) Copies n items from the start of the source array into the destination array
myArray.GetLength(d)Gets the length of dimension d of an array
myArray.GetLowerBound(d)Gets the lowest subscript of dimension d of an array
myArray.GetUpperBound(d)Gets the largest subscript of dimension d of an array
Array.IndexOf(array, item)Gets the subscript of the first occurrence of item in the specified array
Array.Reverse(array)Reverses all of the elements of an array
Array.Reverse(array, start, end)Reverses a portion of the array
Array.Sort(array)Sorts an array numerically or alphabetically using a quicksort algorithm

Having A Go

  1. Initialise an array of 10 names. Output the array to the screen in reverse order.
  2. Declare an array of 10 integers. Allow the user to input the values they want. Output the sum, largest, smallest and mean values from their list.
  3. Declare an array of 7 integers. Initialise each element to 0. Use a loop and random numbers to simulate the rolling of a single die. If a 1 is rolled, increase the value of element 1 in the array by 1, if a 2 is rolled, increase the value of element 2 by 1. When all 200 rolls have been simulated, output the tally to the console.
  4. Write a program to choose 100 random numbers between 1 and 100. Count and display how many numbers are in the range 1-10, 11-20, 21-30 etc.