Chapter 8 - Arrays, Timers, and Random Numbers

advertisement
Chapter 8
Arrays, Timers, and More
Starting Out with Visual Basic .NET 2nd Edition
8.1
Introduction
Starting Out with Visual Basic .NET 2nd Edition
Chapter 8 Topics
• Arrays are like groups of variables that allow you
to store sets of data
• A one dimensional 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
Starting Out with Visual Basic .NET 2nd Edition
8.2
Arrays
An Array Is Like a Group of Variables
With One Name
You Store and Work With Values in an
Array by Using a Subscript
Starting Out with Visual Basic .NET 2nd Edition
Array Characteristics
• An array is a like group of variables with a
single name
• All of the variables within an array are
called elements and are of the same data
type
• You access the individual variables in an
array through a subscript
Starting Out with Visual Basic .NET 2nd Edition
Subscript Characteristics
• A subscript, also known as an index, is a
number that identifies a specific element
within an array
• Subscript numbering begins at 0, so the
subscript of the first element in an array is 0
• The subscript of the last element in an array
is one less than the total number of elements
Starting Out with Visual Basic .NET 2nd Edition
Declaring an Array
Dim ArrayName(UpperSubscript) As DataType
• ArrayName is the name of the array
• UpperSubscript is the value of the array's
highest subscript
• It must be a positive whole number
• DataType is a Visual Basic .NET data type
Starting Out with Visual Basic .NET 2nd Edition
Example of an Array
Dim hours(5) As Integer
hours(0) hours(1) hours(2) hours(3) hours(4) hours(5)
Starting Out with Visual Basic .NET 2nd Edition
Default Initialization
• All of the elements of an Integer array are
initialized with the same value as a normal
integer, zero (0)
• Same for other types of arrays
• Float, zero (0.0)
• String, Nothing
Starting Out with Visual Basic .NET 2nd Edition
Explicit Array Initialization
• Example:
Dim numbers() As Integer = {2, 4, 5, 7, 9, 12}
• No upper subscript value is given
• Visual Basic .NET will automatically make
the array long enough to hold the values
Starting Out with Visual Basic .NET 2nd Edition
Named Constant As Array's
Highest Subscript Value
• In place of a whole number, a named
constant may be used as an array's highest
subscript:
Const upperSub As Integer = 100
Dim array(upperSub) As Integer
Starting Out with Visual Basic .NET 2nd Edition
Working With Array Elements
• An Array element (e.g., numbers(2)) is used
just like an ordinary variable:
numbers(0)
numbers(1)
numbers(2)
numbers(3)
numbers(4)
numbers(5)
=
=
=
=
=
=
100
200
300
400
500
600
pay = hours(3) * rate
tallies(0) += 1
MessageBox.Show(grossPay(5).ToString)
Starting Out with Visual Basic .NET 2nd Edition
Arrays and Loops
• Frequently, arrays will be processed in loops
Dim series(9) As Double
Dim count As Integer
For count = 0 To 9
series(count) = Val(InputBox("Enter a number."))
Next count
Dim names(999) As String
Dim count As Integer
For count = 0 To 999
names(count) = ""
Next count
Starting Out with Visual Basic .NET 2nd Edition
Array Bounds Checking
• Visual Basic .NET will check each subscript
value of each array reference used at run time
• If a subscript is used that is either negative or
greater than the highest allowed, a dialog box
will appear giving the option of Debugging or
Stopping the application
• (Note that no bounds checking is done at
design time)
Starting Out with Visual Basic .NET 2nd Edition
For Each … Next Statement
• This statement is similar to a For…Next
Dim employees As String() = {"Jim", "Sally", _
"Henry", "Jean", "Renee" }
Dim name As String
For Each name In employees
MessageBox.Show(name)
Next name
'above is an alternative to:
Dim i As Integer
For i = 0 To 4
MessageBox.Show(employees(i))
Next i
Starting Out with Visual Basic .NET 2nd Edition
8.3
More About Array Processing
There Are Many Uses of Arrays and Many Programming
Techniques That Involve Them
Arrays May Be Used to Total Values and Search for Data
Related Information May Be Stored in Multiple Parallel Arrays
In Addition, Arrays May Be Resized at Run Time
Starting Out with Visual Basic .NET 2nd Edition
Determining the Number of
Elements in an Array
• Arrays have a Length property that holds the
number of elements in the array
Dim values(25) As Integer
For count = 0 to (values.Length – 1)
MessageBox.Show(values(count).ToString)
Next count
• Note that the length is the number of elements
in the array, not the largest subscript
Starting Out with Visual Basic .NET 2nd Edition
How to Total the Values in an Array
• The values are summed up in a variable that
is initialized to zero beforehand:
Dim units() As Integer = {2, 4, 5, 10}
Dim total As Integer = 0 ' Initialize accumulator
For count = 0 To (units.Length – 1)
total += units(count)
Next count
' Total now equals 21
Starting Out with Visual Basic .NET 2nd Edition
Getting the Average of the
Values in a Numeric Array
• This algorithm first totals the values, then
calculates the average:
Dim total As Integer = 0 ' Initialize accumulator
Dim average As Single
For count = 0 To (units.Length – 1)
total += units(count)
Next count
average = total / units.Length
Starting Out with Visual Basic .NET 2nd Edition
Finding the Highest and Lowest
Values in a Numeric Array
• Pick the first element as the highest, then look
through the rest of the array for even higher ones,
always saving the highest value
Dim numbers() As Integer = {2, 4, 5, 7, 9, 12}
Dim highest As Integer = numbers(0)
For count = 1 To (numbers.Length - 1)
If numbers(count) > highest Then
highest = numbers(count)
End If
Next count
• Proceed analogously to find the lowest value
Starting Out with Visual Basic .NET 2nd Edition
Copying One Array's
Contents to Another
• This is done by copying the elements one at
a time, thusly
Dim newValues(99), oldValues(99) As Double
For count = 0 To 99
newValues(count) = oldValues(count)
Next count
• Note that newvalues = oldvalues will not
work for this use because oldvalues stores a
reference to the array (stores the location of
the elements contained inside)
Starting Out with Visual Basic .NET 2nd Edition
Parallel Arrays
• Sometimes it is useful to store related data
in two or more arrays
• Hence the ith element of one array is related to
the ith element of another
• Then the program can access this related
information by using the same subscript on
both arrays
Dim names(4) As String
Dim addresses(4) As String
Starting Out with Visual Basic .NET 2nd Edition
Parallel Arrays Example
Dim names(4) As String
Dim addresses(4) As String
For count = 0 To 4
lstPeople.Items.Add( "Name: " & names(count) & _
" Address: " & addresses(count))
Next count
Starting Out with Visual Basic .NET 2nd Edition
Parallelism Between Arrays and
List Boxes and Combo Boxes
Dim names(4) As String
Dim addresses(4) As String
' Initialize a List Box with names from previous slide
Dim name as String
For Each name in names
lstPeople.Items.Add(name)
Next name
' Process a selection
If lstPeople.SelectedIndex > -1 And _
lstPeople.SelectedIndex < addresses.Length Then
MessageBox.Show(addresses(lstPeople.SelectedIndex))
Else
MessageBox.Show("That is not a valid selection.")
End If
Starting Out with Visual Basic .NET 2nd Edition
Searching Arrays: Sequential Search
• This code hunts for the value 100 in the
array scores (one student’s scores)
Dim scores(4) As Integer 'initialization not shown
' Search for a 100 in the array.
Dim found As Boolean = False
Dim count As Integer = 0
Do While Not found And count < scores.Length
If scores(count) = 100 Then
found = True
position = count
End If
count += 1
Loop
Starting Out with Visual Basic .NET 2nd Edition
Searching Arrays: Acting on the Result
• This code indicates whether or not the value
was found
' Was 100 found in the array?
If found Then
MessageBox.Show( _
"Congratulations! You made a 100 on test " & _
(position + 1).ToString, "Test Results")
Else
MessageBox.Show( _
"You didn’t score a 100, but keep trying!", _
"Test Results")
End If
Starting Out with Visual Basic .NET 2nd Edition
Sorting an Array
• There is an Array.Sort method that sorts
arrays in ascending order, examples:
Dim numbers() As Integer = { 7, 12, 1, 6, 3 }
Array.Sort(numbers)
' OR
Dim names() As String = { "Sue", "Kim", "Alan", "Bill" }
Array.Sort(names)
Starting Out with Visual Basic .NET 2nd Edition
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
Starting Out with Visual Basic .NET 2nd Edition
Resizing Example
Dim scores() As Single
' Start array as having "Nothing"
' Now obtain a size from the user
numScores = Val(InputBox("Enter the number of test scores."))
If numScores > 0 Then
ReDim scores(numScores - 1)
Else
MessageBox.Show("You must enter 1 or greater.")
End If
Starting Out with Visual Basic .NET 2nd Edition
8.4
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
These Capabilities Allow You to Write Sub Procedures and
Functions That Perform General Operations With Arrays
Starting Out with Visual Basic .NET 2nd Edition
Passing Arrays as Arguments
' In the calling program
Dim numbers() As Integer = { 2, 4, 7, 9, 8, 12, 10 }
DisplaySum(numbers)
' The sub procedure
Sub DisplaySum(ByVal a() As Integer)
' Displays the sum of the elements
Dim total As Integer = 0
' Accumulator
Dim count As Integer
' Loop counter
For count = 0 To (a.Length - 1) ' << Length obtained
total += a(count)
Next
MessageBox.Show("The total is " & total.ToString)
End Sub
Starting Out with Visual Basic .NET 2nd Edition
Passing Arrays: ByVal and ByRef
• ByRef when used with an array, allows
unrestricted changes to the array
• ByVal with an array
• Does not restrict its values from being changed
from within the sub procedure
• It does prevent an array argument from be
assigned to another array (see next slide)
Starting Out with Visual Basic .NET 2nd Edition
ByRef Allows This Sort of Modification
ByVal Does Not
Dim numbers() As Integer = { 1, 2, 3, 4, 5 }
ResetValues(numbers)
Sub ResetValues(ByVal a() As Integer)
' Assign the array argument to a
' new array. Does this work?
'
NOT when using ByVal
'
It would if ByRef was used instead
Dim newArray() As Integer = {0, 0, 0, 0, 0}
a = newArray
End Sub
Starting Out with Visual Basic .NET 2nd Edition
Returning an Array From a Function
Function GetNames() As String()
' Get four names from the user
' and return them as an array
' of strings.
Dim names(3) As String
Dim input As String
Dim count As Integer
For count = 0 To 3
input = InputBox("Enter name " & _
(count + 1).ToString)
names(count) = input
Next
Return names
End Function
Starting Out with Visual Basic .NET 2nd Edition
8.5
Multidimensional Arrays
You May Create Arrays With More Than Two
Subscripts to Hold Complex Sets of Data
Starting Out with Visual Basic .NET 2nd Edition
A Two Dimensional Array Picture
Column 0
Column 1
Column 2
Column 3
Row 0
Row 1
Row 2
Starting Out with Visual Basic .NET 2nd Edition
Two Dimensional Array Syntax
Dim ArrayName(UpperRow, UpperColumn) As DataType
• UpperRow and UpperColumn give the
highest subscript for the row and column
indices of the array
• The array on the previous slide could be:
Dim array(2,3) As Single
Starting Out with Visual Basic .NET 2nd Edition
A Two Dimensional Array
Showing the 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)
Starting Out with Visual Basic .NET 2nd Edition
Two Dimensional Arrays Are
Often Processed With Nested Loops
For row = 0 To 2
For col = 0 To 3
num = Val(InputBox("Enter a score."))
scores(row, col) = num
Next col
Next row
Starting Out with Visual Basic .NET 2nd Edition
Implicit Sizing and Initialization
of Two-Dimensional Arrays
• This works for multi-dimensional arrays as
well as singly dimensioned ones:
Dim numbers(,) As Integer = {{1, 2, 3}, _
{4, 5, 6}, _
{7, 8, 9}}
Starting Out with Visual Basic .NET 2nd Edition
For Each Loops and
Multi-dimensional Arrays
• A For Each Loop will process all of the
elements in an array (without having to
have nested loops):
Dim numbers(,) As Integer = {{1, 2, 3}, _
{4, 5, 6}, _
{7, 8, 9}}
For Each element In numbers
total += element
Next element
Starting Out with Visual Basic .NET 2nd Edition
Summing the Columns of a
Two-dimensional Array
' Sum the columns.
For col = 0 To 2
' Initialize the accumulator.
total = 0
' Sum a column.
For 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
Starting Out with Visual Basic .NET 2nd Edition
Three-dimensional Arrays
and Beyond
• Visual Basic .NET allows arrays with 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
Starting Out with Visual Basic .NET 2nd Edition
8.6
Enabled Property,
Timer Control,
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
Starting Out with Visual Basic .NET 2nd Edition
Enabled Property, I
• Most controls have a Boolean property
named Enabled
• When a control’s Enabled property is set to
false, it is considered disabled, which
means:
• It cannot receive the focus and cannot respond
to events generated by the user
• In addition, it will appear dimmed, or grayed
out
Starting Out with Visual Basic .NET 2nd Edition
Enabled Property, II
• This property defaults to true (Enabled)
• Under program control this property can be
set to whatever the application logic dictates
radBlue.Enabled = False
Starting Out with Visual Basic .NET 2nd Edition
Timer Control, I
• This control, when placed on a form,
generates Tick events on a regular interval
• If there is a corresponding Tick event
procedure, it executes at these intervals
• Hence, your form can perform needed
operations on a regular interval
Starting Out with Visual Basic .NET 2nd Edition
Timer Control, II
• The timer control has two important
properties:
• Enabled - if set to True, it generates the Tick
events, otherwise not
• Interval - holds the interval between Ticks in
milliseconds (thousandths of a second)
Starting Out with Visual Basic .NET 2nd Edition
Splash Screens
• This is a form, typically with the
application's logo, that is often displayed
while an application is loading, it should:
• Have its Topmost property set to True so that it
will be seen in preference to the applications
other forms
• Disappear shortly (using a Timer)
• Be modeless
Starting Out with Visual Basic .NET 2nd Edition
8.6
Anchoring 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
Starting Out with Visual Basic .NET 2nd Edition
Anchor Property
• A control may be Anchored to two adjacent
sides of the form
• This situation will maintain the same distances
from those edges whenever the form is resized
by the user (control does not change size)
• A control may be anchored to opposite sides
of a form
• This situation will again maintain those
distances, but by changing the size of the
control
Starting Out with Visual Basic .NET 2nd Edition
Dock Property
• A control can be docked against any side of
a form
• Whenever the form is resized, the control
will change in size also to fill up the edge
that it is docked to
Starting Out with Visual Basic .NET 2nd Edition
8.7
Random Numbers
Visual Basic .NET Provides the Tools to Generate
Random Numbers and Initialize the Sequence of
Random Numbers With a Seed Value
Starting Out with Visual Basic .NET 2nd Edition
Random Number Generation, Step 1
• Random number generation is initiated with the
selection of a "seed" number
Randomize (Number)
• If you wish to repeat the same sequence of random
numbers, then use the above statement with the
same argument Number
• If you do not want to repeat a sequence, omit the
argument (it will use system time as seed)
Starting Out with Visual Basic .NET 2nd Edition
Random Number Generation, Step 2
• Obtain the next random number in the
sequence
randomNumber = Rnd()
• Repeatedly use a statement like the above to
generate additional random numbers
Starting Out with Visual Basic .NET 2nd Edition
Random Number Range
• Rnd creates random numbers in the range of
0.0 to 0.9999 (from 0 to just less than 1)
• To scale these to a range between two
integers that may be needed in your
program:
randomNumber = CInt(Int((upperbound - lowerbound + 1)
* Rnd + lowerbound)
Starting Out with Visual Basic .NET 2nd Edition
Download