Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 8 Arrays."— Presentation transcript:

1 McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 8 Arrays

2 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-2 Chapter Objectives Establish an array and refer to individual elements in the array with subscripts Use a foreach loop 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

3 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-3 Single-Dimension Arrays A list or series of values similar to a list of values for list boxes and combo boxes—without the box Use an array to store a series of variables for later processing May be referred to as tables or subscripted (or indexed) variables Individual variables (elements) are treated the same as any other variable and may be used in any statement

4 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-4 Subscripts Advantage of an array is using variables for subscripts in place of constants Subscripts are constants, variables, or numeric expressions Must be integers Array name and number of elements are declared –No limit to the number of elements (except for available memory)

5 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-5 The Declaration Statement for Arrays – General Form - 1 Declare arrays as public or private –Defaults to private Location of declaration determines scope and lifetime of array variables Declare an array by placing opening and closing square brackets after the data type Declare the number of elements or the initial values of array elements (which determine the number of elements)

6 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-6 The Declaration Statement for Arrays – General Form - 2 Datatype[] arrayName = new Datatype[NumberOfElements]; Datatype[] arrayName = new Datatype[] {InitialValueList}; Datatype[] arrayName = {InitialValueList}; [public|private] Datatype[] arrayName = new Datatype[NumberOfElements];

7 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-7 The Declaration Statement for Arrays – Examples Array subscripts are zero based –First element is always element zero All array elements must be the same data type string[] nameString = new string[25]; decimal[] balanceDecimal = new decimal[10]; int[] numbersInteger = new int[] {1, 5, 12, 18, 20}; string[] departmentsString = new string[] {"Accounting", "Marketing", "Human Relations"}; private string[] categoryString = new string[10]; public string[] IDNumbersString = new string[5]; string[] nameString = {"Sean", "Sam", "Sally", "Sara"};

8 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-8 Valid Subscripts A subscript must reference a valid element of an array –Zero through one less than the number of elements C# rounds fractional subscripts C# throws an exception for a subscript that is out of range Arrays are based on the System.Array collection

9 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-9 foreach Loops - 1 To reference each element of an array use for loops or foreach loops Advantages of a foreach loop –The subscripts of the array do not have to be manipulated –How many elements there are in an array does not have to be known Array elements are read-only in the body of a foreach loop C# automatically references each element of the array and assigns its value to ElementName –Makes one pass through the loop per element –The variable used for ElementName must be the same data type as array elements or an Object data type

10 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-10 foreach Loops - 2 Best to declare the variable for ElementName as part of the foreach statement to create a block- level variable A foreach loop will execute if the array has at least one element Loop continues to execute until all elements are processed Execution of code continues with the line following the closing braces when the loop finishes You can use a break statement to exit the loop early

11 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-11 foreach Loops - 3 General Form Examples foreach (DataType ElementName in ArrayName) { // Statement(s) in the loop. } foreach (string oneNameString in nameString) { Console.WriteLine(oneNameString); // Write one element of the array. } foreach (decimal oneItemDecimal in allItemsDecimal) // Display all elements in the array. { totalsRichTextBox.Text += indexInteger++ + "\t" + totalDecimal.ToString() + "\n"; }

12 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-12 Structures Combine multiple fields of data to create a new structure using the struct statement –Similar to defining a new data type struct declaration –Cannot go inside a method –Generally placed at the top of a file with the class- level declarations –Can be placed outside of a class –Public by default; can declare as private –The number of elements of an array inside a structure cannot be specified

13 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-13 The struct Statement - Examples struct Employee { public string lastNameString; public string firstNameString; public string SSNString; public string streetString; public string stateString; public string ZIPString; public DateTime hireDateTime; public int payCodeInteger; } public struct Product { public string descriptionString; public string IDString; public int quantityInteger; public decimal priceDecimal; } struct SalesDetail { public decimal[] saleDecimal; }

14 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-14 Declaring Variables Based on a Structure After you declare a structure, declare variables of the structure, just as if it were a data type –The location of the variable declaration determines the scope and lifetime of the variable Employee officeEmployee; Employee warehouseEmployee; Product widgetProduct; Product inventoryProduct[] = new Product[100]; SalesDetail housewaresSalesDetail; SalesDetail homeFurnishingsSalesDetail;

15 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-15 Accessing the Elements in a Structure Variable - 1 Each field of data in a structure is referred to as an element To access elements, use the dot notation similar to that used for objects A variable that is not an array does not need an index A variable that is an array needs the item and the element within the array of structures specified

16 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-16 Accessing the Elements in a Structure Variable - 2 Examples officeEmployee.lastNameString officeEmployee.hireDateTime warehouseEmployee.lastNameString widgetProduct.descriptionString widgetProduct.quantityInteger widgetProduct.priceDecimal inventoryProduct[indexInteger].descriptionString inventoryProduct[indexInteger].quantityInteger inventoryProduct[indexInteger].priceDecimal

17 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-17 Including an Array in a Structure An array can be included in a structure, but you cannot specify the number of elements in the struct declaration Public struct SalesDetail //Class-level declarations. { public decimal[] saleDecimal; } At the class level or inside a method, declare the name of the variable SalesDetail housewaresSalesDetail; Inside a method establish the number of elements in the array housewaresSalesDetail.saleDecimal = new decimal[7]; In processing, use a subscript to refer to each individual element within the structure housewaresSalesDetail.saleDecimal[dayIndexInteger] = todaysSalesDecimal;

18 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-18 Using Array Elements for Accumulators Array elements are regular variables –Perform the same way as all variables used so far –Can be used for counters or total accumulators Eight totals will be accumulated to demonstrate the use of array elements as total accumulators

19 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-19 Adding to the Correct Total Use the totalDecimal array to hold the sales totals for eight scout troops –User enters the group number and sales –Subtract one from the group number and use it as a subscript for the correct total –Add the sales amount to the corresponding total –This technique is called direct reference of the array // Convert input group number to subscript. groupNumberInteger = int.Parse(groupTextBox.Text) – 1; // Add sale to the correct total. saleDecimal = decimal.Parse(saleTextBox.Text); totalDecimal[groupNumberInteger] += saleDecimal;

20 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-20 Debugging Array Programs - 1 View array elements in debugging time by setting a breakpoint in code and viewing the Autos or Locals window –Click the plus sign to the left of the array name to view the individual array elements

21 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-21 Debugging Array Programs - 2 Visual Studio 2008 introduces visualizers –Pop up the value of an array in the Code Editor window Pause the mouse pointer over a variable or array Array name pops up, point to plus sign to display current contents of each element

22 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-22 Table Lookup - 1 Values used to identify a series of elements may not be sequential –Establish a structure and declare an array of the structure –In the Form_Load event handler, initialize the array elements –Use a table lookup to find the correct array element, the subscript –Compare the input group number to each element in the table, one by one –When a match is found, add to the corresponding total

23 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-23 Table Lookup - 2 public struct GroupInfo { public string groupNumberString; public decimal totalDecimal; } public GroupInfo[] arrayGroup = new GroupInfo[8]; groupNumber -String totalDecimal [0] 101 0 [1] 103 0 [2] 110 10 [3] 115 0 [4] 121 0 [5] 123 0 [6] 130 0 [7] 145 0 indexInteger 2

24 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-24 Table Lookup - 3 UML action diagram of the logic of a lookup operation

25 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-25 Coding a Table Lookup - 1 do loop works better than a foreach loop –Logic of a lookup operation // Convert input group number to a subscript. do { if (groupTextBox.Text == arrayGroup[groupNumberInteger].groupNumberString) { // A match is found. decimal saleDecimal = decimal.Parse(salesTextBox.Text); arrayGroup[groupNumberInteger].totalDecimal += saleDecimal; foundBoolean = true; // Clear the controls. groupTextBox.Clear(); salesTextBox.Clear(); groupTextBox.Focus(); } groupNumberInteger++; } while (groupNumberInteger < 8 && !foundBoolean);

26 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-26 Coding a Table Lookup - 2 Validate group number entry –If wrong, display a message box Check foundBoolean after loop completes to determine why loop terminated –Did it terminate because of a match or without a match Table lookup works for any table, numeric or string Searched fields do not have to be in any sequence

27 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-27 Using List Boxes with Arrays Use a list box or combo box rather than a text box for user input Use the list's SelectedIndex property to determine the array subscript –SelectedIndex property holds the position of the selected list item groupNumberInteger = groupComboBox.SelectedIndex;

28 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-28 Multidimensional Arrays - 1 To define a two-dimensional array or table: –The declaration statement specifies the number of rows and columns The row is horizontal and the column is vertical –Specify the number of elements within parentheses and/or specify initial values –Specify the row with the first subscript and the column with the second subscript Use a comma between the subscripts –Always use two subscripts when referring to individual elements of the table

29 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-29 Multidimensional Arrays - 2 Elements of an array are used the same way as other variables –Accumulators, counts, reference fields for lookup –In statements –As conditions Invalid references would include a value greater than the subscript for the row or column

30 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-30 Multidimensional Arrays - 3 General form Examples –Both of these statements create arrays with 3 rows and 4 columns –Note the comma between square brackets Specifies that the array has two dimensions DataType[,] ArrayName = new DataType[NumberOfElements, NumberOfColumns]; DataType[,] ArrayName = new DataType[,] = {ListOfValues}; string[,] nameString = new string[3, 4]; string[,] nameString = new string[,] = { {"James", "Mary", "Sammie", "Sean"}, {"Tom", "Lee", "Leon", "Larry"}, {"Maria", "Margaret", "Jill", "John"} };

31 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-31 Initializing Two-Dimensional Arrays Numeric array elements are initially set to zero String elements are initially set to an empty string You may need to initialize (or reinitialize) arrays to some other value –Nested for loops can set each array element to an initial value Cannot use a foreach loop to initialize an array

32 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-32 Nested for Loop Example for (int rowInteger = 0; rowInteger < 3; rowInteger ++ ) { for (int columnInteger = 0; columnInteger < 4; columnInteger ++) { nameString[rowInteger, columnInteger] = ""; //Initialize each element. }

33 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-33 Printing a Two-Dimensional Table Use a foreach loop to print one array element per line To print an entire row in one line, use a for loop and set the X and Y coordinates to print multiple elements per line // Print one name per line. foreach (string elementString in nameString) { // Set up a line. e.Graphics.DrawString(elementString, printFont, Brushes.Black, printXFloat, printYFloat); // Increment the Y position for the next line. printYFloat += lineHeightFloat; }

34 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-34 Summing a Two-Dimensional Table Include a total field for each row and each column Sum the figures in both directions (double check the totals) –Each column and row needs one total variable Two one- dimensional arrays work well for totals

35 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-35 Lookup Operation for Two-Dimensional Tables - 1 Use same techniques as for single dimension 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

36 McGraw-Hill© 2010 The McGraw-Hill Companies, Inc. All rights reserved. 8-36 Lookup Operation for Two-Dimensional Tables - 2 Example - User selects the weight from one list and the zone from the second list –The SelectedIndex from the Weight list is used to find the correct row –The SelectedIndex from the Zone list is used to find the correct column


Download ppt "McGraw-Hill © 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter 8 Arrays."

Similar presentations


Ads by Google