Chapter 8
Download
1 / 56

Arrays, Timers, and More - PowerPoint PPT Presentation


  • 280 Views
  • Uploaded on

Chapter 8. Arrays, Timers, and More. 8.1 Introduction. 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

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Arrays, Timers, and More' - mekelle


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Chapter 8 l.jpg

Chapter 8

Arrays, Timers, and More


8 1 introduction l.jpg

8.1Introduction


Chapter 8 topics l.jpg
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


8 2 arrays l.jpg

8.2Arrays

An Array Is Like a Group of Variables With One Name

You Store and Work With Values in an Array by Using a Subscript


Array characteristics l.jpg
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


Subscript characteristics l.jpg
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


Declaring an array l.jpg
Declaring an Array

  • 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

Dim ArrayName(UpperSubscript) As DataType


Example of an array l.jpg
Example of an Array

Dim hours(5) As Integer

hours(0) hours(1) hours(2) hours(3) hours(4) hours(5)


Default initialization l.jpg
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


Explicit array initialization l.jpg
Explicit Array Initialization

  • Example:

  • No upper subscript value is given

  • Visual Basic .NET will automatically make the array long enough to hold the values

Dim numbers() As Integer = {2, 4, 5, 7, 9, 12}


Named constant as array s highest subscript value l.jpg
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


Working with array elements l.jpg
Working With Array Elements

  • An Array element (e.g., numbers(2)) is used just like an ordinary variable:

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)


Arrays and loops l.jpg
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


Array bounds checking l.jpg
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)


For each next statement l.jpg
For Each … Next Statement

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

  • This statement is similar to a For…Next


8 3 more about array processing l.jpg

8.3More 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


Determining the number of elements in an array l.jpg
Determining the Number ofElements in an Array

  • Arrays have a Length property that holds the number of elements in the array

  • Note that the length is the number of elements in the array, not the largest subscript

Dim values(25) As Integer

For count = 0 to (values.Length – 1)

MessageBox.Show(values(count).ToString)

Next count


How to total the values in an array l.jpg
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


Getting the average of the values in a numeric array l.jpg
Getting the Average of theValues 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


Finding the highest and lowest values in a numeric array l.jpg
Finding the Highest and LowestValues 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

  • Proceed analogously to find the lowest 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


Copying one array s contents to another l.jpg
Copying One Array'sContents to Another

  • This is done by copying the elements one at a time, thusly

  • 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)

Dim newValues(99), oldValues(99) As Double

For count = 0 To 99

newValues(count) = oldValues(count)

Next count


Parallel arrays l.jpg
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


Parallel arrays example l.jpg
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


Parallelism between arrays and list boxes and combo boxes l.jpg
Parallelism Between Arrays andList 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


Searching arrays sequential search l.jpg
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


Searching arrays acting on the result l.jpg
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


Sorting an array l.jpg
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)


Resizing an array l.jpg
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

ReDim [Preserve] Arrayname(UpperSubscript)


Resizing example l.jpg
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


8 4 sub procedures and functions that work with arrays l.jpg

8.4Sub 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


Passing arrays as arguments l.jpg
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


Passing arrays byval and byref l.jpg
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)


Byref allows this sort of modification byval does not l.jpg
ByRef Allows This Sort of ModificationByVal 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


Returning an array from a function l.jpg
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


8 5 multidimensional arrays l.jpg

8.5Multidimensional Arrays

You May Create Arrays With More Than Two Subscripts to Hold Complex Sets of Data


A two dimensional array picture l.jpg
A Two Dimensional Array Picture

Column 0 Column 1 Column 2 Column 3

Row 0

Row 1

Row 2


Two dimensional array syntax l.jpg
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


A two dimensional array showing the subscripts l.jpg
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)


Two dimensional arrays are often processed with nested loops l.jpg
Two Dimensional Arrays AreOften 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


Implicit sizing and initialization of two dimensional arrays l.jpg
Implicit Sizing and Initializationof 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}}


For each loops and multi dimensional arrays l.jpg
For Each Loops andMulti-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


Summing the columns of a two dimensional array l.jpg
Summing the Columns of aTwo-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


Three dimensional arrays and beyond l.jpg
Three-dimensional Arraysand 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


8 6 enabled property timer control splash screens l.jpg

8.6Enabled 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


Enabled property i l.jpg
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


Enabled property ii l.jpg
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


Timer control i l.jpg
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


Timer control ii l.jpg
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)


Splash screens l.jpg
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


8 6 anchoring and docking controls l.jpg

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


Anchor property l.jpg
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


Dock property l.jpg
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


8 7 random numbers l.jpg

8.7Random Numbers

Visual Basic .NET Provides the Tools to Generate Random Numbers and Initialize the Sequence of Random Numbers With a Seed Value


Random number generation step 1 l.jpg
Random Number Generation, Step 1

  • Random number generation is initiated with the selection of a "seed" 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)

Randomize (Number)


Random number generation step 2 l.jpg
Random Number Generation, Step 2

  • Obtain the next random number in the sequence

  • Repeatedly use a statement like the above to generate additional random numbers

randomNumber = Rnd()


Random number range l.jpg
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)


ad