You are on page 1of 7

Introduction to VB.

NET Arrays Intro


Page 1 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 1 of 7
What is an Array

Consider the coding requirements for an application that is to accept the ages of a group
of people and then display the number of people that have an age that is above the group
average age. Since the average age can only be determined AFTER the last age has
been entered the decision as to whether an age is above average cannot be determined at
the time of its entry. This requires all ages to be stored until the last age has been
accepted and then each processed. The use of separate variables for each age would
only be feasible for a small number of ages but even then the coding would be repetitive.
The concept of an array overcomes this problem.

An array is a single name that reserves memory space in RAM for a set of items with
identical type (size). The individual items in the set are distinguished by attaching to each
separate storage area the name of the array plus a number within brackets called a
subscript or index. The values the subscript can take will vary with the programming
language but in Visual Basic they can be allocated integer values
from 0 onwards. For example a VB array named Age by the
programmer and set to store up to 20 student integer ages would
reserve memory space for 20 integers and can be represented
diagrammatically as shown opposite:

Note that some programming languages use square brackets around
subscripts and some use round brackets. VB uses round brackets.


Declaring Variable Arrays in Visual Basic

Array Variable declarations use the same DIM, PUBLIC or GLOBAL statements that are
used to declare any single variable but the number of members required is placed in round
brackets after the variable name. Thus the general declaration for an array will be:

Dim ArrayVariableName(Size) as DataType
For example, the statement
DIM intAge(20) as Integer

declares an array called intAge of 20 members (with highest index 19). That is, it reserves
space for 20 integer items identified by the names intAge(0), intAge(1), ... ,intAge(19)

If subscripts other than zero onwards are wanted the declaration can specify them using
the statement
Dim ArrName (StartIndex TO EndIndex) as DataType

For example :
DIM DecYrIncome(1990 TO 1999) as Integer

declares an array called DecYrIncome whose subscripts are 1990, 1991, ... ,1999 That is
the members are DecYrIncome(1990), DecYrIncome(1991), ... ,DecYrIncome(1999)

Note that a run time error will occur if any VB statement tries to access an array member
using a subscript outside the declared range and so the programmer must select an array
size that they believe will be the largest needed to hold the data to be stored. However to
Age
Age(0)
Age(1)
Age(2)
Age(3)
Age(4)
:
Age(19)
Introduction to VB.NET Arrays Intro
Page 2 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 2 of 7
make changes easier, if required at some later date, array declarations are commonly
made using a constant to hold the size.

For example :
Const ARRAY_SIZE as integer =20
Dim IntAge(ARRAY_SIZE) as Integer

Processing With Arrays

Processing in which an array is needed commonly has two separate steps.
1. Fill the array- the data is entered into the array members and then
2. Process array contents - the array members are in turn accessed again and
their contents used to perform the required processing. This is nearly always
done using a FOR loop.


Filling Arrays

Method 1 : Assigning Values to Array Members
Array members can be used in any statement in place of a single variable. Hence a single
array member can be individually given a value an assignment statements. Examples
are:

IntMark(6) =80 and IntMark(15) =70

Method 2: Fill at declaration
Array members can also be automatically given an initial value as part of the array
declaration using:
Dim VarName() as DataType ={V1, V2, ... Vn}

For example, the declaration
Dim StrName() as string ={Al, Di, J o, Bo}

Is equivalent to the following

Dim StrName(4) as string

StrNames(0) =Al
StrNames(1) =Di
StrNames(2) =J o
StrNames(3) =Bo

Note that in declarations of this type the array size is NOT specified. It automatically
becomes that of the number of data values supplied.


Other Array filling Methods

The most common array member filling techniques sequentially allocate values to array
members, starting with the member with subscript zero, followed by the member with
subscript 1, and then 2 etc. This is usually done using a loop and a variable that is set to
hold the subscript of the member to be filled that is incremented each time the loop is
Introduction to VB.NET Arrays Intro
Page 3 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 3 of 7
repeated. That is the subscript variable is given a starting value of 0 and has 1 added to it
for each loop repetition. These techniques will be introduced below.


Processing the Contents of filled Arrays

Individual array members can be used in any statement where a regular single value
variable could have been used

Examples are: TxtNum.text =intMark (4)
If IntMark (3) >10 then ....

However, once an array has been filled the most common processing technique uses a
FOR loop to access each array member in turn and process it. The For loop counter
variable becomes the array subscript allowing the each repetition of the loop to change the
array subscript value from its first to its last value. In general the code is:

FOR intIndex = 0 TO (intNumEntries - 1)

Steps here to process the array member having subscript intIndex

NEXT

For example, given a listbox called LstNums and a rich textbox called RtbList and the
declarations
Dim IntNums() ={6,2,4,7}
Dim s as integer
Then the code
For s =0 to 3
LstNums.Items.Add( IntNums(s))
Next

places each array member in turn into the list box and the code

For s =0 to 3
RtbList.Text =RtbList.Text & IntNums(s) & VBcrlf
Next

Places each array member in turn onto a separate line of the rich text box.

Supplied methods (functions) also exist for arrays to provide information about them.

Common methods are:
ArrName.GetLowerBound gives lowest subscript of ArrName
ArrName.GetUpperBound gives highest subscript of ArrName
ArrName.Length gives size (number members) in ArrName

Note that the GetUpperBound method gives the highest subscript and not the subscript of
the highest filled member. Similarly the Length method gives the declared size and not the
number of filled members.

For example:
Introduction to VB.NET Arrays Intro
Page 4 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 4 of 7
Given the declaration Dim IntAge (20) as integer
IntAge.GetLowerBound will return 0
IntAge.GetUpperBound will return 19
IntAge.Length will return 20

Here run Array Example 1 (in the shared drive). Look closely at the code and try to
work out what action each line in the code causes.


Array Exercises Set A
1. Create an application with a form that has a list box and two buttons. Write the
code (as a form variable) to place the names of the six Australian states into an
array.

2. Add two buttons a list box to the form used for question 1 . When either button is
clicked it is cause the state names to be displayed in array member order. However
Clicking the fist button the names are to be displayed in a list box while clicking the
second button on successive lines in a rich text box

3. Repeat Question 2 but display the names in reverse order to their array subscript
positions.


Filling a fixed number of members using InputBox()

Where a fixed number of array members are to be filled a FOR loop can be used that
repeatedly gets a single array member values using InputBox.() . For example, to accept
5 string Item names into the array StrItemArr

For i =0 to 4
StrItemArr(i) =InputBox(Enter Item & ( i+1).Tostring() & - )
Next
Here run Array Example 2 (in the shared drive). Look closely at the code and try to
work out what action each line in the code causes.

Here run Array Example 3 (in the shared drive). Look closely at the code and try to
work out what action each line in the code causes.


Array Exercises Set B
1. Write an application that has three buttons. The first when clicked is to ask the user
to enter any three AFL teams via pop up Input boxes and store them in an array.
The second when clicked is to place the entered names into a list box. The third
Introduction to VB.NET Arrays Intro
Page 5 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 5 of 7
when clicked is to ask the user to enter a number from 0 to 2 inclusive and is to
display in a message box the team name in that array position. Include a check
that the entry is firstly a number and secondly between 0 and 2.

Introduction to VB.NET Arrays Intro
Page 6 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 6 of 7
2. Write an application that has two buttons. When the first is clicked, repeatedly
using an input box, the user is to be asked to enter exactly 5 numbers (allow
fractions) that are to be stored in an array. When the second button is clicked the
numbers in the array and their squares are to be displayed in either a list box or on
successive lines of a rich text box.

3. Create an application that initializes an array called dog() with the following dog
names : corgi, boxer, husky, beagle and collie. When the user clicks on a button a
list box is to appear (it should not be visible before the button is clicked) displaying
the list of dogs in the above order with each dog name preceded by a number
(from 1 to 5) matching its order in the array.

4. Write an application that has a textbox and two buttons. The user to enter a
number between 1 and 12 into the textbox and after doing so can click on the first
button to display in a message box the name of the month which has the entered
month number (or an error message if it is not in the range 1 to 12). Thus, if the
number 3 is entered, March will be displayed. The second button when clicked will
clear the textbox. The application is to use arrays. Hint palce the month names in
an array in month order.

5. Modify Question 4 so that the user enters the month name and the application
displays the month number.

6. Add a third button to Question 2 that when clicked displays in a message box the
average of the array members.

7. Add a textbox to question 3 that allows the user to enter a dog name. Add also
another button that when clicked causes a message box to be displayed that
indicates if the entered name is or is not contained in the array of dog names.
8. Challenge Question: Modify question 6 so that the data entry includes a check that
a number is entered. If the entry is not a number an error message must be
displayed. Note that exactly 5 valid numbers must still be accepted.



Parallel, Related or Matching Arrays

This is the term given to two or more arrays that have related information at the same
subscript position in each array. For example, two arrays could be declared, one to hold
a set of integer ages and the other to hold a set of names (as strings) as in the diagram
below. As a name is placed into a member of the name array the age of that person is
placed in the age array member with the same subscript. Thus if the subscript of a specific
name in the name array is known or found then the age of that person will be in the same
subscript position in the age array.

Introduction to VB.NET Arrays Intro
Page 7 of 7 Cert III in IT Week 13

Brian Kaye File : E:\Teaching Subjects\Cert III VB\Sem 1 2013\lecturer version\week 13 Arrays Intro\Week 13- arrays intros.docxx
Page 7 of 7

Name Age Values at the same subscript match
Name(0) Al Age(0) 10 Als age is 10 (both values at Index 0 in each array)
Name(1) J o Age(1) 60 J os age is 60 (both values at Index 1 in each array)
Name(2) Di Age(2) 35 Dis age is 35 (both values at Index 2 in each array)
Name(3) Fi Age(3) 30 Fis age is 30 (both values at Index 3 in each array)
etc etc etc

Here run Array Example 4 (in the shared drive). Look closely at the code and try to
work out what action each line in the code causes.


Exercise Set C

1. Below is a list of magazines and their prices
Time $4.00
Australian Geographic $6.50
Gormet $5.00
Dolly $4.50
Wheels $3.95

Create an application that declare two arrays, one to hold the Magazine names and
the other their prices. Initialise these arrays with the above information. The
application must have two buttons that carry out actions as described below:
(a) A Find Price button that will request the user enter via an input box the
name of a magazine and then display its price or a message saying
magazine not in our list
(b) A price under button that will request the user enter via an input box a cost
and then display in a list box the name and price of all magazines with a
price less than that cost.
(c) Repeat (b) but include numeric entry validation for the cost entry plus
displaying an appropriate message if no magazines are under the entered
cost.

2. A company has branches in Perth, Bunbury, Albany and Geraldton. The profits
made by the branches last year were respectively $750,000 , $250,000 , $140,000
and $160,000. Create an application that declares two array that at start up hold
the above values. The application is to have three buttons that act as follows.
(a) The first when clicked is to respectively display in two text boxes the total
profit for all branches and the average branch profit.
(b) The second when clicked is to display in a list box the names of the branches
with an above average profit.
(c) The third when clicked is to display respectively in two additional textboxes,
the name of the branch with the highest profit and the name of the branch
with the lowest profit.

You might also like