Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz, 2012 1  2009 - 11 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.

Similar presentations


Presentation on theme: "Jozef Goetz, 2012 1  2009 - 11 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved."— Presentation transcript:

1

2 Jozef Goetz, 2012 1  2009 - 11 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.

3 Jozef Goetz, 2012 2 Chapter 8 - Arrays Outline 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:

4 Jozef Goetz, 2012 3  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

5 Jozef Goetz, 2012 4 Chapter 8: Arrays Objectives  To introduce the array data structure.  To understand how arrays store, sort and search lists and tables of values.  To understand how to declare an array, initialize an array and refer to individual elements of an array.  To understand basic sorting techniques.  To be able  to declare and manipulate multiple-subscripted arrays.  to store data in and retrieve data from tables of values  to pass arrays to methods.  to use the foreach statement to iterate through arrays.  to declare and manipulate multidimensional arrays.  to write methods that use variable-length argument lists.  to read command-line arguments into an application.

6 Jozef Goetz, 2012 5 8.1 Introduction  Data structures are collections of related data items of same type.  Arrays  Data structures  Related data items of same type  Remain same size once created  they remain the same length once they are created  So they are “static” entities, although an array reference may be assigned to a new array of different si ze  The elements of an array can be either value types or reference types.

7 Jozef Goetz, 2012 6 8.2 Arrays Fig. 8.1A 12-element array. -45 6 0 72 1543 -89 0 62 -3 1 6453 -78c[ 11 ] c[ 10 ] c[ 9 ] c[ 8] c[ 7 ] c[ 4 ] c[ 3 ] c[ 2 ] c[ 1 ] c[ 0 ] c[ 6 ] c[ 5 ] Position number (index or subscript or sub) of the element within array c Name of array (Note that all elements of this array have the same name, c ) Indices begin at 0

8 Jozef Goetz, 2012 7 8.2 Arrays  Array  Group of contiguous memory locations  Each memory location has same name  Each memory location has same type  To refer to an element, specify  Array name  Position number  e.g. Refer to particular element in the array by position number  Format :  arrayname [ position number ]  First element at position 0  n element array named c : c[0], c[1]... c[n-1]

9 Jozef Goetz, 2012 8 8.2 Arrays (cont.)  Subscript  Also called an index  Position number in square brackets  Must be int, uint, long, ulong or a value of a type that can be implicitly promoted to one of these types  or integer expression a = 5; b = 6; c[a + b] += 2; c[11] pronounced as “c sub eleven”– derives from “subscript  Adds 2 to c[11] – the 12 th element of array c or array element eleven. –This confusion is a source of “off-by-one” error

10 Jozef Goetz, 2012 9 8.2 Arrays (cont.)  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] )  The value of c[0] is –45  The brackets ( [] ) are in highest level of precedence in C# (Java too)

11 Jozef Goetz, 2012 10 8.2 Arrays Short circuit evaluation is applied

12 Jozef Goetz, 2012 11 8.3 Declaring and Allocating Arrays  Declaring and Allocating arrays  Arrays are objects that occupy memory  Allocated dynamically with operator new int[]c = new int[ 12 ]; //Java: int c[] = new int[ 12 ]; –Equivalent to int[]c; // declare array; int c[12] - error c = new int[ 12 ]; // allocate array create an array object containing 12 int elements and store the array’s reference in variable c  Other example double[] array1 = new double [10], array2 = new double [30] ;  Can contain any data type  In arrays of value types, each element contains one value of the declared type  For non-primitive types, every element is a reference to an object –We can allocate arrays of objects too string[] b = new string[ 100 ]; - Each of a string is a reference to a string which has the value null by default  Primitive elements initialized to zero or false  Non-primitive references are null

13 Jozef Goetz, 2012 12 Good Programming Practice For readability, declare only one variable per declaration. Keep each declaration on a separate line and include a comment describing the variable being declared. 8.3 Declaring and Creating Arrays (Cont.) Common Programming Error 8.1 In the declaration of a variable that will refer to an array, specifying the number of elements in the square brackets (e.g., int[ 12 ] c; ) is a syntax error.

14 Jozef Goetz, 2012 13 Resizing an Array  Though arrays are fixed-length entities, you can resize an array using the static Array method Resize.  Resize takes two arguments—the array to be resized and the new length. It performs the following operations: int[] newArray = new int[5]; Array.Resize( ref newArray, 10);  Creates a new array with the specified length  Copies the contents of the old array into the new array  Sets the array variable to reference the newArray to refer to a new 10-element array  Any content that cannot fit into the new array is truncated. 8.3 Declaring and Creating Arrays (Cont.)

15 Jozef Goetz, 2012 14 8.4 Examples Using Arrays Allocating an Array and Initializing Its Elements  Arrays can be allocated using the word new to specify how many elements the array should hold  int[] c = new int[ 12 ];  Arrays can be initialized with initializer lists  Allocate space for the array – number of elements in initializer list determines the size of array  Elements in array are initialized with the values in the initializer list int[] n = {10, 20, 30, 40, 50}; int[] n = new int[]{10, 20, 30, 40, 50};  Example  Show how to  Declare array  Allocate array  Initialize array elements

16 Jozef Goetz, 2012 15 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

17  2002 Prentice Hall. All rights reserved. Outline 16 1 // Fig. 7.3 ed1: InitArray.cs 2 // Different ways of initializing 3 integer arrays. 3 4 using System; 5 using System.Windows.Forms; 6 7 class InitArray 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 string output = ""; 13 14 int[] x; // declare reference to an array 15 x = new int[ 10 ]; // dynamically allocate array and set 16 // default values 17 18 // initializer list specifies number of elements 19 // and value of each element 20 int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 21 22 const int ARRAY_SIZE = 10; // you cannot change constant later 23 int[] z; // reference to int array 24 25 // allocate array of ARRAY_SIZE (i.e., 10) elements 26 z = new int[ ARRAY_SIZE ]; 27 28 // set the values in the array 29 for ( int i = 0; i < z.Length; i++ ) 30 z[ i ] = 2 + 2 * i; 31 32 output += "Subscript\tArray x\tArray y\tArray z\n"; 33 Declare an integer array x Allocate x to be of size 10 Declare an integer array y and initialize it with values Declare a constant ARRAY_SIZE Declare an integer array zInitialize z to be of size ARRAY_SIZE Initialize the elements in z using a for loop

18  2002 Prentice Hall. All rights reserved. Outline 17 InitArray.cs Program Output 34 // output values for each array 35 for ( int i = 0; i < ARRAY_SIZE; i++ ) 36 output += i + "\t" + x[ i ] + "\t" + y[ i ] + 37 "\t" + z[ i ] + "\n"; 38 39 MessageBox.Show( output, 40 "Initializing an array of int values", 41 MessageBoxButtons.OK, MessageBoxIcon.Information ); 42 43 } // end Main 44 45 } // end class InitArray Add values in the arrays to output

19 Jozef Goetz, 2012 18 Outline InitArray.cs ( 1 of 2 ) The application in Fig. 8.3 initializes an integer array with 10 values (line 10) and displays the array in tabular format. Fig. 8.3 | Initializing the elements of an array with an array initializer. (Part 1 of 2.)

20 Jozef Goetz, 2012 19 Outline InitArray.cs ( 2 of 2 ) Fig. 8.3 | Initializing the elements of an array with an array initializer. (Part 2 of 2.) The code for displaying the array elements (lines 15–16) is identical to that in the previous example.

21 Jozef Goetz, 2012 20 Outline InitArray.cs ( 1 of 2 ) Calculating a Value to Store in Each Array Element The application in Fig. 8.4 creates a 10-element array and assigns to each element one of the even integers from 2 to 20 ( 2, 4, 6,..., 20 ). Fig. 8.4 | Calculating values to be placed into the elements of an array. (Part 1 of 2.) Constants must be initialized when they are declared and cannot be modified thereafter. Common Programming Error 8.2  Assigning a value to a named constant after it has been initialized is a compilation error.

22 Jozef Goetz, 2012 21 Outline InitArray.cs ( 2 of 2 ) Fig. 8.4 | Calculating values to be placed into the elements of an array. (Part 2 of 2.)

23 Jozef Goetz, 2012 22 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 +’s 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.

24  2002 Prentice Hall. All rights reserved. Outline 23 1 // Fig.7.4 ed1: SumArray.cs 2 // Computing the sum of the elements in an array. 3 4 using System; 5 using System.Windows.Forms; 6 7 class SumArray 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 13 int total = 0; 14 15 for ( int i = 0; i < a.Length; i++ ) 16 total += a[ i ]; 17 18 MessageBox.Show( "Total of array elements: " + total, 19 "Sum the elements of an array", 20 MessageBoxButtons.OK, MessageBoxIcon.Information ); 21 22 } // end Main 23 24 } // end class SumArray Declare integer array a and initialize it Total the contents of array a Exercise: Find the sum of odd numbers in the array.

25 Jozef Goetz, 2012 24 Using Histograms to Display Array Data Graphically  Present array values graphically  Histogram  Plot each numeric value as bar of asterisks ( * )  Examine the distribution of grades

26  2002 Prentice Hall. All rights reserved. Outline 25 Histogram.cs 1 // Fig. 7.5 ed1: Histogram.cs 2 // Using data to create a histogram. The nested for loops are used 3 4 using System; 5 using System.Windows.Forms; 6 7 class Histogram 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 int[] n = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 13 string output = ""; 14 15 output += "Element\tvalue\tHistogram\n"; 16 17 // build output 18 for ( int i = 0; i < n.Length; i++ ) 19 { 20 output += "\n" + i + "\t" + n[ i ] + "\t"; 21 22 for ( int j = 1; j <= n[ i ]; j++ ) // print a bar 23 output += "*"; // using n [i] 24 } 25 26 MessageBox.Show( output, "Histogram Printing Program", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 29 } // end Main 30 31 } // end class Histogram Declare an integer array n and initialize it Create a bar for each element in n Print a bar consisting of asterisks, corresponding to the value of the element in n Exercise: Based on program Fig. 7.5 ed1 generate random values from 1 to 99 for each element for array indexes from 1 to 20. Provide similar output to Fig.7.5 ed1 by plotting each numeric value as a bar chart of a pound sign (#) for each 10 values and each asterisk (*) for each single value.

27 Jozef Goetz, 2012 26 Outline  BarChart.cs For each array element, print associated number of asterisks

28 Jozef Goetz, 2012 27 8.4 Examples Using Arrays (Cont.)  Using the elements of an array as counters (Fig. 8.7)  Use a series of counter variables to summarize data

29 Jozef Goetz, 2012 28 Example – Die Rolling Program 1.Use the value of rolling the dice as the subscript for the array 2.Increment the corresponding array element when a die value is rolled 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 Using the elements of an array as counters

30 Jozef Goetz, 2012 29 Using the Elements of an Array as Counters  Use array elements to keep track of number of occurrences of each side on a six-sided die as the program rolled 12 dice at a time  Example – Die Rolling Program  Use the value of rolling the dice as the subscript for the array  Increment the corresponding array element when a die value is rolled

31  2002 Prentice Hall. All rights reserved. Outline 30 RollDie.cs 1 // Fig. 7.6 ed1: RollDie.cs 2 // Rolling 12 dice 3 // keep track of number of occurrences of each side on a six-sided 4 // die as the program rolled 12 dice at a time 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 using System.IO; 11 12 public class RollDie : System.Windows.Forms.Form 13 { 14 private System.Windows.Forms.Button rollButton; 15 16 private System.Windows.Forms.RichTextBox displayTextBox; 17 18 private System.Windows.Forms.Label dieLabel1; 19 private System.Windows.Forms.Label dieLabel2; 20 private System.Windows.Forms.Label dieLabel3; 21 private System.Windows.Forms.Label dieLabel4; 22 private System.Windows.Forms.Label dieLabel5; 23 private System.Windows.Forms.Label dieLabel6; 24 private System.Windows.Forms.Label dieLabel7; 25 private System.Windows.Forms.Label dieLabel8; 26 private System.Windows.Forms.Label dieLabel9; 27 private System.Windows.Forms.Label dieLabel10; 28 private System.Windows.Forms.Label dieLabel11; 29 private System.Windows.Forms.Label dieLabel12; 30 31 private System.ComponentModel.Container components = null; 32 33 Random randomNumber = new Random(); 34 int[] frequency = new int[ 7 ]; 35 Create a Random objectDeclare an integer array frequency and allocate it enough memory to hold 7 integers

32  2002 Prentice Hall. All rights reserved. Outline 31 RollDie.cs 36 public RollDie() 37 { 38 InitializeComponent(); 39 } 40 41 // Visual Studio.NET generated code 42 43 [STAThread] 44 static void Main() 45 { 46 Application.Run( new RollDie() ); 47 } 48 49 private void rollButton_Click( 50 object sender, System.EventArgs e ) 51 { 52 // pass the labels to a method that will 53 // randomly assign a face to each die 54 DisplayDie( dieLabel1 ); 55 DisplayDie( dieLabel2 ); 56 DisplayDie( dieLabel3 ); 57 DisplayDie( dieLabel4 ); 58 DisplayDie( dieLabel5 ); 59 DisplayDie( dieLabel6 ); 60 DisplayDie( dieLabel7 ); 61 DisplayDie( dieLabel8 ); 62 DisplayDie( dieLabel9 ); 63 DisplayDie( dieLabel10 ); 64 DisplayDie( dieLabel11 ); 65 DisplayDie( dieLabel12 ); 66 67 double total = 0; 68 69 for ( int i = 1; i < 7; i++ ) 70 total += frequency[ i ]; // Accumulate the total when a die value is rolled Event handler for the rollButton Click event Call method DisplayDie once for each Label Total the number of times the dice have been rolled

33  2002 Prentice Hall. All rights reserved. Outline 32 RollDie.cs // N – string as a decimal with 2 decimal places 71 72 displayTextBox.Text = "Face\tFrequency\tPercent\n"; // header 73 74 // output frequency values 75 for ( int x = 1; x < frequency.Length; x++ ) // starts from 1 76 { 77 displayTextBox.Text += x + "\t" + 78 frequency[ x ] + "\t\t" + String.Format( "{0:N}", 79 frequency[ x ] / total * 100 ) + "%\n"; 80 } 81 82 } // end Main 83 84 // simulates roll, display proper 85 // image and increment frequency 86 public void DisplayDie( Label dieLabel ) 87 { 88 int face = randomNumber.Next( 1, 7 ); 89 90 dieLabel.Image = Image.FromFile( 91 Directory.GetCurrentDirectory() + 92 "\\images\\die" + face + ".gif" ); 93 94 frequency [face]++; 95 } 96 97 } // end class RollDie Output the frequency of each die value Get a random number from 1 to 6 Display die image corresponding to the number rolls Exercise 1. Expand program Fig. 7.6 ed1 to keep track of the number of occurrences of each side on a six-sided die as the user roll 6 dice each time for 25 rolls ( or the number of rolls enter by the user). You can create roll [6] [25] to keep track of it. Print the result in the tabular format. Exercise 2. In addition to the output in Fig.7.6 expand the program by accumulating and displaying all 12 element generated sequence last time.

34 Jozef Goetz, 2012 33 Using Arrays to Analyze Survey Results  Problem statement:  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

35  2002 Prentice Hall. All rights reserved. Outline 34 StudentPoll.cs 1 // Fig. 7.7 ed1: StudentPoll.cs 2 // A student poll program. 3 4 using System; 5 using System.Windows.Forms; 6 7 class StudentPoll 8 { 9 // main entry point for application 10 static void Main( string[] args ) 11 { 12 int[] responses = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 13 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 14 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 }; 15 16 int[] frequency = new int[ 11 ]; 17 string output = ""; 18 19 // increment the frequency for each response 20 for ( int answer = 0; answer < responses.Length; answer++ ) 21 ++frequency [responses [answer] ]; 22 23 output += "Rating\tFrequency\n"; 24 25 // output results 26 for ( int rating = 1; rating < frequency.Length; rating++ ) 27 output += rating + "\t" + frequency[ rating ] + "\n"; 28 29 MessageBox.Show( output, "Student poll program", 30 MessageBoxButtons.OK, MessageBoxIcon.Information ); 31 32 } // end method Main 33 34 } // end class StudentPoll Declare and initialize integer array responses Declare and allocate integer array frequency For every element in responses, increment the frequency element that corresponds to the answer Output the number of times each response appeared

36 Jozef Goetz, 2012 35 Outline  StudentPoll.cs Declare responses as array to store 40 responses For each response, increment frequency values at index associated with that response

37 Jozef Goetz, 2012 36 New edition  StudentPoll.cs Declare responses as array to store 40 responses For each response, increment frequency values at index associated with that response

38 Jozef Goetz, 2012 37 8.4 Examples Using Arrays (Cont.)  In many programming languages, like C and C++, writing outside the bounds of an array is allowed, but often causes disastrous results.  In C#, accessing any array element forces a check on the array index to ensure that it is valid. This is called bounds checking.  If an application uses an invalid index, the Common Language Runtime generates an IndexOutOfRangeException to indicate that an error occurred in the application at execution time.

39 Jozef Goetz, 2012 38 8.4 Examples Using Arrays (Cont.) 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 13. Error-Prevention Tip 8.2 When writing code to loop through an array, ensure that the array index remains >=0 and < the length of the array. The loop-continuation condition should prevent the accessing of elements outside this range.

40 Jozef Goetz, 2012 39 Outline  Card.cs Ten of Hearts Ace of Diamonds Jack of Spades Queen of Diamonds Six of Clubs Seven of Hearts Deuce of Spades Seven of Diamonds Queen of Spades King of Hearts Nine of Hearts Deuce of Clubs Eight of Clubs Five of Diamonds Three of Hearts Five of Hearts Three of Spades Four of Diamonds Six of Hearts Nine of Diamonds Queen of Clubs Deuce of Diamonds Queen of Hearts Four of Clubs Seven of Spades Four of Hearts Three of Diamonds Seven of Clubs Ten of Clubs Ten of Spades Jack of Diamonds Jack of Clubs Nine of Clubs Six of Diamonds Eight of Hearts Eight of Spades King of Spades Three of Clubs King of Diamonds Six of Spades Jack of Hearts Ace of Clubs Five of Spades Nine of Spades Deuce of Hearts Five of Clubs Ten of Diamonds Ace of Hearts Ace of Spades Four of Spades Eight of Diamonds King of Clubs Return the string representation of a card

41 Jozef Goetz, 2012 40 Outline  DeckOfCar ds.cs  (1 of 2)

42 Jozef Goetz, 2012 41 Outline  DeckOfCar ds.cs  (2 of 2) Swap current Card with randomly selected Card Determine whether deck is empty

43 Jozef Goetz, 2012 42 Outline  DeckOfCardsTest.cs

44 Jozef Goetz, 2012 43 8.6 foreach Repetition Structure  The foreach repetition structure (no in Java) is used to iterate through values in data structures such as arrays  No counter  Cannot access the counter indicating the index  A variable is used to represent the value of each element  Can access array elements int lowGrade = 100; foreach ( int grade in gradeArray ) { if ( grade < lowGrade ) lowGrade = grade; } How it works:  repetition begins with element whose indices are all 0s,  then iterates through all possible combinations of indices, incrementing the rightmost index first.  When the rightmost index reaches its upper bound, it is reset to zero, and the index to the left of it is incremented by 1

45  2002 Prentice Hall. All rights reserved. Outline 44 ForEach.cs 1 // Fig. 8.12 ed1: ForEach.cs 2 // Demonstrating for/each structure. 3 using System; 4 5 class ForEach 6 { 7 // main entry point for the application 8 static void Main( string[] args ) 9 { 10 int[,] gradeArray = { { 77, 68, 86, 73 }, 11 { 98, 87, 89, 81 }, { 70, 90, 86, 81 } }; 12 13 int lowGrade = 100; 14 15 foreach ( int grade in gradeArray ) 16 { 17 if ( grade < lowGrade ) 18 lowGrade = grade; 19 } 20 21 Console.WriteLine( "The minimum grade is: " + lowGrade ); 22 } 23 } The minimum grade is: 68 Use the foreach loop to examine each element in the array If the current array element is smaller then lowGrade, set lowGrade to contain the value of the current element

46 Jozef Goetz, 2012 45 Outline ForEachTest.cs ( 1 of 2 ) Figure 8.12 uses the foreach statement to calculate the sum of the integers in an array of student grades. Fig. 8.12 | Using the foreach statement to total integers in an array. For each iteration, number represents the next int value in the array.

47 Jozef Goetz, 2012 46 Outline ForEachTest.cs ( 2 of 2 ) Common Programming Error 8.4 The foreach statement can be used only to access array elements it cannot be used to modify elements. Any attempt to change the value of the iteration variable in the body of a foreach statement will cause a compilation error. The foreach statement can be used in place of the for statement whenever code looping through an array does not need to know the index of the current array element.

48 Jozef Goetz, 2012 47 8.6 foreach Statement (Cont.) Implicitly Typed Local Variables  C# provides a new feature - called implicitly typed local variables - that enables the compiler to infer a local variable ’ s type based on the type of the variable ’ s initializer.  To distinguish such an initialization from a simple assignment statement, the var keyword is used in place of the variable ’ s type.  var y = - 156.34;  The compiler assumes that floating-point number values are of type double.  You can use local type inference with control variables in the header of a for or foreach statement.  For example, the following for statement headers are equivalent: for ( int counter = 1; counter < 10; counter++ ) for ( var counter = 1; counter < 10; counter++ ) In this case counter is of type int

49 Jozef Goetz, 2012 48 8.6 foreach Statement (Cont.)  Similarly, if myArray is an array of int s, the following foreach statement headers are equivalent: foreach (int number in myArray) foreach (var number in myArray)  The implicitly typed local-variable feature is one of several new Visual C# 2008 features that support Language Integrated Query (LINQ).  Implicitly typed local variables can be also used to initialize arrays without explicitly giving their type.  var array = new[] {32,27,64, 60, 37};  There are no square brackets on the left side of the assignment operator.  new[] is used on the right to specify that the variable is an array.

50 Jozef Goetz, 2012 49 8.7 Passing Arrays to Methods  Pass arrays as arguments to methods by specifying the name of the array (no brackets) 1: Array hourlyTemperatures declaration int [ ] hourlyTemperatures = new int[ 24 ]; 2: The method call modifyArray(hourlyTemperatures); Every array object “knows” its own size via the Length  Passes array hourlyTemperatures by reference to method modifyArray 3: The method definition public void modifyArray (int[] b) {.. body..}  Arrays are always passed by reference  e.g. Call by reference = sharing a box of candy  Individual array elements are passed by value  e.g. Call by value = making a Xerox copy

51 Jozef Goetz, 2012 50 Performance Tip  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

52 Jozef Goetz, 2012 51 8.7 Passing Arrays and Array Elements to Methods  To pass an array argument to a method, specify the name of the array without any brackets. For a method to receive an array reference through a method call, the method’s parameter list must specify an array parameter.  When an argument to a method is an entire array or an individual array element of a reference type, the called method receives a copy of the reference.  When an argument to a method is an individual array element of a value type, the called method receives a copy of the element’s value.  To pass an individual array element to a method, use the indexed name of the array (e.g. a[5] ) as an argument in the method call.

53  2002 Prentice Hall. All rights reserved. Outline 52 PassArray.cs 1 // Fig. 8.13: PassArray.cs 2 // Passing arrays and individual elements to methods. 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class PassArray : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button showOutputButton; 13 private System.Windows.Forms.Label outputLabel; 14 15 // Visual Studio.NET generated code 16 17 [STAThread] 18 static void Main() 19 { 20 Application.Run( new PassArray() ); 21 } 22 23 private void showOutputButton_Click( object sender, 24 System.EventArgs e ) 25 { 26 int[] a = { 1, 2, 3, 4, 5 }; 27 28 outputLabel.Text = "Effects of passing entire array " + 29 "call-by-reference:\n\nThe values of the original " + 30 "array are:\n\t"; 31 32 for ( int i = 0; i < a.Length; i++ ) 33 outputLabel.Text += " " + a[ i ]; 34 35 ModifyArray( a ); // array is passed by reference Declare and initialize integer array a Output contents of array aCall method ModifyArray, pass array a as an argument by reference

54  2002 Prentice Hall. All rights reserved. Outline 53 PassArray.cs 36 37 outputLabel.Text += 38 "\n\nThe values of the modified array are:\n\t"; 39 40 // display elements of array a 41 for ( int i = 0; i < a.Length; i++ ) 42 outputLabel.Text += " " + a[ i ]; 43 44 outputLabel.Text += "\n\nEffects of passing array " + 45 "element call-by-value:\n\na[ 3 ] before " + 46 "ModifyElement: " + a[ 3 ]; 47 48 // array element passed call-by-value 49 ModifyElement( a[ 3 ] ); 50 51 outputLabel.Text += 52 "\na[ 3 ] after ModifyElement: " + a[ 3 ]; 53 } 54 55 // method modifies the array it receives, 56 // original will be modified 57 public void ModifyArray( int[] b ) 58 { 59 for ( int j = 0; j < b.Length; j++ ) 60 b[ j ] *= 2; 61 } 62 63 // method modifies the integer passed to it 64 // original will not be modified 65 public void ModifyElement( int e ) 66 { 67 outputLabel.Text += 68 "\nvalue received in ModifyElement: " + e; 69 Output array a after ModifyArray changed the contents Replace every element in array by twice its value Pass array element array[3] to method ModifyElement

55  2002 Prentice Hall. All rights reserved. Outline 54 PassArray.cs Program Output 70 e *= 2; 71 72 outputLabel.Text += 73 "\nvalue calculated in ModifyElement: " + e; 74 } 75 } Multiply argument by two This does not change value of element in original array, because the element was passed by value

56 Jozef Goetz, 2012 55 8.8 Passing Arrays by Value and by Reference  Variables that “store” object, actually store references to those objects  A reference is a location in computer’s memory where the object itself is stored  Passing v a lue type variables to methods  A copy of the variable is made  Any changes to the variable in the method do not effect the original variable  Passing reference type variables to methods by value:  A copy of the reference to the object is made (creating a local copy of the reference itself)  Any changes to the reference in the method do not effect the original variable (which is the reference)  Any changes to the contents of the object in the method, do effect the object outside the method

57 Jozef Goetz, 2012 56 8.8 Passing Arrays by Value and by Reference  Keyword ref may be used to pass arguments to method by ref erence:  References to objects are not copied ( used the original )  the called method actually gains control over the passed reference itself allowing the called method to replace the original references in the caller with different object or even with null  modifying the reference in the method will modify the reference outside the method  Programmers have to be careful when using ref  May lead to references being set to null  May lead to methods modifying variable values and references in ways that are not desired

58 Jozef Goetz, 2012 57 Software Engineering Observations  In C#, objects (including arrays) always pass by reference.  So, a called method receiving a reference to an object can modify the caller's object via a non-const reference parameter.  When a method receives a reference-type object parameter by value:  the object still passes by reference but the object's reference is passed by value.  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.  to modify the caller's reference, pass the reference-type using keyword ref  but, again, such situations are rare.

59  2002 Prentice Hall. All rights reserved. Outline 58 ArrayReferenceTe st.cs 1 // Fig. 8.14: ArrayReferenceTest.cs 2 // Testing the effects of passing array references 3 // by value and by reference. 4 using System; 5 using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; 9 using System.Data; 10 11 public class ArrayReferenceTest : System.Windows.Forms.Form 12 { 13 private System.Windows.Forms.Label outputLabel; 14 private System.Windows.Forms.Button showOutputButton; 15 16 [STAThread] 17 static void Main() 18 { 19 Application.Run( new ArrayReferenceTest() ); 20 } 21 22 private void showOutputButton_Click( object sender, 23 System.EventArgs e ) 24 { 25 // create and initialize firstArray 26 int[] firstArray = { 1, 2, 3 }; 27 28 // copy firstArray reference 29 int[] firstArrayCopy = firstArray; 30 31 outputLabel.Text += 32 "Test passing firstArray reference by value"; 33 34 outputLabel.Text += "\n\nContents of firstArray " + 35 "before calling FirstDouble:\n\t"; Declare and initialize integer array firstArray Declare integer array firstArrayCopy and have it reference firstArray

60  2002 Prentice Hall. All rights reserved. Outline 59 ArrayReferenceTe st.cs 36 37 // print contents of firstArray 38 for ( int i = 0; i < firstArray.Length; i++ ) 39 outputLabel.Text += firstArray[ i ] + " "; 40 41 // pass reference firstArray by value to FirstDouble 42 FirstDouble( firstArray ); 43 44 outputLabel.Text += "\n\nContents of firstArray after " + 45 "calling FirstDouble\n\t"; 46 47 // print contents of firstArray 48 for ( int i = 0; i < firstArray.Length; i++ ) 49 outputLabel.Text += firstArray[ i ] + " "; 50 51 // test whether reference was changed by FirstDouble 52 if ( firstArray == firstArrayCopy ) 53 outputLabel.Text += 54 "\n\nThe references refer to the same array\n"; 55 else 56 outputLabel.Text += 57 "\n\nThe references refer to different arrays\n"; 58 //part II 59 // create and initialize secondArray 60 int[] secondArray = { 1, 2, 3 }; 61 62 // copy secondArray reference 63 int[] secondArrayCopy = secondArray; 64 65 outputLabel.Text += "\nTest passing secondArray " + 66 "reference by reference"; 67 68 outputLabel.Text += "\n\nContents of secondArray " + 69 "before calling SecondDouble:\n\t"; 70 Output contents of firstArray Call method FirstDouble on firstArray Output contents of firstArrayTest whether firstArray and firstArrayCopy reference the same object Declare and initialize integer array secondArray Declare integer array secondArrayCopy and set it to reference secondArray

61  2002 Prentice Hall. All rights reserved. Outline 60 ArrayReferenceTe st.cs 71 // print contents of secondArray before method call 72 for ( int i = 0; i < secondArray.Length; i++ ) 73 outputLabel.Text += secondArray[ i ] + " "; 74 75 SecondDouble ( ref secondArray ); 76 77 outputLabel.Text += "\n\nContents of secondArray " + 78 "after calling SecondDouble:\n\t"; 79 80 // print contents of secondArray after method call 81 for ( int i = 0; i < secondArray.Length; i++ ) 82 outputLabel.Text += secondArray[ i ] + " "; 83 84 // test whether reference was changed by SecondDouble 85 if (secondArray == secondArrayCopy) 86 outputLabel.Text += 87 "\n\nThe references refer to the same array\n"; 88 else 89 outputLabel.Text += 90 "\n\nThe references refer to different arrays\n"; 91 92 } // end method showOutputButton_Click 93 94 // modify elements of array and attempt to modify 95 // reference 96 void FirstDouble( int[] array ) 97 { 98 // double each element's value 99 for ( int i = 0; i < array.Length; i++ ) 100 array[ i ] *= 2; 101 102 // create new reference and assign it to array 103 array = new int[] { 11, 12, 13 }; // reference copy is changed, not the original reference 104 } 105 Output contents of secondArray Test whether secondArray and secondArrayCopy reference the same object Replace each element in the array by twice its value Set array to reference a new integer array containing the values 11, 12 and 13

62  2002 Prentice Hall. All rights reserved. Outline 61 ArrayReferenceTe st.cs Program Output 106 // modify elements of array and change reference array 107 // to refer to a new array – the same body 108 void SecondDouble( ref int[] array ) 109 { 110 // double each element's value 111 for ( int i = 0; i < array.Length; i++ ) 112 array[ i ] *= 2; 113 114 // create new reference and assign it to array 115 array = new int[] { 11, 12, 13 }; // the original reference is changed 116 } 117 } Replace each element in the array by twice its value Set array to reference a new integer array containing the values 11, 12 and 13

63 Jozef Goetz, 2012 62 Outline  GradeBook.cs  (1 of 6)

64 Jozef Goetz, 2012 63 Outline  GradeBook.cs  (2 of 6)

65 Jozef Goetz, 2012 64 Outline  GradeBook.cs  (3 of 6)

66 Jozef Goetz, 2012 65 Outline  GradeBook.cs  (4 of 6)

67 Jozef Goetz, 2012 66 Outline  GradeBook.cs  (5 of 6)

68 Jozef Goetz, 2012 67 Outline  GradeBook.cs  (6 of 6)

69 Jozef Goetz, 2012 68 Outline  GradeBook Test.cs

70 Jozef Goetz, 2012 69 Using Arrays to Analyze Survey Results  Some additional checked for validity  When looping through an array  Subscript should never go below 0  Subscript should be less than total number of array elements  When invalid array reference occurs  C# generates IndexOutOfBoundsException and terminates the program abnormally –programmers can write code to recover from exceptions and continue program execution Later we will discuss exception handling

71 Jozef Goetz, 2012 70 8.8 Passing Arrays by Value and by Reference (Cont.) 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. Software Engineering Observation 8.2 In C#, objects (including arrays) are effectively passed by reference, because references to objects are passed to called methods. A called method receiving a reference to an object in a caller can interact with, and possibly change, the caller’s object.

72 Jozef Goetz, 2012 71 8.10 Multiple-Subscripted Arrays  Require two or more subscripts to identify a particular element  Arrays that require two subscripts to identify an element are called double-subscripted arrays  Rectangular arrays  Often represent tables in which each row is the same size and each column is the same size  Tables with rows and columns  Double-subscripted (two-dimensional) array  Declaring double-subscripted array b[2][2] 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]  By convention, first subscript identifies the element’s row and the second subscript the element’s column

73 Jozef Goetz, 2012 72 8.10 Multiple-Subscripted Arrays Fig. 8.17Double-subscripted array with three rows and four columns. Row 0 Row 1 Row 2 Column 1Column 0Column 2Column 3 a[0, 0]a[0, 3]a[0, 1]a[0, 2] a[1, 0]a[1, 3]a[1, 1]a[1, 2] a[2, 0]a[2, 3] a[2, 2] Column index (or subscript) Row index (or subscript) Array name a[2, 1]

74 Jozef Goetz, 2012 73 8.10 Multiple-Subscripted Arrays  Allocating multiple-subscripted arrays  Can be allocated dynamically  3 -by- 4 array int[,]b; b = new int[ 3 ][ 4 ]; or int[,]b = new int[ 3 ][ 4 ];  3 Dimensional: int[,, ] myArray = new int [4,2,3];  Jagged Arrays  Arrays of arrays  Arrays that compose jagged arrays can be of different lengths  Rows can have different number of columns, so each one-dimensional array must be initialized separately (show graphical representation) int[][] b = new int[ 2][] // declare 2 rows of array b[ 0 ] = new int[ 5 ]; // allocate row 0 b[ 1 ] = new int[ 3 ]{3,4,5}; // allocate row 1 // initialize it

75 Jozef Goetz, 2012 74 8.10 Multidimensional Arrays (Cont.) int[][] b = new int[ 2][] // declare 2 rows of array b[ 0 ] = new int[ 5 ]; // allocate row 0 b[ 1 ] = new int[ 3 ]{3,4,5}; // allocate row 1 and initialize it  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 } };

76 Jozef Goetz, 2012 75 8.10 Multidimensional Arrays (Cont.)  initialization in declarations like single-subscripted arrays  int[, ]b = {{1,2}, {3,4,5}}; –row 0 contains elements 1 and 2 –row 1 contains elements 3, 4 and 5  or int[, ]b = new int[, ]{{1,2}, {3,4,5}};

77 Jozef Goetz, 2012 76 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

78 Jozef Goetz, 2012 77 Outline Iterates through each of the array’s “rows” Passes in a “rectangular” array Iterates through each of the array’s “columns”, 2 nd dimension GetLength returns the length of 1 st dimension Values in the rectangular array by row are 1 2 3 4 5 6 Values in the jagged array by row are 1 2 3 4 5 6

79 Jozef Goetz, 2012 78 Outline 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

80 Jozef Goetz, 2012 ©1992-2011 by Pearson Education, Inc. All Rights Reserved. Values in the jagged array by row are 1 2 3 4 5 6 Iterations in a “jagged” array use the foreach control structure

81  2002 Prentice Hall. All rights reserved. Outline 80 DoubleArray.cs 1 // Fig. 7.15 ed1 DoubleArray.cs 2// Manipulating a double-subscripted array. 3// Find min and max grade of any student for the semester 4// each row of the array represent a student 5// each column of the array represent a grade 3 using System; 4 using System.Drawing; 5 using System.Collections; 6 using System.ComponentModel; 7 using System.Windows.Forms; 8 using System.Data; 9 10 public class DoubleArray : System.Windows.Forms.Form 11 { 12 private System.Windows.Forms.Button showOutputButton; 13 private System.Windows.Forms.Label outputLabel; 14 15 int[][] grades; 16 int students, exams; 17 18 // Visual Studio.NET generated code 19 20 [STAThread] 21 static void Main() 22 { 23 Application.Run( new DoubleArray() ); 24 } 25 26 private void showOutputButton_Click( object sender, 27 System.EventArgs e ) 28 29 { 30 grades = new int[ 3 ][]; 31 grades[ 0 ] = new int[]{ 77, 68, 86, 73 }; 32 grades[ 1 ] = new int[]{ 96, 87, 89, 81 }; 33 grades[ 2 ] = new int[]{ 70, 90, 86, 81 }; 34 Initialize array grades to have 3 rowsInitialize each element in array grades

82  2002 Prentice Hall. All rights reserved. Outline 81 DoubleArray.cs 35 students = grades.Length; // number of students- # of rows 36 exams = grades[ 0 ].Length; // number of exams 37 38 // line up column headings 39 outputLabel.Text += " "; 40 41 // output the column headings 42 for ( int i = 0; i < exams; i++ ) 43 outputLabel.Text += "[" + i + "] "; 44 45 // output the rows 46 for ( int i = 0; i < students; i++ ) 47 { 48 outputLabel.Text += "\ngrades[" + i + "] "; 49 50 for ( int j = 0; j < exams; j++ ) 51 outputLabel.Text += grades[ i ][ j ] + " "; 52 } 53 54 outputLabel.Text += "\n\nLowest grade: " + Minimum() + 55 "\nHighest grade: " + Maximum() + "\n"; 56 57 for ( int i = 0; i < students; i++ ) 58 outputLabel.Text += "\nAverage for student " + i + " is " 59 + Average( grades[ i ] ); // it passes i-th row 60 61 } // end method showOutputButton_Click 62 Output each rowOutput each element of the row Output the minimum and maximum grades Output the average for each row

83  2002 Prentice Hall. All rights reserved. Outline 82 DoubleArray.cs 63 // find minimum grade in grades array 64 public int Minimum() 65 { 66 int lowGrade = 100; 67 68 for ( int i = 0; i < students; i++ ) 69 70 for ( int j = 0; j < exams; j++ ) 71 72 if ( grades[ i ][ j ] < lowGrade ) 73 lowGrade = grades[ i ][ j ]; 74 75 return lowGrade; 76 } 77 78 // find maximum grade in grades array 79 public int Maximum() 80 { 81 int highGrade = 0; 82 83 for ( int i = 0; i < students; i++ ) 84 85 for ( int j = 0; j < exams; j++ ) 86 87 if ( grades[ i ][ j ] > highGrade ) 88 highGrade = grades[ i ][ j ]; 89 90 return highGrade; 91 } 92 Examine each element in grades array If the current array element is less then the lowest grade, set the value of lowGrade to be the current element Examine each element in grades array If the current array element higher then the highest grade, set the value of highGrade to be the current element

84  2002 Prentice Hall. All rights reserved. Outline 83 DoubleArray.cs Program Output 93 // determine average grade for a particular student 94 public double Average( int[] setOfGrades ) 95 { 96 int total = 0; 97 98 for ( int i = 0; i < setOfGrades.Length; i++ ) 99 total += setOfGrades[ i ]; 100 101 return ( double ) total / setOfGrades.Length; 102 } 103 104 } // end class DoubleArray Total the grades for the array Divide the total by the number of grades

85 Jozef Goetz, 2012 84 Outline  GradeBook.cs  (1 of 7)

86 Jozef Goetz, 2012 85 Outline  GradeBook.cs  (2 of 7)

87 Jozef Goetz, 2012 86 Outline  GradeBook.cs  (3 of 7) Loop through array to find the lowest grade of any student

88 Jozef Goetz, 2012 87 Outline  GradeBook.cs  (4 of 7) Loop through array to find the highest grade of any student Calculate a particular student’s average

89 Jozef Goetz, 2012 88 Outline  GradeBook.cs  (5 of 7) Calculate the distribution of all student grades

90 Jozef Goetz, 2012 89 Outline  GradeBook.cs  (6 of 7)

91 Jozef Goetz, 2012 90 Outline  GradeBook.cs  (7 of 7)

92 Jozef Goetz, 2012 91  GradeBook Test.cs  (1 of 2) Declare gradesArray as 3-by-10 array Each row represents a student; each column represents an exam grade

93 Jozef Goetz, 2012 92 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

94 Jozef Goetz, 2012 93 Outline  VarargsTest.cs 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

95 Jozef Goetz, 2012 94 Common Programming Error 8.5  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.

96 Jozef Goetz, 2012 95 8.13 Using Command-Line Arguments  On many systems:  it is possible to pass arguments from the command line (as command line arguments) to an application by including a parameter of type string[] (i.e., an array of strings) in the parameter list of Main public static void Main( string[] args ) When you execute your apps from the cmd line, you type the app name, as in ApplicationName arg1 arg2,…

97 Jozef Goetz, 2012 96 8.13 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 ]

98 Jozef Goetz, 2012 97  InitArray.cs (1 of 2) C:\Examples\ch08\fig08_21>InitArray.exe 10 1 2 // 3 arguments are passed to apps Index Value 0 1 1 3 2 5 3 7 4 9 5 11 6 13 7 15 8 17 9 19 Array args stores command-line arguments Obtain first command-line argument Obtain second and third command-line arguments Calculate the value for each array element based on command-line arguments

99 Jozef Goetz, 2012 98 Outline  InitArray.cs  (2 of 2) Missing command-line arguments

100 Jozef Goetz, 2012 99 Enter the size of an array by the user instead of entering from the Command-line Console.WriteLine("Enter the size of an array: "); int arrayLength = Convert.ToInt32(Console.ReadLine()); //int arrayLength = Convert.ToInt32( args[ 0 ] ); int[] array = new int[ arrayLength ]; // create array


Download ppt "Jozef Goetz, 2012 1  2009 - 11 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved."

Similar presentations


Ads by Google