|
Arrays
-
a group of related elements given a common name.
-
each element is referenced by its position in the group (index).
-
an
array is similar to a list of numbered items

Justification
- How data is organized plays an important role in the design process.
-
It is sometimes necessary to show
relationships among different variables or store and reference variables as
a group.
-
Many problems have so many components that
it is difficult to process them if each one must have a unique field name.
Example:
- A program is
required to store and print 1000 pieces of related data, such as
pressure readings from some manufacturing process.
- If individually
named variables are used for each data item, then the program must
have 1000 unique variable names and 1000 separate print statements
to print those individual data items.
- A one-dimensional
array is a structured data type that is provided to help programmers
code operations such as this with ease.
|
Declaration
There are multiple ways in which to declare an
array. At a minimum, the programmer must specify the array name, upper
bound, and data type:
Dim array_name (upper_bound) As
component_type
Example: Dim grade (35) As Integer
Component_type indicates what can be stored in
each element of the array.
The upper_bound is the highest valid index.
The array has upper_bound + 1 elements, because the lower_bound defaults to 0.
When specifying the upper_bound,
using a constant like SIZE
instead of a number makes it easier to change the array size: only one program
line needs to be changed to change the array size, loop limits, etc.
════════════════════════════════════════════════════════════
You can also declare an array in the following
ways:
Dim array_name As component_type
( )
Example:
Dim grade As Integer ( )
Notice that no size was declared. Before
the programmer can use such an array the size must be specified, and memory for
the array must be allocated, using the keyword New.
array_name = New component_type (upper_bound)
{ }
Example: grade = New Integer (35) { }
This can be done in a single statement, such as
Dim grade As Integer ( ) = New Integer (11) { }
Initialization
The elements in an array are initialized to the default value
for the data type of the elements in the array. The default value is 0 for
numeric primitive data type variables and False for Boolean variables.
The initializer list (between the curly braces) can contain a
comma-separated list specifying the initial values of the elements in the array.
For example,
Dim numberList As Integer ( )
numberList = New Integer ( ) {1, 2, 3, 6}
VB determines the array bounds from the initializer list.
Accessing array elements
To access a particular element in an array,
use the array name and an index.
Array_name(constant or variable)
The index can be a variable, constant, or expression of type
Long, and
indicates the location of the element that will be referenced.

Example
Dim grade (35)
As Short
Console.WriteLine (grade(ctr))
Array
grade
is of type Short -- a group of 36 memory locations, each of which contains a data item of type
Short.
Each element is accessed by its position in the group of 36.

grade(0) refers to the first element of in the group of 36.
grade(I-1) refers to the Ith element of in the group of 36.
The index must be a Long or
Long expression between 0 and
upper_bound.
Since each element is a Short it occupies two bytes.
Processing arrays
To process an array element by element, you can use a
For loop.
For ctr = 0 to 35
Console.Write
(grade(ctr) & Space(2))
Next ctr
Or
For ctr = 0 to grade.GetUpperBound(0)
Console.Write
(grade(ctr) & Space(2))
Next ctr
Method GetLowerBound returns the lowest-numbered index
value.
Method GetUpperBound returns the highest-numbered index
value.
If an application requires either processing all
elements in the array or stopping if a certain condition is detected, one
of the forms of While loops must be used.
The following example checks all students in a class to determine whether
everyone is passing. If a failing student is detected, processing can be
terminated because it has been determined that everyone is not passing.
Therefore a While loop is used.
All_Passing = True
Ctr = 0
While (Ctr <= 35) And All_Passing
If (Grade(Ctr) < 70) Then
All_Passing = False
Else
Ctr = Ctr + 1
EndIf
End While
Example
Dim studentGrade (9) As String
Sample contents after some processing:
studentGrade
|
"F"
|
|
"B"
|
|
"C"
|
|
"A"
|
|
"F"
|
|
"C"
|
|
"A"
|
|
"A"
|
|
"C"
|
|
"B"
|
studentGrade(4) = "F"
Assigns "F" to the fifth cell in the array studentGrade.
ID = 6
studentGrade(ID) = "A"
Assigns "A" to the seventh cell in the array
studentGrade.
For ID = 0 to studentGrade.GetUpperBound(0)
Console.Write(studentGrade(ID))
Next ID
The loop prints all the values in studentGrade: FBCAFCAACB
For ID = 0 to studentGrade.GetUpperBound(0)
Console.WriteLine("Student " & ID+1 & "Grade " & studentGrade(ID))
Next ID
The loop prints all the values in studentGrade in a more readable form.
ID is used as the index, but also serves as the student's identification
number.
Student 1 Grade F
Student 2 Grade B
:
:
Student 10 Grade B
Bounds checking in arrays
If an attempt is made to access an element outside of the array bounds, it
is a run-time error. i.e., Visual Basic performs bounds checking on array
subscripts.
For example, given the declaration Dim grade (35) As Integer, an attempt
to access grade(ctr) when
ctr has a value of 36 would be a run-time error.
Examples using arrays
The program below uses a For
to print the contents of the ten-element Integer
array called array.


════════════════════════════════════════════════════════════ The next program creates two
Integer arrays of 10
elements each and sets the values of the elements, using an initializer
and a For statement, and prints the array element contents in a tabular format.


════════════════════════════════════════════════════════════ The following program uses arrays to summarize the results
of data collected in a survey. The problem statement stipulates
Forty students were asked to rate the
quality of the food in the student cafeteria on a scale of 1 to 10 (10 meaning
excellent). Place the 40 responses in an integer array and determine the
frequency of each rating.
-
The task is to summarize the number of responses of
each type, i.e., 1 to 10.
-
The array
responses is a 40-element array (actually 41
elements) of the students' responses, which are randomly
generated in this simulation.
-
The ten-element array (actually 11 elements)
frequency
is used to count the number of occurrences of each response.
-
The code segment randomly
fills the response array with simulated poll responses.



The program calculates and prints the frequency of each response.
The second For
loop takes each response from responses
and increments one of the ten frequency counters--frequency(1) to
frequency(10).
The statement frequency(responses(answer)) += 1
increments the appropriate frequency counter depending on the value of
responses(answer).
-
For example, if
responses(answer) is 1, then
frequency(responses(answer)) += 1 is actually interpreted as
frequency(1) = frequency(1) + 1, which increments array index 1.
-
Likewise, if responses(answer) is 2, then
frequency(responses(answer)) += 1 is actually interpreted as
frequency(2) = frequency(2) + 1, which increments array index 2.
-
Finally, if responses(answer) is 6, then
frequency(responses(answer)) += 1 is actually interpreted as
frequency(6) = frequency(6) + 1, which increments array index 6.
Note that the line above could have been written
as two lines
foodRating = responses(answer)
frequency(foodRating) = frequency(foodRating) + 1
Regardless of the number of responses in the survey, only an
eleven-element array is required to summarize the results, because there are only
10 possible responses. (Notice that element 0 of the frequency array is
unused.)
Arrays in procedures
-
Arrays are automatically passed by reference, but by
convention (and for security reasons) the keyword
ByVal is used.
-
An array name actually holds a memory address, or
reference, so even when called ByVal it
actually passes a reference.
-
Remember that any changes made to an array in a procedure will change the original array.
-
Individual array elements can be passed
ByVal or ByRef.
Passing
arrays to procedures
To pass an entire array to a procedure, specify the
array name as the argument.
For example, if array hourlyTemperatures
is declared as
Dim hourlyTemperatures(24) As Integer
the call
Call modifyArray(hourlyTemperatures)
passes array hourlyTemperatures to procedure
modifyArray.
════════════════════════════════════════════════════════════
To pass an element of an array to a procedure, use the array element
(array name and index) as an
argument in the call.
For example, the call
Call passOneElement(hourlyTemperatures(5))
would pass the array element corresponding to index 5 to
passOneElement.
Receiving
arrays in procedures
For a procedure to receive an entire array through a call, the parameter list must
specify that an array will be received.
For example, the
procedure header for modifyArray might be written as
Private Sub
modifyArray(ByVal receivedArray( ) As Integer)
indicating that modifyArray expects to receive an
Integer
array in parameter receivedArray.
The size of the array is not specified between the array parentheses.
════════════════════════════════════════════════════════════
For a procedure to receive an array element from a call, the procedure
declares a variable of the type passed.
For example, the procedure header for
passOneElement might be written as
Private Sub passOneElement (ByVal
arrayElement as Integer)
Variable
arrayElement would refer to
hourlyTemperatures
(5) in the call
Call passOneElement(hourlyTemperatures(5))
Example of arrays as parameters
The following program demonstrates passing an array and passing array elements to a procedure.




The procedure call
modifyArray(array1) passes a
reference to array1 to modifyArray
by value, where array1's elements are then multiplied by 2.
The call modifyElementByVal(array1(3), output) passes array element
3 to modifyElementByVal by-value where a copy of
the element is
multiplied by 2, but the result is lost when the procedure terminates.
The call modifyElementByRef(array1(3), output) passes array element
3 to modifyElementByRef by-reference where the element is
multiplied by 2 and the result is stored in the element itself.
Demo code available here. |