+ All Categories
Home > Documents > Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and...

Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and...

Date post: 18-Jan-2016
Category:
Upload: mercy-lloyd
View: 227 times
Download: 0 times
Share this document with a friend
Popular Tags:
44
Chapter 9 Processing Lists with Arrays
Transcript
Page 1: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Chapter 9

Processing Lists with Arrays

Page 2: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Class 9: Arrays

• Understand the concept of random numbers and how to generate random numbers

• Describe the similarities and differences between arrays and collections

• Understand and work with arrays, and use Do loops and For loops to examine array elements

• Sort, reverse, and search for elements in an array

• Find and diagnose common array errors

• Work with multidimensional arrays and arrays of objects

Page 3: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Introduction to Arrays

• Chapter 8 introduced the concept of a collection (list)• This chapter introduces the concept of an array• Lists and arrays have similarities and differences

– Both arrays and instances of the List class store multiple items having the same data type

– The size of both lists and arrays can be changed at run time• The Add and RemoveAt methods work with lists• An array's size is changed through a process called

redimensioning

Page 4: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Characteristics of Arrays

• An array stores multiple data items, each having the same data type– An array can store a list of primary data types or other

data types• An array of integers or text boxes, for example

• An array has one or more dimensions– A one-dimensional array can be thought of as a list– A two-dimensional array can be though of as a grid or

table– A Visual Basic array can have between 1 and 60

dimensions

Page 5: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Characteristics of Arrays (continued)

• The number of dimensions in an array is called the rank– A one-dimensional array has a rank of 1– A two-dimensional array has a rank of 2

• Each data item stored in an array is called an element

• An array element is referenced by a unique index value called a subscript– One subscript is used to reference elements in a one-

dimensional array– Two subscripts are used to reference elements in a two-

dimensional array

Page 6: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

The Array Class (Members)

• The Length property gets the number of elements in the array– The Length property is 1-based

• The Rank property gets the number of dimensions– A one-dimensional array has a Rank of 1

• The GetLength method gets the number of array elements in a particular dimension

• The GetUpperBound and GetLowerBound methods get the largest and smallest subscript for a dimension– These methods are 0-based– The array dimension is passed as an argument

• The Sort method sorts an array or part of an array

Page 7: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Common Array Tasks

• Arrays must be declared just as any variable must be declared

• It is possible to declare and initialize an array in the same statement

• It's possible to determine the bounds of an array

• An array's size can be changed at run time• Data must be stored and retrieved to and from

array elements

Page 8: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Declaring Arrays (Syntax)

• [Public | Friend | Private | Dim] arrayName ([size]) As dataType = initExpr– The access modifier (Public, Private, Friend)

defines the array's visibility– The identifier (name) is defined by arrayName– The optional size contains the value of the largest subscript

• The size argument is 0-based• Omit the size to declare a dynamic uninitialized array

– dataType defines the data type of the array– initExpr is used to assign initial values to the array's

elements

Page 9: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Declaring Arrays (Examples)

• Declare an uninitialized array– Dim EmptyArray() As Integer

• Declare a one-dimensional array with one element– Dim IntegerArray(0) As Integer

• Declare a one-dimensional array with four elements– Dim IntegerArray(3) As Integer

Page 10: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Initializing an Array• An array can be initialized when it is declared

– The initialization list appears in braces ({})– A comma separates each initialization value– The array must be dynamic (declared without an

initial subscript value)

• Example to declare and initialize an Integer array with four elements:Dim IntegerList() As Integer = _ {24, 12, 34, 42}

Page 11: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Declaring and Initializing Boolean and String Arrays

• Declare and initialize a Boolean arrayDim WeekDayArray() As Boolean = _

{False, False, True, True, True, True, True}

• Declare and initialize a String arrayDim MonthNames() As String = _

{"January", "February", "March", "April", "May", _

"June", "July", "August", "September", _

"October", "November", "December"}

Page 12: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining an Array's Bounds

• The GetUpperBound method gets the largest subscript for a particular dimension– It returns the largest subscript, not the number of

elements

• The GetLowerBound method gets the smallest subscript for a particular dimension

• The 0-based dimension is passed as an argument to each method– The method will throw an exception if the array

dimension does not exist

Page 13: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining an Array's Bounds (Examples)

• Get the lower and upper bound of the first array dimension for the array named MonthNames

Dim SmallestSubscript, _ LargestSubscript As Integer

SmallestSubscript = _ MonthNames.GetLowerBound(0) ' 0

LargestSubscript = _

MonthNames.GetUpperBound(0) ' 12

Page 14: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Redimensioning an Array

• An array's size is determined by the number of dimensions in the array and the number of elements in each dimension

• An array is redimensioned with the ReDim statement– Arrays must be redimensioned when the size

cannot be determined in advance

Page 15: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

The ReDim Statement (Syntax)

• ReDim [Preserve] varname(size)– The ReDim statement redimensions an array

• The ReDim statement is an executable statement

• It must appear inside of a procedure

– The optional Preserve keyword preserves the array's contents

• There are restrictions on the use of the Preserve keyword

– varname contains the name of the array to redimension

– size contains the new array size

Page 16: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Redimensioning an Array (Example)

• Declare an arrayDim IntegerList() As Integer = _ {24, 12, 34, 42}

• Redimension the array (increasing the size by one to five elements)ReDim IntegerList(4)

• Redimension the array and preserve its contentsReDim Preserve IntegerList(4)

Page 17: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Performing Assignment Statements with Arrays

• Assignment statements using arrays require a subscript– The subscript appears in parentheses after the

array name

• The data types of the left and right side of the assignment statement must be compatible

Page 18: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Performing Assignment Statements with Arrays (Example)

• Declare an array with 12 elements (subscript values from 0 to 11)Dim SalesList(11) As Double

• Store and retrieve a value from the second array element (a subscript value of 1)Dim SalesListItem As DoubleSalesList(1) = 84616.12SalesListItem = SalesList(1)

Page 19: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Figure 9-4: Storing and Retrieving

Array Values

Page 20: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Type Conversion and Arrays

• Explicit type conversion of array elements is possible• Call methods of the System.Convert class or call

the ToString method to convert an element to a string

• Convert an array element (Double) to a stringDim OutputString As StringOutputString = SalesList(1).ToString

• Convert a String to a Double and store the result in an array elementSalesList(1) = ToDouble(txtSalesAmount.Text)

Page 21: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Type Conversion and Arrays (Errors)

• Use care to apply the subscript when working with arrays

• The following statement is missing a subscript and will return the data type of the array's elements:OutputString = SalesList.ToString

• Example output:System.Double[]

Page 22: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Variables and Array Subscripts

• Variables are often used as array subscripts– Especially when using loops to examine all the

elements in an array

• Variables used as subscripts must have an integral data type

Page 23: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Variables and Array Subscripts (Example)

• Reference an array element with a variable as a subscript:Dim SubscriptValue As Integer = 1

Dim SalesListItem As Double

SalesListItem = _

SalesList(SubscriptValue)

Page 24: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Using Loops to Examine Array Elements

• Common array tasks involving loops– Calculate the total value of all array elements

using an accumulator– Calculate the minimum value stored in an array– Calculate the maximum value stored in an array– Calculate the average value of the elements in

an array

Page 25: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Figure 9-7: Using a Loop to Examine Array Elements

Page 26: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Examine an Array's Elements (Example)

• Tally the values of an array's elements. Total contains the total value

Dim Total As Double = 0.0Dim Counter As Integer = 1Do While Counter <= _ SalesList.GetUpperBound(0) Total += SalesList(Counter)Loop

Page 27: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Minimum Value of an Array Element

• First, initialize the current minimum value– Use the value of the first array element, or

– Use the largest value for the underlying data type

• Use a loop to find the current minimum value comparing the current minimum value with the current array element– Replace the current minimum value, if necessary

Page 28: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Minimum Value of an Array Element

(Example)• Find the minimum value in the array named SalesList– Note the first element is not used in the example

Dim Counter As Integer = 1Dim CurrentMinimum As Double = _ SalesList(Counter)For Counter = 1 To _ SalesList.GetUpperBound(0) If CurrentMinimum > _ SalesList(Counter) Then CurrentMinimum = SalesList(Counter) End IfNext

Page 29: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Maximum Value of an Array Element

• The process is nearly the same as finding the minimum value– The condition in the decision-making statement

is reversed– Initialize the current minimum value to the

value of the first element or the minimum value for the data type

Page 30: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Maximum Value of an Array Element (Example)

• Find the maximum value in the array named SalesList– Note the first element is not used in the example

Dim Counter As Integer = 1Dim CurrentMaximum As Double = _ SalesList(Counter)For Counter = 1 To _ SalesList.GetUpperBound(0) If CurrentMaximum < _ SalesList(Counter) Then CurrentMaximum = SalesList(Counter) End IfNext

Page 31: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Average Value of an Array's Elements

• Using an accumulator, tally the value of all array elements

• Divide the total value by the number of array elements to determine the average

Page 32: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Determining the Average Value of an Array's Elements (Example)

• Store in Average, the value of all array elements– Note the first element is not used

Dim Counter As Integer = 1

Dim Total, Average As Double

For Counter = 1 To SalesList.GetUpperBound(0)

Total += SalesList(Counter)

Next

Average = Total / SalesList.GetUpperBound(0)

Page 33: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Arrays as Function Arguments

• An array can be passed to a procedure as an argument– In the Function declaration, declare the

argument with parentheses in the same way a dynamic array is declared

• Example:Public Shared Function Total( _

ByVal argList() As Double) As Double

End Function

Page 34: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Sorting Array Elements

• Use the Sort method of the System.Array class to sort array elements

• Example:Private SampleArray() As Double = _ {6.11, 4.12, 5.88, 6.44}System.Array.Sort(SampleArray)

• Example output:4.12 5.88 6.11, 6.44

Page 35: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Sorting Array Elements (continued)

• It's possible to sort part of an array

• Call the Sort method with additional arguments– The first argument contains the array to sort– The second argument contains the starting array

subscript– The third argument contains the number of

elements to sort

Page 36: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Sorting Array Elements (continued)

• Sort the array named SampleArray excluding the first elementPrivate SampleArray() As Double = _ {0, 6.11, 4.12, 5.88, 6.44}

System.Array.Sort(SampleArray, 1, _

SampleArray.GetUpperBound(0))

Page 37: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Reversing Array Elements

• Calling the Reverse method of the System.Array class reverses the order of the array elements

• It's possible to reverse all array elements or a range of elements– The arguments to the Reverse method are the

same as the arguments to the Sort method

• Example:– System.Array.Reverse(SampleArray)

Page 38: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Introduction to Searching

• It's often necessary to search for an array element

• Searching can be performed in different ways– A sequential search examines each element, in

order, until the element is found or the entire array has been searched

– A sorted array can be efficiently searched using a binary search

Page 39: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Using a Sequential Search

• A sequential search works on an unordered (unsorted) array

• Each element is examined sequentially using a loop– If the item is found, the loop exits– If all elements are examined, the item is not

found and the loop exits

Page 40: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Using a Sequential Search (Example)

• Search for a value in the array named DataArray

Dim Counter As IntegerDim SearchValue As IntegerDim Found As Boolean = FalseSearchValue = ToInt32(txtSearch.Text)For Counter = 0 To DataArray.GetUpperBound(0) If SearchValue = DataArray(Counter) Then Found = True Exit For End IfNext

Page 41: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Using a Binary Search

• If an array is sorted, a binary search can be used to find an array element– The performance is much better than a sequential

search

• Algorithm– Compare the search value with the value of the item

in the middle of the array– Divide the array in half based on the results– Continue the previous two steps until the desired

array element is found

Page 42: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Figure 9-10: Comparisons Using the Binary Search

Page 43: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Common Array Errors

• Errors are commonly made when processing arrays

• Forgetting to include a subscriptDim DemoArray(12) As Integer

DemoArray = 100

• Subscript out of range errorsDim DemoArray(10) As Integer

DemoArray(20) = 100

DemoArray(–1) = 100

Page 44: Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.

Common Array Errors (continued)

• Forgetting to examine the first or last array elementDim DemoArray(12) As Double

Dim Total As Double

For Counter = 1 to _

DemoArray.GetUpperBound(0)

Total += DemoArray(Counter)

Next


Recommended