Date post: | 26-Mar-2015 |
Category: |
Documents |
Upload: | zoe-shepherd |
View: | 232 times |
Download: | 4 times |
Chapter 8, Slide 1 Starting Out with Visual Basic 3rd Edition
Chapter 8
Arrays, Timers, and More
Chapter 8, Slide 2 Starting Out with Visual Basic 3rd Edition
Chapter 8Introduction
Chapter 8, Slide 3 Starting Out with Visual Basic 3rd Edition
Chapter 8 Topics 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
Chapter 8, Slide 4 Starting Out with Visual Basic 3rd Edition
Section 8.1Arrays
An Array Is Like a Group of Variables With One Name
You Store and Work With Values in an Array by Using a Subscript
Chapter 8, Slide 5 Starting Out with Visual Basic 3rd Edition
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
Chapter 8, Slide 6 Starting Out with Visual Basic 3rd Edition
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
Chapter 8, Slide 7 Starting Out with Visual Basic 3rd Edition
Declaring an Array
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
Dim ArrayName(UpperSubscript) As DataType
Chapter 8, Slide 8 Starting Out with Visual Basic 3rd Edition
Array Declaration Example
hours(0) hours(1) hours(2) hours(3) hours(4) hours(5)
Dim hours(5) As Integer
Note that 6 elements are available when an array with an uppersubscript of 5 is declared
Each element is an integer type
Chapter 8, Slide 9 Starting Out with Visual Basic 3rd Edition
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)
Chapter 8, Slide 10 Starting Out with Visual Basic 3rd Edition
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}
Chapter 8, Slide 11 Starting Out with Visual Basic 3rd Edition
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 = 100Dim array(UPPER_SUB) As Integer
Chapter 8, Slide 12 Starting Out with Visual Basic 3rd Edition
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) = 100numbers(1) = 200numbers(2) = 300numbers(3) = 400numbers(4) = 500numbers(5) = 600
pay = hours(3) * rate
tallies(0) += 1
MessageBox.Show(grossPay(5).ToString)
Chapter 8, Slide 13 Starting Out with Visual Basic 3rd Edition
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 IntegerFor count = 0 To 9
series(count) = CInt(InputBox("Enter a number"))Next count
Dim count As IntegerFor count = 0 To 999
names(count) = ""Next count
Chapter 8, Slide 14 Starting Out with Visual Basic 3rd Edition
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
Chapter 8, Slide 15 Starting Out with Visual Basic 3rd Edition
For Each … Next Statement This statement is similar to a For…Next 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 StringFor Each strName In employees
MessageBox.Show(strName)Next name
Chapter 8, Slide 16 Starting Out with Visual Basic 3rd Edition
Section 8.2More 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
Chapter 8, Slide 17 Starting Out with Visual Basic 3rd Edition
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
Chapter 8, Slide 18 Starting Out with Visual Basic 3rd Edition
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 arrayDim intTotal As Integer = 0 'Initialize accumulatorDim intCount as Integer ‘Declare loop counter
‘Find total of all values held in arrayFor intCount = 0 To (intUnits.Length – 1)
intTotal += intUnits(intCount)Next intCount
Chapter 8, Slide 19 Starting Out with Visual Basic 3rd Edition
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 arrayDim intTotal As Integer = 0 'Initialize accumulatorDim dblAverage as Double ‘Declare average varDim intCount as Integer ‘Declare loop counter
‘Find total of all values held in arrayFor intCount = 0 To (intUnits.Length – 1)
intTotal += intUnits(intCount)Next intCount
‘Use floating-point division to compute averagedblAverage = intTotal / intUnits.Length
Chapter 8, Slide 20 Starting Out with Visual Basic 3rd Edition
Find 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 IntegerDim intCount as IntegerDim intHighest as Integer = intNumbers(0)
For intCount = 1 To (intNumbers.Length - 1)If intNumbers(intCount) > intHighest Then
intHighest = intNumbers(intCount)End If
Next intCount
Chapter 8, Slide 21 Starting Out with Visual Basic 3rd Edition
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 100newValues(intCount) = oldValues(intCount)
Next intCount
Chapter 8, Slide 22 Starting Out with Visual Basic 3rd Edition
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
Chapter 8, Slide 23 Starting Out with Visual Basic 3rd Edition
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 StringDim addresses(4) As String
Names(0) Names(1) Names(2) Names(3) Names(4)
Addresses(0) Addresses(1) Addresses(2) Addresses(3) Addresses(4)
Person #1 Person #2 Person #3 Person #4 Person #5
Chapter 8, Slide 24 Starting Out with Visual Basic 3rd Edition
Parallel Arrays Processing
Dim names(4) As StringDim addresses(4) As String
For intCount = 0 To 4lstPeople.Items.Add("Name: " & names(intCount) & _
" Address: " & addresses(intCount))Next intCount
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
Chapter 8, Slide 25 Starting Out with Visual Basic 3rd Edition
Array & List Box Parallel Processing
' Initialize a List Box with nameslstPeople.Items.Add("Jean James") ' Subscript 0lstPeople.Items.Add("Kevin Smith") ' Subscript 1lstPeople.Items.Add("Joe Harrison") ' Subscript 2' Initialize an Array with corresponding phone numbersphoneNumbers(0) = "555-2987"phoneNumbers(1) = "555-5656"phoneNumbers(2) = "555-8897"
' Process a selectionIf lstPeople.SelectedIndex > -1 And _
lstPeople.SelectedIndex < phoneNumbers.Length ThenMessageBox.Show(phoneNumbers(lstPeople.SelectedIndex))
ElseMessageBox.Show("That is not a valid selection.")
End If
A list box selection used as an array index
Chapter 8, Slide 26 Starting Out with Visual Basic 3rd Edition
Searching Arrays, The Search Find 1st instance of value 100 in array scores intPosition gives position of this value
Dim blnFound as Boolean = FalseDim intCount as Integer = 0Dim intPosition as Integer = -1
‘ Search for a 100 in the arrayDo While Not blnFound And intCount < scores.Length
If scores(intCount) = 100 ThenblnFound = TrueintPosition = intCount
End IfintCount += 1Loop
Chapter 8, Slide 27 Starting Out with Visual Basic 3rd Edition
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")
ElseMessageBox.Show( _
"You didn’t score a 100, but keep trying!", _"Test Results")
End If
Chapter 8, Slide 28 Starting Out with Visual Basic 3rd Edition
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)
Chapter 8, Slide 29 Starting Out with Visual Basic 3rd Edition
Resizing an Array
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
ReDim [Preserve] Arrayname(UpperSubscript)
Chapter 8, Slide 30 Starting Out with Visual Basic 3rd Edition
Resizing Example
Dim scores() As Single ' Declared with no elementsDim numScores as Integer
' Obtain number of elements from the usernumScores = CInt(InputBox("Enter number of test scores"))If numScores > 0 Then
ReDim scores(numScores - 1)Else
MessageBox.Show("You must enter 1 or greater.")End If
Array scores declared with no elements User prompted for number of elements ReDim resizes array based on user input
Chapter 8, Slide 31 Starting Out with Visual Basic 3rd Edition
Section 8.3Sub 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
This Allows You to Write Sub Procedures and Functions That Perform General Operations With Arrays
Chapter 8, Slide 32 Starting Out with Visual Basic 3rd Edition
Passing Arrays as Arguments
Dim numbers() As Integer = { 2, 4, 7, 9, 8, 12, 10 }DisplaySum(numbers)
Sub DisplaySum(ByVal intArray() As Integer)Dim total As Integer = 0 ' AccumulatorDim count As Integer ' Loop counterFor count = 0 To (intArray.Length - 1)
total += intArray(count)NextMessageBox.Show(“Total is " & total.ToString)
End Sub
Array numbers passed to DisplaySum sub
Sub computes/shows sum of array elements Can pass any integer array to DisplaySum
Chapter 8, Slide 33 Starting Out with Visual Basic 3rd Edition
Passing Arrays: ByVal and ByRef When passing an array ByVal
• Calling procedure “sees” sub procedure changes to element values◦ Simple variables don’t 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
Chapter 8, Slide 34 Starting Out with Visual Basic 3rd Edition
Passing Arrays Example
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 = newArrayEnd Sub
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
Chapter 8, Slide 35 Starting Out with Visual Basic 3rd Edition
An Array Returned From a Function
Function GetNames() As String()' Get four names from user' Return them as an array of strings.Dim strNames(3) As StringDim strInput As StringDim count As IntegerFor count = 0 To 3
strInput = InputBox("Enter name " & _(count + 1).ToString)
strNames(count) = strInputNextReturn strNames
End Function
Return type String() indicates an array of strings Thus the function result must be assigned to an
array of strings
Chapter 8, Slide 36 Starting Out with Visual Basic 3rd Edition
Section 8.4Multidimensional Arrays
You May Create Arrays With More Than Two Subscripts to Hold Complex Sets of Data
Chapter 8, Slide 37 Starting Out with Visual Basic 3rd Edition
A Two Dimensional Array Picture
Column 0 Column 1 Column 2 Column 3
Row 0
Row 1
Row 2
Thus far, arrays have been one-dimensional However, arrays can also be two-dimensional Picture a two-dimensional array like a
spreadsheet with rows and columns
Chapter 8, Slide 38 Starting Out with Visual Basic 3rd Edition
Two Dimensional Array Syntax
UpperRow and UpperColumn give the highest subscript for the row and column indices of the array
The array on the previous slide could be:
• Defines three rows; 0, 1, and 2• And four columns; 0, 1, 2, and 3
Dim ArrayName(UpperRow, UpperColumn) As DataType
Dim array(2,3) As Single
Chapter 8, Slide 39 Starting Out with Visual Basic 3rd Edition
Two Dimensional Array Subscripts
Dim array(2,3) As Single
Column 0 Column 1 Column 2 Column 3
Row 0 array(0,0) array(0,1) array(0,2) array(0,3)
Row 1 array(1,0) array(1,1) array(1,2) array(1,3)
Row 2 array(2,0) array(2,1) array(2,2) array(2,3)
Chapter 8, Slide 40 Starting Out with Visual Basic 3rd Edition
Nested Loops And Two Dimensions
For row = 0 To 2For col = 0 To 3
num = Val(InputBox("Enter a score."))scores(row, col) = num
Next colNext row
Nested loops are often used in processing two-dimensional arrays
In the example, a nested loop is used to insert a value into every element of array scores
Chapter 8, Slide 41 Starting Out with Visual Basic 3rd Edition
Implicit Sizing and Initialization
Can be used with multi-dimensional arrays:
Row 0 values Row 1 values Row 2 values
Initializes array numberswith the following values
Dim numbers(,) As Integer = _{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }
Col 0 Col 1 Col 2
Row 0 1 2 3
Row 1 4 5 6
Row 2 7 8 9
Chapter 8, Slide 42 Starting Out with Visual Basic 3rd Edition
For Each Loop With Two Dimensions
A For Each Loop will process all elements of an array without requiring nested loops
The example below computes the sum of all elements
Total has the value 45 when loop is complete
Dim numbers(,) As Integer = {{1, 2, 3}, _ {4, 5, 6}, _ {7, 8, 9}}
For Each element In numberstotal += element
Next element
Chapter 8, Slide 43 Starting Out with Visual Basic 3rd Edition
Sum Two-Dimensional Array Columns
' Process each column in turnFor col = 0 To 2
' Initialize column accumulatortotal = 0' Sum the column values from each rowFor row = 0 To 4
total += values(row, col)Next row
' Display the sum of the column.MessageBox.Show("Sum of column " & _
col.ToString & " is " & total.ToString)Next col
Outer loop controls column subscript Inner loop controls row subscript
Chapter 8, Slide 44 Starting Out with Visual Basic 3rd Edition
Three-Dimensional Arrays & Beyond
VB allows arrays of up to 32 dimensions Beyond three dimensions, they are difficult to
visualize But, all one needs to do is to be consistent in
the use of the different indices
Chapter 8, Slide 45 Starting Out with Visual Basic 3rd Edition
Section 8.5Enabled Property, Timer
Control, and Splash Screens
You Disable Controls by Setting Their Enabled Property to False
The Timer Control Allows Your Application to Execute a Procedure at Regular Time Intervals
Splash Screens Are Forms That Appear As an Application Begins Executing
Chapter 8, Slide 46 Starting Out with Visual Basic 3rd Edition
Enabled Property Most controls have an Enabled property If this Boolean property is set to false the
control is disabled meaning the control:• Cannot receive the focus• Cannot respond to user generated events• Will appear dimmed, or grayed out
Default value for this property is true May be set in code when needed as shown:
btnExample.Enabled = False
Chapter 8, Slide 47 Starting Out with Visual Basic 3rd Edition
Timer Control A Timer control generates Tick events
• Double-click on Timer tool in Toolbox to add• Appears in component tray• Standard prefix is tmr
Can perform a process at regular intervals by coding the process in a Tick event procedure
Two important properties• Enabled must be true to generate Tick events• Interval (milliseconds) decides tick frequency◦ Interval of 1000 causes 1 timer tick per second
Tutorial 8-5 demonstrates the Timer control
Chapter 8, Slide 48 Starting Out with Visual Basic 3rd Edition
Splash Screens
A form, often with an application logo, that is displayed while an application is loading
A splash screen usually:• Has Topmost property set to True so it is
displayed over the forms of other applications• Disappears shortly by using a Timer• Is modeless so the application continues to
load while the splash screen is displayed Tutorial 8-6 demonstrates a splash screen
Chapter 8, Slide 49 Starting Out with Visual Basic 3rd Edition
Section 8.6Anchoring and Docking
Controls
Controls Have Two Properties, Anchor and Dock, That Allow You to Determine the Control’s Position on the Form When the Form
Is Resized at Run Time
Chapter 8, Slide 50 Starting Out with Visual Basic 3rd Edition
Anchor Property Anchor - a property of various form controls A control anchored to a form edge keeps
the same distance to the form edge Controls may be anchored to any, all, or
none of the right, left, top, or bottom edges• Default is to anchor to top and left edges• Can just as easily anchor to bottom right• If anchoring to opposing sides, control is
resized when form is resized• Anchoring to all 4 sides causes control to be
resized proportionally to form
Chapter 8, Slide 51 Starting Out with Visual Basic 3rd Edition
Dock Property Dock - a property of various form controls A control docked to a form edge is placed
directly against the form edge Controls may be docked to
• Any one form edge but not more than one• No edge or not docked (the default)
Length or width of docked control changes to match length or width of the form edge
Chapter 8, Slide 52 Starting Out with Visual Basic 3rd Edition
Section 8.7Random Numbers
Visual Basic Provides the Tools to Generate Random Numbers
Chapter 8, Slide 53 Starting Out with Visual Basic 3rd Edition
Initial Random Number Generation
Often used for games and simulations A Random class provides methods and
properties to work with random numbers May supply a seed number as below causing
same sequence of numbers to be generated
Leave the argument blank to omit the seed• VB then uses its default random number seed• Sequence not repeated if seed omitted
Randomize [Number]
Chapter 8, Slide 54 Starting Out with Visual Basic 3rd Edition
Generating More Random Numbers
To get next random number in sequence
Repeatedly use a statement like the above to generate additional random numbers
randomNumber = Rnd
Chapter 8, Slide 55 Starting Out with Visual Basic 3rd Edition
Random Numbers in a Range
Rnd creates random numbers in the range of 0.0 to 1.0
Can scale these to a selected range of integer numbers needed in your program:
Where LowerNumber and UpperNumber are the lowest and highest numbers permitted
Tutorial 8-7 shows an interesting use of random numbers
randomNumber = Int(LowerNumber + Rnd * _(UpperNumber - LowerNumber))
Chapter 8, Slide 56 Starting Out with Visual Basic 3rd Edition
Section 8.8Building the Demetris
Leadership Center Application
Build an application making use of arrays and a splash screen