Arrays - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

Arrays

Description:

A single dimension array is useful for storing and working with a single set of data ... tallies(0) = 1. MessageBox.Show(grossPay(5).ToString) Arrays and Loops ... – PowerPoint PPT presentation

Number of Views:86
Avg rating:3.0/5.0
Slides: 35
Provided by: cit62
Category:
Tags: arrays | tallies

less

Transcript and Presenter's Notes

Title: Arrays


1
Chapter
8
  • Arrays

2
Introduction
  • Arrays are like groups of variables that allow
    you to store sets of similar data
  • A single dimension array is useful for storing
    and working with a single set of data
  • A multidimensional array can be used to store and
    work with multiple sets of data
  • Array programming techniques covered
  • Summing and averaging all the elements in an
    array
  • Summing all the columns in a two-dimensional
    array
  • Searching an array for a specific value
  • Using parallel arrays

3
Array Characteristics
  • An array stores multiple values of same type
  • Like a group of variables with a single name
  • For example, the days of the week would be
  • a set of 7 string variables
  • maximum length of 9 characters
  • All variables within an array are called elements
    and must be of the same data type
  • You access the elements in an array through a
    subscript

4
Subscript Characteristics
  • A subscript, also known as an index, is a number
    that identifies a specific element within an
    array
  • Subscript numbering works like the index for a
    list box
  • Subscript numbering begins at 0
  • 1st element in an array is always subscript 0
  • Last element is total number of elements - 1

5
Declaring an Array
Dim ArrayName(UpperSubscript) As DataType
  • ArrayName is the variable name of the array
  • UpperSubscript is the value of the array's
    highest subscript
  • Must be a positive whole number
  • DataType may be any valid Visual Basic data type
  • VB knows an array is declared when name is
    followed by number of elements in parens

6
Array Declaration Example
Dim hours(5) As Integer
hours(0) hours(1) hours(2) hours(3) hours(4)
hours(5)
  • Note that 6 elements are available when an array
    with an uppersubscript of 5 is declared
  • Each element is an integer type

7
Default Initialization
  • All elements of an Integer array are initialized
    to zero
  • Same initialization as an integer variable
  • Each array element is initialized exactly the
    same as a simple variable of that data type
  • A Single is initializled to zero (0.0)
  • A String is initialized to nothing (empty string)

8
Implicit Array Sizing Initialization
  • An array can be initialized when declared
  • Example
  • This array is implicitly sized
  • Upper subscript value is left blank
  • Number of elements implied from initialization
  • Upper subscript of 5 implied by this example
  • A 6 element array is declared
  • Elements are assigned the values shown

Dim numbers() As Integer 2, 4, 5, 7, 9, 12
9
Named Constant as Upper Subscript
  • A named constant may be used as an array's
    highest subscript instead of a number
  • A common use for named constants
  • Highest subscript is often used multiple times
  • If highest subscript changes, use of a named
    constant allows it to be changed in one place

Const UPPER_SUB As Integer 100 Dim
array(UPPER_SUB) As Integer
10
Working With Array Elements
  • Simply include the subscript to use an array
    element like an ordinary variable
  • numbers(2) refers to 3rd element of array

numbers(0) 100 numbers(1) 200 numbers(2)
300 numbers(3) 400 numbers(4) 500 numbers(5)
600
pay hours(3) rate tallies(0)
1 MessageBox.Show(grossPay(5).ToString)
11
Arrays and Loops
  • Loops are frequently used to process arrays
  • Use a loop to prompt for 10 values
  • Use a loop to reset values in the names array to
    an empty string

Dim count As Integer For count 0 To
9 series(count) CInt(InputBox("Enter a
number")) Next count
Dim count As Integer For count 0 To
999 names(count) "" Next count
12
Array Bounds Checking
  • Visual Basic checks each subscript value of each
    array reference used at run time
  • A subscript is invalid if it is
  • Negative
  • Greater than the UpperSubscript declared
  • An invalid subscript causes VB to throw an
    exception
  • Bounds checking is not done at design time

13
For Each Next Statement
  • This statement is similar to a ForNext
  • Iterates for each element in the array
  • strName assigned value of next array element at
    each iteration
  • Tutorial 8-1 demonstrates array processing

Dim employees As String() "Jim", "Sally",
_ "Henry", "Jean", "Renee" Dim strName As
String For Each strName In employees MessageBox.S
how(strName) Next name
14
8.2
  • More About Array Processing

There Are Many Uses of Arrays and Many
Programming Techniques That Involve Them For
Example, Arrays Are Used to Total Values or
Search for Data
15
Determining Number of Elements
  • Arrays have a Length property that holds the
    number of elements in the array
  • Note that length is number of array elements, not
    the upper subscript of the array
  • Length property always 1 greater than the upper
    subscript

Dim values(25) As Integer For count 0 to
(values.Length 1) MessageBox.Show(values(count).
ToString) Next count
16
Total the Values in an Array
  • Variable to hold sum (intTotal)is initialized to
    zero prior to loop
  • Iterate over all elements, adding each element to
    intTotal

Dim intUnits(24) as Integer Declare array Dim
intTotal As Integer 0 'Initialize
accumulator Dim intCount as Integer Declare loop
counter Find total of all values held in
array For intCount 0 To (intUnits.Length
1) intTotal intUnits(intCount) Next intCount
17
Average the Values in an Array
  • Similar to previous example but then divides
    total by number of elements to get average

Dim intUnits(24) as Integer Declare array Dim
intTotal As Integer 0 'Initialize
accumulator Dim dblAverage as Double Declare
average var Dim intCount as Integer Declare loop
counter Find total of all values held in
array For intCount 0 To (intUnits.Length
1) intTotal intUnits(intCount) Next
intCount Use floating-point division to compute
average dblAverage intTotal / intUnits.Length
18
Highest Lowest Array Values
  • Pick first element as the highest
  • Search rest of array for higher values
  • If a higher value is located, save the value
  • Use similar logic to find lowest value

Dim intNumbers(24) as Integer Dim intCount as
Integer Dim intHighest as Integer
intNumbers(0) For intCount 1 To
(intNumbers.Length - 1) If intNumbers(intCount)
gt intHighest Then intHighest
intNumbers(intCount) End If Next intCount
19
Example
  • Sales Data

20
Copy Values in One Array to Another
  • Done by copying elements one at a time
  • Note that this cannot be done by a simple
    assignment newValues oldValues
  • Causes newValues variable to reference the same
    memory location as oldValues
  • Thus any change to oldValues will affect
    newValues and vice versa

For intCount 0 To 100 newValues(intCount)
oldValues(intCount) Next intCount
21
Parallel Arrays
  • Sometimes useful to store related data in two or
    more arrays called parallel arrays
  • Causes the ith element of one array to be related
    to the ith element of another
  • Allows related data to be accessed using the same
    subscript on both arrays

22
Parallel Arrays Example
  • Assume the following array declarations
  • Element 1 refers to the same person with name in
    one array and address in the other

Dim names(4) As String Dim addresses(4) As String
Names(0) Names(1) Names(2)
Names(3) Names(4)
Person 1 Person 2 Person 3 Person 4 Person 5
Addresses(0) Addresses(1) Addresses(2)
Addresses(3) Addresses(4)
23
Parallel Arrays Processing
  • Use parallel array processing to add name and
    address of each person to a list box
  • Tutorial 8-2 has an example of parallel arrays
  • Pizza Payroll

Dim names(4) As String Dim addresses(4) As
String For intCount 0 To 4 lstPeople.Items.Add
("Name " names(intCount) _ " Address "
addresses(intCount)) Next intCount
24
Array List Box Parallel Processing
  • A list box selection used as an array index

' Initialize a List Box with names lstPeople.Items
.Add("Jean James") ' Subscript 0 lstPeople.Items.A
dd("Kevin Smith") ' Subscript 1 lstPeople.Items.Ad
d("Joe Harrison") ' Subscript 2 ' Initialize an
Array with corresponding phone numbers phoneNumber
s(0) "555-2987" phoneNumbers(1)
"555-5656" phoneNumbers(2) "555-8897" '
Process a selection If lstPeople.SelectedIndex gt
-1 And _ lstPeople.SelectedIndex lt
phoneNumbers.Length Then MessageBox.Show(phoneNum
bers(lstPeople.SelectedIndex)) Else MessageBox.Sh
ow("That is not a valid selection.") End If
25
Searching Arrays, The Search
  • Find 1st instance of value 100 in array scores
  • intPosition gives position of this value

Dim blnFound as Boolean False Dim intCount as
Integer 0 Dim intPosition as Integer -1
Search for a 100 in the array Do While Not
blnFound And intCount lt scores.Length If
scores(intCount) 100 Then blnFound
True intPosition intCount End If intCount
1 Loop
26
Searching Arrays, The Result
  • Indicates whether the value was found
  • If found, position is given as a test number

' Was 100 found in the array? If blnFound
Then MessageBox.Show( _ "Congratulations! You
made a 100 on test " _ (intPosition
1).ToString, "Test Results") Else MessageBox.Show
( _ "You didnt score a 100, but keep trying!",
_ "Test Results") End If
27
Sorting an Array
  • Arrays have a Sort method
  • Arranges elements in ascending order (lowest to
    highest)
  • Sorted so that numbers 1, 3, 6, 7, 12
  • Sorted so that names Alan, Bill, Kim, Sue

Dim numbers() As Integer 7, 12, 1, 6, 3
Array.Sort(numbers) Dim names() As String
"Sue", "Kim", _ "Alan", "Bill"
Array.Sort(names)
28
Resizing an Array
ReDim Preserve Arrayname(UpperSubscript)
  • ReDim is a new keyword
  • If Preserve is specified, the existing contents
    of the array are preserved
  • Arrayname names the existing array
  • UpperSubscript specifies the new highest
    subscript value
  • Can declare an array with no subscript and state
    number of elements later with ReDim

29
Resizing Example
  • Array scores declared with no elements
  • User prompted for number of elements
  • ReDim resizes array based on user input

Dim scores() As Single ' Declared with no
elements Dim numScores as Integer ' Obtain
number of elements from the user numScores
CInt(InputBox("Enter number of test scores")) If
numScores gt 0 Then ReDim scores(numScores -
1) Else MessageBox.Show("You must enter 1 or
greater.") End If
30
8.3
  • Sub Procedures and Functions That Work With
    Arrays

You May Pass Arrays As Arguments to Sub
Procedures and Functions You May Also Return an
Array From a Function
31
Passing Arrays as Arguments
  • Array numbers passed to DisplaySum sub
  • Sub computes/shows sum of array elements
  • Can pass any integer array to DisplaySum

Dim numbers() As Integer 2, 4, 7, 9, 8, 12,
10 DisplaySum(numbers) Sub DisplaySum(ByVal
intArray() As Integer) Dim total As Integer 0
' Accumulator Dim count As Integer ' Loop
counter For count 0 To (intArray.Length -
1) total intArray(count) Next MessageBox.Sh
ow(Total is " total.ToString) End Sub
32
Passing Arrays ByVal and ByRef
  • When passing an array ByVal
  • Calling procedure sees sub procedure changes to
    element values
  • Simple variables dont work this way
  • If sub assigns array argument to another array,
    no effect on array in calling procedure
  • When passing an array ByRef
  • Calling procedure sees sub procedure changes to
    element values
  • If sub assigns array argument to another array,
    calling procedure array values affected

33
Passing Arrays Example
  • After ResetValues procedure executes, numbers
    array still contains 1, 2, 3, 4, 5
  • If array passed ByRef, numbers array will contain
    0, 0, 0, 0, 0 after procedure runs

Dim numbers() As Integer 1, 2, 3, 4, 5
ResetValues(numbers) Sub ResetValues(ByVal
intArray() As Integer) Dim newArray() As Integer
0, 0, 0, 0, 0 intArray newArray End Sub
34
An Array Returned From a Function
  • Return type String() indicates an array of
    strings
  • Thus the function result must be assigned to an
    array of strings

Function GetNames() As String() ' Get four names
from user ' Return them as an array of
strings. Dim strNames(3) As String Dim strInput
As String Dim count As Integer For count 0 To
3 strInput InputBox("Enter name "
_ (count 1).ToString) strNames(count)
strInput Next Return strNames End Function
Write a Comment
User Comments (0)
About PowerShow.com