Presentation is loading. Please wait.

Presentation is loading. Please wait.

 2006 Pearson Education, Inc. All rights reserved. 1 8 8 Arrays.

Similar presentations


Presentation on theme: " 2006 Pearson Education, Inc. All rights reserved. 1 8 8 Arrays."— Presentation transcript:

1  2006 Pearson Education, Inc. All rights reserved. 1 8 8 Arrays

2  2006 Pearson Education, Inc. All rights reserved. 2 Now go, write it before them in a table, and note it in a book. — Isaiah 30:8 To go beyond is as wrong as to fall short. — Confucius Begin at the beginning, … and go on till you come to the end: then stop. — Lewis Carroll

3  2006 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn:  What arrays are.  To use arrays to store data in and retrieve data from lists and tables of values.  To declare arrays, initialize arrays and refer to individual elements of arrays.  To use the foreach statement to iterate through arrays.  To pass arrays to methods.  To declare and manipulate multidimensional arrays.  To write methods that use variable-length argument lists.  To read command-line arguments into an application.

4  2006 Pearson Education, Inc. All rights reserved. 4 8.1 Introduction 8.2 Arrays 8.3 Declaring and Creating Arrays 8.4 Examples Using Arrays 8.5 Case Study: Card Shuffling and Dealing Simulation 8.6 foreach Statement 8.7 Passing Arrays and Array Elements to Methods 8.8 Passing Arrays by Value and by Reference 8.9 Case Study: Class GradeBook Using an Array to Store Grades 8.10 Multidimensional Arrays 8.11 Case Study: Class GradeBook Using a Rectangular Array 8.12 Variable-Length Argument Lists 8.13 Using Command-Line Arguments 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System 8.15 Wrap-Up

5  2006 Pearson Education, Inc. All rights reserved. 5 8.1 Introduction Arrays -Data structures -Related data items of same type -Remain same size once created Fixed-length entries

6  2006 Pearson Education, Inc. All rights reserved. 6 8.2 Arrays Arrays -Group of variables Have same type -Reference type

7  2006 Pearson Education, Inc. All rights reserved. 7 Fig. 8.1 | A 12-element array.

8  2006 Pearson Education, Inc. All rights reserved. 8 8.2 Arrays (Cont.) Index -Position number in square brackets -Must be positive integer or integer expression -First element has index zero a = 5; b = 6; c[ a + b ] += 2; Adds 2 to c[ 11 ] Examine array c - c is the array name - c.Length accesses array c ’s length - c has 12 elements ( c[0], c[1], … c[11] )

9  2006 Pearson Education, Inc. All rights reserved. 9 8.3 Declaring and Creating Arrays Declaring and creating arrays -Arrays are objects that occupy memory -Created dynamically with keyword new int c[] = new int[ 12 ]; -Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array We can create arrays of objects too string b[] = new string[ 100 ];

10  2006 Pearson Education, Inc. All rights reserved. 10 Common Programming Error 8.1 In an array declaration, specifying the number of elements in the square brackets of the declaration (e.g., int[ 12 ] c; ) is a syntax error.

11  2006 Pearson Education, Inc. All rights reserved. 11 Good Programming Practice 8.1 For readability, declare only one variable per declaration. Keep each declaration on a separate line and include a comment describing the variable being declared.

12  2006 Pearson Education, Inc. All rights reserved. 12 8.4 Examples Using Arrays Declaring arrays Creating arrays Initializing arrays Manipulating array elements Creating and initializing an array -Declare array -Create array -Initialize array elements

13  2006 Pearson Education, Inc. All rights reserved. 13 Outline InitArray.cs Declare array as an array of int s Create 10 int s for array ; each int is initialized to 0 by default array.Length returns length of array array[counter] returns int associated with index in array Each int is initialized to 0 by default

14  2006 Pearson Education, Inc. All rights reserved. 14 8.4 Examples Using Arrays (Cont.) Using an array initializer -Use initializer list Items enclosed in braces ( {} ) Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; -Creates a five-element array -Index values of 0, 1, 2, 3, 4 -Do not need keyword new

15  2006 Pearson Education, Inc. All rights reserved. 15 Outline InitArray.cs Declare array as an array of int s Compiler uses initializer list to allocate array

16  2006 Pearson Education, Inc. All rights reserved. 16 Good Programming Practice 8.2 Constants also are called named constants. Such variables often make applications more readable than applications that use literal values (e.g., 10 )—a named constant such as ARRAY_LENGTH clearly indicates its purpose, whereas a literal value could have different meanings based on the context in which it is used. Another advantage to using named constants is that if the value of the constant must be changed, it is necessary to change it only in the declaration, thus reducing the cost of maintaining the code.

17  2006 Pearson Education, Inc. All rights reserved. 17 8.4 Examples Using Arrays (Cont.) Calculating a value to store in each array element (Fig. 8.4) -Initialize elements of 10-element array to even integers Summing the elements of an array (Fig. 8.5) -Array elements can represent a series of values We can sum these values -Use a variable to add these values when iterating through them

18  2006 Pearson Education, Inc. All rights reserved. 18 Outline InitArray.cs (1 of 2) Declare constant variable ARRAY_LENGTH using the final modifier Declare and create array that contains 10 int s Use array index to assign array value

19  2006 Pearson Education, Inc. All rights reserved. 19 Outline InitArray.cs (2 of 2)

20  2006 Pearson Education, Inc. All rights reserved. 20 Outline SumArray.cs Declare array with initializer list Sum all array values

21  2006 Pearson Education, Inc. All rights reserved. 21 Common Programming Error 8.2 Assigning a value to a named constant after it has been initialized is a compilation error.

22  2006 Pearson Education, Inc. All rights reserved. 22 Common Programming Error 8.3 Attempting to declare a named constant without initializing it is a compilation error.

23  2006 Pearson Education, Inc. All rights reserved. 23 8.4 Examples Using Arrays (Cont.) Using bar charts to display array data graphically (Fig. 8.6) -Present data in graphical manner E.g., bar chart -Examine the distribution of grades Using the elements of an array as counters (Fig. 8.7) -Use a series of counter variables to summarize data

24  2006 Pearson Education, Inc. All rights reserved. 24 Outline BarChart.cs (1 of 2) Declare array with initializer list For each array element, print associated number of asterisks

25  2006 Pearson Education, Inc. All rights reserved. 25 Outline BarChart.cs (2 of 2)

26  2006 Pearson Education, Inc. All rights reserved. 26 Outline RollDie.cs Declare frequency as array of 7 int s Generate 6000 random integers in range 1-6 Increment frequency values at index associated with random number

27  2006 Pearson Education, Inc. All rights reserved. 27 8.4 Examples Using Arrays (Cont.) Using arrays to analyze survey results (Fig. 8.8) -40 students rate the quality of food 1-10 Rating scale: 1 mean awful, 10 means excellent -Place 40 responses in array of integers -Summarize results

28  2006 Pearson Education, Inc. All rights reserved. 28 Outline StudentPoll.cs (1 of 2) Declare responses as array to store 40 responses Declare frequency as array of 11 int and ignore the first element For each response, increment frequency values at index associated with that response

29  2006 Pearson Education, Inc. All rights reserved. 29 Outline StudentPoll.cs (2 of 2)

30  2006 Pearson Education, Inc. All rights reserved. 30 Error-Prevention Tip 8.1 An exception indicates that an error has occurred in an application. You often can write code to recover from an exception and continue application execution, rather than abnormally terminating the application. Exception handling is discussed in Chapter 12.

31  2006 Pearson Education, Inc. All rights reserved. 31 Error-Prevention Tip 8.2 When writing code to loop through an array, ensure that the array index remains greater than or equal to 0 and less than the length of the array. The loop-continuation condition should prevent the accessing of elements outside this range.

32  2006 Pearson Education, Inc. All rights reserved. 32 8.5 Case Study: Card Shuffling and Dealing Simulation Program simulates card shuffling and dealing -Use random number generation -Use an array of reference type elements to represent cards -Three classes Card (Fig. 8.9) -Represent a playing card DeckOfCards (Fig. 8.10) -Represent a deck of 52 playing cards DeckOfCardsTest (Fig. 8.11) -Demonstrate card shuffling and dealing

33  2006 Pearson Education, Inc. All rights reserved. 33 Outline Card.cs Return the string representation of a card

34  2006 Pearson Education, Inc. All rights reserved. 34 Outline DeckOfCards.cs (1 of 2) Declare deck as array to store Card objects Constant NUMBER_OF_CARDS indicates the number of Cards in the deck Declare and initialize faces with string s that represent the face of card Declare and initialize suits with string s that represent the suit of card Fill the deck array with Card s

35  2006 Pearson Education, Inc. All rights reserved. 35 Outline DeckOfCards.cs (2 of 2) Swap current Card with randomly selected Card Determine whether deck is empty

36  2006 Pearson Education, Inc. All rights reserved. 36 Outline DeckOfCardsTest.cs (1 of 2)

37  2006 Pearson Education, Inc. All rights reserved. 37 Outline DeckOfCardsTest.cs (2 of 2)

38  2006 Pearson Education, Inc. All rights reserved. 38 8.6 foreach Statement foreach -Iterates through the elements of an entire array or collection without using counter Can access array elements Cannot access the counter indicating the index Cannot modify array elements -Syntax foreach ( type identifier in arrayName ) statement -Fig. 8.12 Lines 13-14 equivalent to: for ( int counter = 0; counter < array.Length; counter++ ) total += array[ counter ];

39  2006 Pearson Education, Inc. All rights reserved. 39 Outline ForEachTest.cs For each iteration, assign the next element of array to int variable number, then add it to total

40  2006 Pearson Education, Inc. All rights reserved. 40 8.7 Passing Arrays and Array Elements to Methods To pass array argument to a method -Arrays are always passed by reference -Specify array name without brackets Array hourlyTemperatures is declared as double hourlyTemperatures = new double[ 24 ]; The method call ModifyArray( hourlyTemperatures ); The method header void ModifyArray( double[] b )

41  2006 Pearson Education, Inc. All rights reserved. 41 Outline PassArray.cs (1 of 3) Declare 5 - int array with initializer list Pass entire array to method ModifyArray

42  2006 Pearson Education, Inc. All rights reserved. 42 Outline PassArray.cs (2 of 3) Pass array element array[3] to method ModifyElement Method ModifyArray manipulates the array directly

43  2006 Pearson Education, Inc. All rights reserved. 43 Outline PassArray.cs (3 of 3) Method ModifyElement tries to manipulate an array’s element

44  2006 Pearson Education, Inc. All rights reserved. 44 8.8 Passing Arrays by Value and by Reference Pass-by-Reference -Caller gives called method direct access to caller’s data -Called method can manipulate this data -Improved performance over pass-by-value -Using ref allows the method to change the variable itself

45  2006 Pearson Education, Inc. All rights reserved. 45 Performance Tip 8.1 Passing arrays and other objects by reference makes sense for performance reasons. If arrays were passed by value, a copy of each element would be passed. For large, frequently passed arrays, this would waste time and would consume considerable storage for the copies of the arrays— both of these problems cause poor performance.

46  2006 Pearson Education, Inc. All rights reserved. 46 Outline ArrayReferenceTest.cs (1 of 5) Declare array firstArray to store individual values Declare array firstArrayCopy to point to firstArray Passes array firstArray to method FirstDouble by value

47  2006 Pearson Education, Inc. All rights reserved. 47 Outline ArrayReferenceTest.cs (2 of 5) Declare array secondArray to store individual values Declare array secondArrayCopy to point to secondArray

48  2006 Pearson Education, Inc. All rights reserved. 48 Outline ArrayReferenceTest.cs (3 of 5) Passes array secondArray to method SecondDouble by reference

49  2006 Pearson Education, Inc. All rights reserved. 49 Outline ArrayReferenceTest.cs (4 of 5) Parameter passed in by value Changes to elements are kept Since argument is passed by value, the reference of the original array cannot be modified Parameter passed in by reference Changes to elements are kept The reference of the original array is modified

50  2006 Pearson Education, Inc. All rights reserved. 50 Outline ArrayReferenceTest.cs (5 of 5)

51  2006 Pearson Education, Inc. All rights reserved. 51 Software Engineering Observation 8.1 When a method receives a reference-type parameter by value, a copy of the object’s reference is passed. This prevents a method from overwriting references passed to that method. In the vast majority of cases, protecting the caller’s reference from modification is the desired behavior. If you encounter a situation where you truly want the called procedure to modify the caller’s reference, pass the reference-type parameter using keyword ref — but, again, such situations are rare.

52  2006 Pearson Education, Inc. All rights reserved. 52 Software Engineering Observation 8.2 In C#, objects (including arrays) are passed by reference by default. So, a called method receiving a reference to an object in a caller can change the caller’s object.

53  2006 Pearson Education, Inc. All rights reserved. 53 8.9 Case Study: Class GradeBook Using an Array to Store Grades Further evolve class GradeBook Class GradeBook (Fig. 8.15) -Represent a grade book that stores and analyzes grades -Does not maintain individual grade values -Repeat calculations require reentering the same grades Can be solved by storing grades in an array

54  2006 Pearson Education, Inc. All rights reserved. 54 Outline GradeBook.cs (1 of 6) Declare array grades to store individual grades Assign the array’s reference to instance variable grades

55  2006 Pearson Education, Inc. All rights reserved. 55 Outline GradeBook.cs (2 of 6)

56  2006 Pearson Education, Inc. All rights reserved. 56 Outline GradeBook.cs (3 of 6) Loop through grades to find the lowest grade

57  2006 Pearson Education, Inc. All rights reserved. 57 Outline GradeBook.cs (4 of 6) Loop through grades to find the highest grade Loop through grades to sum grades for one student

58  2006 Pearson Education, Inc. All rights reserved. 58 Outline GradeBook.cs (5 of 6) Loop through grades to calculate frequency

59  2006 Pearson Education, Inc. All rights reserved. 59 Outline GradeBook.cs (6 of 6) Loop through grades to display each grade

60  2006 Pearson Education, Inc. All rights reserved. 60 Outline GradeBookTest.cs (1 of 2) Declare and initialize gradesArray with 10 elements Pass gradesArray to GradeBook constructor

61  2006 Pearson Education, Inc. All rights reserved. 61 Outline GradeBookTest.cs (2 of 2)

62  2006 Pearson Education, Inc. All rights reserved. 62 Software Engineering Observation 8.3 A test harness (or test application) is responsible for creating an object of the class being tested and providing it with data. This data could come from any of several sources. Test data can be placed directly into an array with an array initializer, it can come from the user at the keyboard, it can come from a file (as you will see in Chapter 18) or it can come from a network (as you will see in Chapter 23). After passing this data to the class’s constructor to instantiate the object, the test harness should call the object to test its methods and manipulate its data. Gathering data in the test harness like this allows the class to manipulate data from several sources.

63  2006 Pearson Education, Inc. All rights reserved. 63 8.10 Multidimensional Arrays Multidimensional arrays -Two-dimensional array: Table of values consisting of rows and columns Rectangular Arrays (Fig. 8.17) -M-by-N array -Often represents tables -Declaring two-dimensional array b[2,2] with nested array initializer: int b[, ] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0,0] and b[0,1] 3 and 4 initialize b[1,0] and b[1,1]

64  2006 Pearson Education, Inc. All rights reserved. 64 Fig. 8.17 | Rectangular array with three rows and four columns.

65  2006 Pearson Education, Inc. All rights reserved. 65 8.10 Multidimensional Arrays (Cont.) -Jagged Arrays (Fig. 8.18) Maintained as a one-dimensional array Rows of different lengths int [][] jagged = { new int [] { 1, 2 }, new int [] { 3 }, new int [] { 4, 5, 6 } };

66  2006 Pearson Education, Inc. All rights reserved. 66 Fig. 8.18 | Jagged array with three rows of different lengths.

67  2006 Pearson Education, Inc. All rights reserved. 67 8.10 Multidimensional Arrays (Cont.) Creating two-dimensional arrays with array- creation expressions -Can be created dynamically Rectangular 3 -by- 4 array int b[, ]; b = new int[ 3, 4 ]; Jagged Array int b[][]; b = new int[ 2 ][ ]; // create 2 rows b[ 0 ] = new int[ 5 ]; // create 5 columns for row 0 b[ 1 ] = new int[ 3 ]; // create 3 columns for row 1

68  2006 Pearson Education, Inc. All rights reserved. 68 Outline InitArray.cs (1 of 3) Use nested array initializers to initialize the “rectangular” array array1 Use nested array initializers of different lengths to initialize the “jagged” array array2

69  2006 Pearson Education, Inc. All rights reserved. 69 Outline InitArray.cs (2 of 3) Iterates through each of the array’s “rows” Passes in a “rectangular” array Iterates through each of the array’s “columns” GetLength returns the length of each dimension

70  2006 Pearson Education, Inc. All rights reserved. 70 Outline InitArray.cs (3 of 3) Iterates through each of the array’s “rows” Passes in a “jagged” array Iterates through each of the array’s “columns” array[row].Length returns number of columns associated with row subscript

71  2006 Pearson Education, Inc. All rights reserved. 71 8.10 Multidimensional Arrays (Cont.) Common multidimensional-array manipulations performed with for statements -Many common array manipulations use for statements E.g., int total = 0 for ( int row = 0; row < a.GetLength(0); row++ ) { for ( int column = 0; column < a.GetLength(1); column++ ) total += a[ row, column]; }

72  2006 Pearson Education, Inc. All rights reserved. 72 8.11 Case Study: Class GradeBook Using a Rectangular Array Class GradeBook (Fig. 8.20) -Two-dimensional array Store grades of all the student of the class -Graph of the overall grade distribution -Gives statistical information about the tests

73  2006 Pearson Education, Inc. All rights reserved. 73 Outline GradeBook.cs (1 of 7) Declare two-dimensional array grades GradeBook constructor accepts a string and a two-dimensional array

74  2006 Pearson Education, Inc. All rights reserved. 74 Outline GradeBook.cs (2 of 7)

75  2006 Pearson Education, Inc. All rights reserved. 75 Outline GradeBook.cs (3 of 7) Loop through array to find the lowest grade of any student

76  2006 Pearson Education, Inc. All rights reserved. 76 Outline GradeBook.cs (4 of 7) Loop through array to find the highest grade of any student Calculate a particular student’s average

77  2006 Pearson Education, Inc. All rights reserved. 77 Outline GradeBook.cs (5 of 7) Calculate the distribution of all student grades

78  2006 Pearson Education, Inc. All rights reserved. 78 Outline GradeBook.cs (6 of 7)

79  2006 Pearson Education, Inc. All rights reserved. 79 Outline GradeBook.cs (7 of 7)

80  2006 Pearson Education, Inc. All rights reserved. 80 Outline GradeBookTest.cs (1 of 2) Declare gradesArray as 3- by-10 array Each row represents a student; each column represents an exam grade

81  2006 Pearson Education, Inc. All rights reserved. 81 Outline GradeBookTest.cs (2 of 2)

82  2006 Pearson Education, Inc. All rights reserved. 82 8.12 Variable-Length Argument Lists Variable-length argument lists -One-dimensional array-type argument preceded by the keyword params indicates that the method receives a variable number of arguments with the type of the array’s elements params modifier can occur only in the last entry of parameter list Array whose elements are all the same type

83  2006 Pearson Education, Inc. All rights reserved. 83 Outline VarargsTest.cs (1 of 2) Method Average receives a variable length sequence of double s Calculate the total of the double s in the array Access numbers.length to obtain the size of the numbers array

84  2006 Pearson Education, Inc. All rights reserved. 84 Outline VarargsTest.cs (2 of 2) Invoke method Average with two arguments Invoke method Average with three arguments Invoke method Average with four arguments

85  2006 Pearson Education, Inc. All rights reserved. 85 Common Programming Error 8.4 Using the params modifier with a parameter in the middle of a method parameter list is a syntax error. The params modifier may be used only with the last parameter of the parameter list.

86  2006 Pearson Education, Inc. All rights reserved. 86 7.12 Using Command-Line Arguments Command-line arguments -Pass arguments from the command line string args[] -Appear after the class name in Command Prompt MyClass a b -Number of arguments passed in from command line args.Length -First command-line argument args[ 0 ]

87  2006 Pearson Education, Inc. All rights reserved. 87 Outline InitArray.cs (1 of 3) Array args stores command- line arguments Check number of arguments passed in from the command line Obtain first command-line argument Obtain second and third command-line arguments Calculate the value for each array element based on command-line arguments

88  2006 Pearson Education, Inc. All rights reserved. 88 Outline InitArray.cs (2 of 3) Missing command-line arguments

89  2006 Pearson Education, Inc. All rights reserved. 89 Outline InitArray.cs (3 of 3) Three command-line arguments are 10, 1 and 2 Three command-line arguments are 5, 0 and 4

90  2006 Pearson Education, Inc. All rights reserved. 90 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System Collaborations -When objects communicate to accomplish task Accomplished by invoking operations (methods) -One object sends a message to another object

91  2006 Pearson Education, Inc. All rights reserved. 91 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System (Cont.) Identifying the collaborations in a system -Read requirements document to find What ATM should do to authenticate a use What ATM should do to perform transactions -For each action, decide Which objects must interact -Sending object -Receiving object

92  2006 Pearson Education, Inc. All rights reserved. 92 Fig. 8.24 | Collaborations in the ATM system.

93  2006 Pearson Education, Inc. All rights reserved. 93 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System (Cont.) Interaction Diagrams -Model interactions use UML -Communication diagrams Also called collaboration diagrams Emphasize which objects participate in collaborations -Sequence diagrams Emphasize when messages are sent between objects

94  2006 Pearson Education, Inc. All rights reserved. 94 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System (Cont.) Communication diagrams -Objects Modeled as rectangles Contain names in the form objectName : className -Objects are connected with solid lines -Messages are passed alone these lines in the direction shown by arrows -Name of message appears next to the arrow

95  2006 Pearson Education, Inc. All rights reserved. 95 Fig. 8.25 | Communication diagram of the ATM executing a balance inquiry.

96  2006 Pearson Education, Inc. All rights reserved. 96 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System (Cont.) Sequence of messages in a communication diagram -Appear to the left of a message name -Indicate the order in which the message is passed -Process in numerical order from least to greatest

97  2006 Pearson Education, Inc. All rights reserved. 97 Fig. 8.26 | Communication diagram for executing a BalanceInquiry.

98  2006 Pearson Education, Inc. All rights reserved. 98 8.14 (Optional) Software Engineering Case Study: Collaboration Among Objects in the ATM System (Cont.) Sequence diagrams -Help model the timing of collaborations -Lifeline Dotted line extending down from an object’s rectangle -Represents the progression of time -Activation Thin vertical rectangle -Indicates that an object is executing

99  2006 Pearson Education, Inc. All rights reserved. 99 Fig. 8.27 | Sequence diagram that models a Withdrawal executing.

100  2006 Pearson Education, Inc. All rights reserved. 100 Fig. 8.28 | Sequence diagram that models a Deposit executing.


Download ppt " 2006 Pearson Education, Inc. All rights reserved. 1 8 8 Arrays."

Similar presentations


Ads by Google