1 / 56

Chapter 8

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

mekelle
Download Presentation

Chapter 8

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8 Arrays, Timers, and More

  2. 8.1Introduction

  3. 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

  4. 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

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

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

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

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

  16. 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

  17. 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

  18. 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

  19. 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

  20. 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

  21. 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

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

  25. 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

  26. 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

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

  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.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

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

  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.5Multidimensional 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 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

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

  41. 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

  42. 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

  43. 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

  44. 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

  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.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

More Related