Presentation is loading. Please wait.

Presentation is loading. Please wait.

8 Arrays.

Similar presentations


Presentation on theme: "8 Arrays."— Presentation transcript:

1 8 Arrays

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 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 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 8.1 Introduction Arrays Data structures
Related data items of same type Remain same size once created Fixed-length entries

6 8.2 Arrays Arrays Group of variables Have same type Reference type

7 Fig | A 12-element array.

8 8.2 Arrays (Cont.) Index Examine array c
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 8.3 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 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 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 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 Outline Create 10 ints for array; each int is initialized to 0 by default Declare array as an array of ints InitArray.cs array.Length returns length of array Each int is initialized to 0 by default array[counter] returns int associated with index in array

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 Outline Declare array as an array of ints
InitArray.cs Compiler uses initializer list to allocate array

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 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 Outline Declare constant variable ARRAY_LENGTH using the final modifier InitArray.cs (1 of 2) Declare and create array that contains 10 ints Use array index to assign array value

19 Outline InitArray.cs (2 of 2)

20 Declare array with initializer list
Outline Declare array with initializer list SumArray.cs Sum all array values

21 Common Programming Error 8.2
Assigning a value to a named constant after it has been initialized is a compilation error.

22 Common Programming Error 8.3
Attempting to declare a named constant without initializing it is a compilation error.

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 Outline Declare array with initializer list (1 of 2)
BarChart.cs (1 of 2) For each array element, print associated number of asterisks

25 Outline BarChart.cs (2 of 2)

26 Outline Declare frequency as array of 7 ints
RollDie.cs Generate 6000 random integers in range 1-6 Increment frequency values at index associated with random number

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 Outline Declare responses as array to store 40 responses (1 of 2)
StudentPoll.cs (1 of 2) 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 Outline StudentPoll.cs (2 of 2)

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 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 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 Return the string representation of a card
Outline Card.cs Return the string representation of a card

34 Outline Declare deck as array to store Card objects
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 strings that represent the face of card Declare and initialize suits with strings that represent the suit of card Fill the deck array with Cards

35 Outline (2 of 2) Swap current Card with randomly selected Card
DeckOfCards.cs (2 of 2) Swap current Card with randomly selected Card Determine whether deck is empty

36 Outline DeckOfCardsTest.cs (1 of 2)

37 Outline DeckOfCardsTest.cs (2 of 2)

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 Lines equivalent to: for ( int counter = 0; counter < array.Length; counter++ ) total += array[ counter ];

39 Outline ForEachTest.cs For each iteration, assign the next element of array to int variable number, then add it to total

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 Outline Declare 5-int array with initializer list (1 of 3)
PassArray.cs (1 of 3) Pass entire array to method ModifyArray

42 Outline (2 of 3) Pass array element array[3] to method ModifyElement
PassArray.cs (2 of 3) Pass array element array[3] to method ModifyElement Method ModifyArray manipulates the array directly

43 Method ModifyElement tries to manipulate an array’s element
Outline Method ModifyElement tries to manipulate an array’s element PassArray.cs (3 of 3)

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 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 Outline Declare array firstArray to store individual values (1 of 5)
ArrayReferenceTest .cs (1 of 5) Declare array firstArrayCopy to point to firstArray Passes array firstArray to method FirstDouble by value

47 Outline (2 of 5) Declare array secondArray to store individual values
ArrayReferenceTest .cs (2 of 5) Declare array secondArray to store individual values Declare array secondArrayCopy to point to secondArray

48 Passes array secondArray to method SecondDouble by reference
Outline ArrayReferenceTest .cs (3 of 5) Passes array secondArray to method SecondDouble by reference

49 Outline Parameter passed in by value Changes to elements are kept
ArrayReferenceTest .cs (4 of 5) 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 Outline ArrayReferenceTest .cs (5 of 5)

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 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 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 Outline (1 of 6) Declare array grades to store individual grades
GradeBook.cs (1 of 6) Declare array grades to store individual grades Assign the array’s reference to instance variable grades

55 Outline GradeBook.cs (2 of 6)

56 Loop through grades to find the lowest grade
Outline GradeBook.cs (3 of 6) Loop through grades to find the lowest grade

57 Outline Loop through grades to find the highest grade (4 of 6)
GradeBook.cs (4 of 6) Loop through grades to sum grades for one student

58 Loop through grades to calculate frequency
Outline GradeBook.cs (5 of 6) Loop through grades to calculate frequency

59 Loop through grades to display each grade
Outline GradeBook.cs (6 of 6) Loop through grades to display each grade

60 Outline Declare and initialize gradesArray with 10 elements (1 of 2)
GradeBookTest.cs (1 of 2) Pass gradesArray to GradeBook constructor

61 Outline GradeBookTest.cs (2 of 2)

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 8.10 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 Fig. 8.17 | Rectangular array with three rows and four columns.

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 Fig. 8.18 | Jagged array with three rows of different lengths.

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 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 Outline Passes in a “rectangular” array
Iterates through each of the array’s “rows” InitArray.cs (2 of 3) GetLength returns the length of each dimension Iterates through each of the array’s “columns”

70 Outline Passes in a “jagged” array
Iterates through each of the array’s “rows” InitArray.cs (3 of 3) array[row].Length returns number of columns associated with row subscript Iterates through each of the array’s “columns”

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 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 Outline Declare two-dimensional array grades (1 of 7)
GradeBook.cs (1 of 7) Declare two-dimensional array grades GradeBook constructor accepts a string and a two-dimensional array

74 Outline GradeBook.cs (2 of 7)

75 Loop through array to find the lowest grade of any student
Outline GradeBook.cs (3 of 7) Loop through array to find the lowest grade of any student

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 Calculate the distribution of all student grades
Outline GradeBook.cs (5 of 7) Calculate the distribution of all student grades

78 Outline GradeBook.cs (6 of 7)

79 Outline GradeBook.cs (7 of 7)

80 Outline Declare gradesArray as 3-by-10 array (1 of 2)
GradeBookTest.cs (1 of 2) Each row represents a student; each column represents an exam grade

81 Outline GradeBookTest.cs (2 of 2)

82 8.12 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 Outline Method Average receives a variable length sequence of doubles
VarargsTest.cs (1 of 2) Calculate the total of the doubles in the array Access numbers.length to obtain the size of the numbers array

84 Outline (2 of 2) Invoke method Average with two arguments
VarargsTest.cs (2 of 2) Invoke method Average with two arguments Invoke method Average with three arguments Invoke method Average with four arguments

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 7.12 Using 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 Outline Array args stores command-line arguments (1 of 3)
InitArray.cs (1 of 3) 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 Missing command-line arguments
Outline InitArray.cs (2 of 3) Missing command-line arguments

89 Outline Three command-line arguments are 5, 0 and 4 (3 of 3)
InitArray.cs (3 of 3) Three command-line arguments are 10, 1 and 2

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 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 Fig. 8.24 | Collaborations in the ATM system.

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 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 Fig. 8.25 | Communication diagram of the ATM executing a balance inquiry.

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 Fig. 8.26 | Communication diagram for executing a BalanceInquiry.

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 Fig. 8.27 | Sequence diagram that models a Withdrawal executing.

100 Fig. 8.28 | Sequence diagram that models a Deposit executing.


Download ppt "8 Arrays."

Similar presentations


Ads by Google