Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Arrays, Timers, and More.

Similar presentations


Presentation on theme: "Chapter 8 Arrays, Timers, and More."— Presentation transcript:

1 Chapter 8 Arrays, Timers, and More

2 8.1 Introduction

3 Chapter 8 Topics Arrays are like groups of variables that allow you to store sets of 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

4 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

5 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

6 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

7 Declaring an Array ArrayName is the name of the 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

8 Example of an Array Dim hours(5) As Integer hours(0) hours(1) hours(2) hours(3) hours(4) hours(5)

9 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

10 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}

11 Named Constants 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

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

13 Arrays and Loops Frequently, arrays will be processed in loops
Dim count As Integer For count = 0 To 9 series(count) = Val(InputBox("Enter a number.")) Next count Dim count As Integer For count = 0 To 999 names(count) = "" Next count

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

15 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

16 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

17 Determining the Number of Elements in an Array
Array's have a Length property that holds the number of elements in the array Note that the length is the number of elements on 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

18 How to Total the Values in an Array
The values are summed up in a variable that is initialized to zero beforehand: Dim total As Integer = 0 ' Initialize accumulator For count = 0 To (units.Length – 1) total += units(count) Next count

19 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

20 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 Proceed analogously to find the lowest value highest = numbers(0) For count = 1 To (numbers.Length - 1) If numbers(count) > highest Then highest = numbers(count) End If Next count

21 Copying One Array's Contents 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 the value of oldvalues is the storage location for that array (not all of the contents of oldvalues) For count = 0 To 100 newValues(count) = oldValues(count) Next count

22 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

23 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

24 Parallelism Between Arrays and List Boxes and Combo Boxes
' Initialize a List Box with names lstPeople.Items.Add("Jean James") ' Subscript 0 lstPeople.Items.Add("Kevin Smith") ' Subscript 1 lstPeople.Items.Add("Joe Harrison") ' Subscript 2 ' Initialize an Array with corresponding phone numbers phoneNumbers(0) = " " phoneNumbers(1) = " " phoneNumbers(2) = " " ' Process a selection If lstPeople.SelectedIndex > -1 And _ lstPeople.SelectedIndex < phoneNumbers.Length Then MessageBox.Show(phoneNumbers(lstPeople.SelectedIndex)) Else MessageBox.Show("That is not a valid selection.") End If

25 Searching Arrays, The Search
This code hunts for the value 100 in the array scores ' Search for a 100 in the array. found = False count = 0 Do While Not found And count < scores.Length If scores(count) = 100 Then found = True position = count End If count += 1 Loop

26 Searching Arrays, Acting on the Result
This code indicates whether or not the value was found or not ' Was 100 found in the array? If found Then MessageBox.Show( _ "Congratulations! You made a 100 on test " & _ (position + 1).ToString, "Test Results") Else "You didn’t score a 100, but keep trying!", _ "Test Results") End If

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

28 Resizing an Array ReDim is a new keyword
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

29 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

30 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

31 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

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

33 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

34 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

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

36 A Two Dimensional Array Picture
Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2

37 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

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

39 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

40 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}}

41 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

42 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

43 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

44 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

45 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

46 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

47 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

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

49 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

50 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

51 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

52 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

53 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

54 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 Randomize [Number]

55 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

56 Random Number Range Rnd creates random numbers in the range of 0.0 to 1.0 To scale these to a range between two integers that may be needed in your program: randomNumber = Int(LowerNumber + Rnd * _ (UpperNumber - LowerNumber))


Download ppt "Chapter 8 Arrays, Timers, and More."

Similar presentations


Ads by Google