Presentation is loading. Please wait.

Presentation is loading. Please wait.

Brief description on how to navigate within this presentation (ppt)

Similar presentations


Presentation on theme: "Brief description on how to navigate within this presentation (ppt)"— Presentation transcript:

1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf
Brief description on how to navigate within this presentation (ppt) The first time a Key Term from the chapter is used in the ppt it will display in blue Gold colored text boxes display coding examples Slides will be numbered (# of #) when multiple slides on same topic (Slide title) Speaker notes are included where appropriate for slides (*)Denotes either a comment for page reference to textbook or slide reference in ppt

2 8 Arrays Chapter McGraw-Hill
© 2006 The McGraw-Hill Companies, Inc. All rights reserved.

3 Objectives Establish an array and refer to individual elements in the array with subscripts Use the For Each/Next to traverse the elements of an array Create a structure for multiple fields of related data Accumulate totals using arrays Distinguish between direct access and indirect access of a table Write a table lookup for matching an array element Combine the advantages of list box controls with arrays Store and look up data in multidimensional arrays

4 Single-Dimension Arrays
List or series of values all referenced by the same name Similar to list of values for list boxes and combo boxes - without the box Use an array to store a series of variables for later processing Use an array to store multiple values May be referred to as a table or subscripted (index) variable Individual elements are treated the same as any other variable and my be used in any statement

5 Array Terms Element Subscript (or index) Boundaries
Individual item in the array Subscript (or index) Zero based number used to reference the specific elements in the array Must be an integer Boundaries Lower Subscript, 0 by default Upper Subscript

6 Array Example nameString Array (0) Janet Baker (1) George Lee (2)
(3) (4) (5) (6) (7) (8) (9) Janet Baker George Lee Sue Li Samuel Hoosier Sandra Weeks William Macy Andy Harrison Ken Ford Denny Franks Shawn James

7 Subscripts Subscripts may be constants, variables, or numeric expressions Subscripts must be integers-VB rounds any noninteger subscript The real advantage of using an array is not realized until you use variables for subscripts in place of constants

8 The Declaration Statements for Arrays - General Form
This Dim statement allocates storage for specific number of elements and initializes numeric variables to 0 and string array elements to empty string (zero characters) Elements in an array may be assigned values in the Dim statement, cannot declare upper subscript and initial values Dim ArrayName(UpperSubscript) As Datatype Dim ArrayName( ) As Datatype = {InitialValueList} Dim ArrayName As Datatype( ) = {InitialValueList} Arrays can be declared by using Dim, Public, Private, or Friend keyword Just as with any other variable, the location of the declaration determines the scope and lifetime of the array variables *The next slide displays the Declaration Statements for Arrays Example

9 Dim Statement for Arrays Example(s)
Dim nameString(25) As String Dim balanceDecimal(10) As Decimal Dim productString(99) As String Dim indexInteger( ) As Integer = {1, 5, 12, 18, 20} Dim indexInteger As Integer( ) = {1, 5, 12, 18, 20} Dim departmentsString( ) As String = {"Accounting", "Marketing"} Private categoryString(10) As String Public idNumberString(5) As String Array subscripts are zero bases, so the first element is always element zero The upper subscript is the highest subscript—one less than the number of elements You declare a data type for the array—all of the array elements must be the same data type; if the data type is omitted by having Option Strict off, just as single variables, the type defaults to Object

10 Valid Subscripts Subscript must reference a valid element of an array
VB rounds fractional subscripts VB throws exceptions for subscripts that are out of range Arrays are based on System.Array, which is a collection

11 For Each/Next Statements
Use Loops to reference each element in the array For / Next or For Each/Next VB references EACH element of the array and assigns its value to ElementName Variable used for ElementName must be same datatype as array elements or an Object datatype Best to declare the variable for ElementName as part of the For Each statement to create a block-level variable Makes one pass through the loop per element Use Exit For statement within loop to exit early The significant advatanges of using the For Each and Next (key term) are that subscripts for the array don’t have to be manipulated or the user doesn’t need to know how many elements there are in the array *The next slide displays the General Form for the For Each and Next Statements

12 The For Each and Next Statements General Form
For Each ElementName [As Datatype] In ArrayName ' Statement(s) in loop. Next [ElementName] If the array has 12 elements, the loop will execute 12 times *The next slide provides an example of the For Each and Next Statements

13 The For Each and Next Statements Example
For Each eachNameString In nameString ' Write one element of the array. Debug.WriteLine(eachNameString) Next eachNameString The For Each loop executes if the array has at least one elements—all the statements within the loop are executed for the first element If the array has more elements, the loop continues to execute until all the elements are processesd

14 Structures Combine multiple fields of data to create a new structure
Similar to defining a new data type Combine fields into a structure using the Structure, End Structure Structure Declaration (by default a Structure is Public) Cannot be declared inside a procedure Generally place at the top of a file with module-level declarations Can also be placed in a separate file *The next slide displays the general form for the Structure and End Structure Statements

15 The Structure and End Structure Statements - General Form
[Public|Private|Friend] Structure NameOfStructure Dim FirstField As Datatype Dim SecondField As Datatype . . . End Structure By default, a structure is public—it can be declared to be Friend or Private if desired

16 The Structure and End Structure Statements – Example (1 of 2)
Structure Employee Dim lastnameString As String Dim firstNameString As String Dim socialSecurityNumberString As String Dim streetString As String Dim stateString As String Dim zipCodeString As String Dim hireDate As Date Dim payCodeInteger As Integer End Structure *Continuation of the Structure and End Structure Statement Example is on the next slide

17 The Structure and End Structure Statements – Example (2 of 2)
Friend Structure Product Dim descriptionString As String Dim productNumberString As String Dim quantityInteger As Integer Dim priceDecimal As Decimal End Structure Structure SalesDetail Dim saleDecimal () As Decimal EndStructure Once a structure is created variables of the structure can be declared just as if it were another data type

18 Accessing the Elements in a Structure Variable
Each field of data in Structure is referred to as an element of the structure To access elements use the dot notation similar to that used for objects--Specify Variable.Element Examples officeEmployee.lastNameString officeEmployee.hireDate inventoryProduct(indexInteger).descriptionString inventoryProduct(indexInteger).quantityInteger inventoryProduct(indexInteger).priceDecimal A variable that is not an array, does not need an index

19 Including An Array In A Structure
Arrays can be included as elements within a Structure VB does not allow you to declare the number of elements in the array within the Structure declaration Use the ReDim statement inside a procedure to define the size of the array *The next slide provides an example of the code used to include an Array in a Structure

20 ReDim Code Example ' Module-level declarations. Structure SalesDetail Dim saleDecimal( ) As Decimal End Structure Private houseWaresSalesDetail As SalesDetail ' Inside a procedure. ' Establish the number of elements in the array. ReDim houseWaresSalesDetail.saleDecimal(6) ' In processing. houseWaresSalesDetail.saleDecimal _ (dayIndexInteger) = currentDaySalesDecimal

21 Using Array Elements for Accumulators
Array elements are regular variables and perform in the same ways as many other variables Subscripted variables can be used in any choosen such as for counters or total accumulators *Use example in the textbook on p. 327 to explain this slide

22 Debugging Array Programs
View the array elements in debugging time by setting a breakpoint and view the Autos window; click the plus sign to left of array name to view individual array elements

23 Table Lookup Often values used to identify a series of elements are not sequential Use a table lookup process to find the correct element in the array Establish a structure and dimension an array of the structure Use the Form_Load event procedure to put numbers in table-executed once the form is loaded into memory Things don’t always work out so neatly as having sequential group numbers that can be used to access the table directly Sometimes a little work is involved to find (look up) the correct value and reference the array elements indirectly

24 Coding a Table Lookup For a table lookup, a Do/Loop works better than For Each When comparing to element in the array and eventually finding a match the user needs to know the subscript of the matching element *Example on p. 331 in textbook

25 Lookup Operation Logic
The table-lookup technique will work for any table, numeric or string It isn’t necessary to arrange the fields being searched in any particular sequence The comparison is made to one item in the list, then the next, and the next until a match is found Time can be saved in a large table by arranging the elements with the most-often-used entries at the top so that fewer comparisons must be made

26 Using List Boxes With Arrays (1 of 2)
Use List Boxes or Combo Boxes rather than text boxes to look up information in the array Use the list's SelectedIndex property to determine the array subscript Selected Index property holds the position or index of the selected list item *The next slide displays an example of using a List Box

27 Using List Boxes With Arrays (1 of 2)
Allow the user to select from a list and the SelectedIndex property can be used as the subscript of the total array. groupNumberInteger = groupListBox.SelectedIndex

28 Multidimensional Arrays
To define a two-dimensional array or table-- Dim statement specifies number of rows and columns The row is horizontal and the column is vertical May specify number of elements –OR-- initial values Specify row with first subscript, column with second subscript, need to use a comma to specify the dimensions Generally two subscripts are needed to identify tabular data, where data is arranged in rows and columns

29 The Dim Statement for Two-Dimensional Arrays - General Form
Dim ArrayName(HighestSubscript, Highest Subscript) As Datatype Dim ArrayName( , ) As Datatype = {ListOfValues}

30 The Dim Statement for Two-Dimensional Arrays – Example(s)
Dim nameString(2, 3) As String Dim nameString( , ) As String = {{"James", "Mary", "Sammie", "Sean"}, _ {"Tom", "Lee", "Leon", "Larry"}, {"Maria", "Margaret", "Jill", "John"}} ' Both statements establish an array of 12 elements. (0, 0) James (0, 1) Mary (0, 2) Sammie (0, 3) Sean (1, 0) Tom (1, 1) Lee (1, 2) Leon (1, 3) Larry (2, 0) Maria (2, 1) Margaret (2, 2) Jill (2, 3) John The elements of the array may be used in the same ways as any other variable – in accumulators, counts and reference fields for lookup, or in statements like assignment and printing, and as conditions

31 Initializing Two-Dimensional Arrays
Initializing/Reinitializing Use nested For/Next loop Printing a Two-Dimensional Table Use For Each/Next loop Summing a Two-Dimensional Table Include a total field for each row and each column Sum the figures in both directions (double-check totals) Numeric array elements are initially set to 0 and string elements are set to empty strings; initial values can be assigned when declaring the array

32 Nested For/Next Example
For rowInteger = 0 To 2 For columnInteger = 0 To 3 ' Initialize each element. nameString(rowInteger, columnInteger) = " " Next columnInteger Next rowInteger The assignment statement will be executed once for each element of nameString

33 Printing a Two-Dimensional Table
' Print one name per line. For Each elementString In nameString ' Set up a line. e.Graphics.DrawString(elementString, printFont, _ Brushes.Black, horizontalPrintLocationSingle, _ verticalPrintLocationSingle) ' Increment the Y position for the next line. verticalPrintLocationSingle += lineHeightSingle Next elementString

34 Summing a Two-Dimensional Table
The sum of a table can be found in various ways; either sume the columns or the rows of the table; or, as sum the figures in both directions and double-check the totals; to sum an array in both directions, each column needs one total variable and each row needs one total variable Two-one dimensional arrays work well for the totals

35 Lookup Operations for Two-Dimensional Tables
Use same techniques as for single dimensional arrays Direct Reference (if meaningful row and column subscripts are available) Table Lookup Many 2D tables used for lookup will require additional one-dimensional arrays or lists to aid in the lookup process A table lookup is the most common lookup technique

36 Two Dimensional Array Example
*This example is found in the textbook on p. 337 Many two-dimensional tables used for lookup require additional one-dimensional arrays or lists to aid in the lookup process


Download ppt "Brief description on how to navigate within this presentation (ppt)"

Similar presentations


Ads by Google