jozef goetz, 2012 1 2009 - 11 pearson education, inc. all rights reserved. 2002 prentice hall. all...

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

Upload: felicia-marshall

Post on 02-Jan-2016

226 views

Category:

Documents


4 download

TRANSCRIPT

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

Jozef Goetz, 2012

1

2009 - 11 Pearson Education, Inc. All rights reserved.

2002 Prentice Hall. All rights reserved.

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

Jozef Goetz, 2012

2

Chapter 8 - Arrays

Outline8.1   Introduction8.2   Arrays8.3   Declaring and Creating Arrays8.4   Examples Using Arrays8.5   Case Study: Card Shuffling and Dealing Simulation8.6   foreach Statement8.7   Passing Arrays and Array Elements to Methods8.8   Passing Arrays by Value and by Reference8.9   Case Study: Class GradeBook Using an Array to Store Grades8.10   Multidimensional Arrays8.11   Case Study: Class GradeBook Using a Rectangular Array8.12   Variable-Length Argument Lists8.13   Using Command-Line Arguments8.14   (Optional) Software Engineering Case Study:

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

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

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

Jozef Goetz, 2012

4Chapter 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.

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

Jozef Goetz, 2012

58.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 size

The elements of an array can be either value types or reference types.

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

Jozef Goetz, 2012

68.2 Arrays

Fig. 8.1 A 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

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

Jozef Goetz, 2012

78.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]

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

Jozef Goetz, 2012

88.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 12th element of array c or array element eleven .– This confusion is a source of “off-by-one” error

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

Jozef Goetz, 2012

98.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)

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

Jozef Goetz, 2012

108.2 Arrays

Operators Associativity Type () [] . left to right highest (unary postfix)

++ -- + - ! (type) right to left unary (unary prefix)

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

& left to right boolean logical AND

^ left to right boolean logical exclusive OR

| left to right boolean logical inclusive OR

&& left to right logical AND

|| left to right logical OR

?: right to left conditional

= += -= *= /= %= right to left assignment

Fig. 7.2 ed1. Precedence and associativity of the operators discussed so far.

Short circuit evaluation is applied

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

Jozef Goetz, 2012

118.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 toostring[] 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

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

Jozef Goetz, 2012

12

Good Programming Practice For readability, declare only one variable per declaration. Keep eachdeclaration on a separate line and include a comment describing thevariable being declared.

8.3  Declaring and Creating Arrays (Cont.)

Common Programming Error 8.1In 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.

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

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.)

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

Jozef Goetz, 2012

148.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

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

Jozef Goetz, 2012

15 1 // Fig. 8.2: InitArray.cs

2 // Creating an array.

3 using System;

4

5 public class InitArray

6 {

7 public static void Main( string[] args )

8 {

9 int[] array; // declare array named array

10

11 // create the space for array and initialize to default zeros

12 array = new int[ 10 ]; // 10 int elements

13

14 Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // headings

15

16 // output each array element's value

17 for ( int counter = 0; counter < array.Length; counter++ )

18 Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] );

19 } // end Main {1,8} chr spaces

20 } // end class InitArray Index Value 0 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0

Outline

InitArray.cs

Declare array as an array of ints

Create 10 ints 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

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

2002 Prentice Hall.All rights reserved.

Outline16

1 // Fig. 7.3 ed1: InitArray.cs2 // Different ways of initializing 3 integer arrays.3 4 using System;5 using System.Windows.Forms;6 7 class InitArray8 {9 // main entry point for application10 static void Main( string[] args )11 {12 string output = "";13 14 int[] x; // declare reference to an array15 x = new int[ 10 ]; // dynamically allocate array and set16 // default values17 18 // initializer list specifies number of elements19 // and value of each element20 int[] y = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };21

22 const int ARRAY_SIZE = 10; // you cannot change constant later23 int[] z; // reference to int array24 25 // allocate array of ARRAY_SIZE (i.e., 10) elements26 z = new int[ ARRAY_SIZE ];27 28 // set the values in the array29 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 z

Initialize z to be of size ARRAY_SIZE

Initialize the elements in z using a for loop

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

2002 Prentice Hall.All rights reserved.

Outline17

InitArray.cs

Program Output

34 // output values for each array35 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 Main44 45 } // end class InitArray

Add values in the arrays to output

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

Jozef Goetz, 2012

18

1 // Fig. 8.3: InitArray.cs

2 // Initializing the elements of an array with an array initializer.

3 using System;

4

5 public class InitArray

6 {

7 public static void Main( string[] args )

8 {

9 // initializer list specifies the value for each element

10 int[] array = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 };

11

12 Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // headings

13

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.)

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

Jozef Goetz, 2012

19

14 // output each array element's value

15 for ( int counter = 0; counter < array.Length; counter++ )

16 Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] );

17 } // end Main

18 } // end class InitArray Index Value 0 32 1 27 2 64 3 18 4 95 5 14 6 90 7 70 8 60 9 37

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.

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

Jozef Goetz, 2012

20

1 // Fig. 8.4: InitArray.cs

2 // Calculating values to be placed into the elements of an array.

3 using System;

4

5 public class InitArray

6 {

7 public static void Main( string[] args )

8 {

9 const int ARRAY_LENGTH = 10; // create a named constant

10 int[] array = new int[ ARRAY_LENGTH ]; // create array

11

12 // calculate value for each array element

13 for ( int counter = 0; counter < array.Length; counter++ )

14 array[ counter ] = 2 + 2 * counter;

15

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.

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

Jozef Goetz, 2012

21

16 Console.WriteLine( "{0}{1,8}", "Index", "Value" ); // headings

17

18 // output each array element's value

19 for ( int counter = 0; counter < array.Length; counter++ )

20 Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] );

21 } // end Main

22 } // end class InitArray Index Value 0 2 1 4 2 6 3 8 4 10 5 12 6 14 7 16 8 18 9 20

Outline

InitArray.cs

( 2 of 2 )

Fig. 8.4 | Calculating values to be placed into the elements of an array. (Part 2 of 2.)

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

Jozef Goetz, 2012

22Good 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.

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

2002 Prentice Hall.All rights reserved.

Outline23

1 // Fig.7.4 ed1: SumArray.cs2 // Computing the sum of the elements in an array.3 4 using System;5 using System.Windows.Forms;6 7 class SumArray8 {9 // main entry point for application10 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 Main23 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.

1 // Fig. 8.5: SumArray.cs

2 // Computing the sum of the elements of an array.

3 using System;

4

5 public class SumArray

6 {

7 public static void Main( string[] args )

8 {

9 int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

10 int total = 0;

11

12 // add each element's value to total

13 for ( int counter = 0; counter < array.Length; counter++ )

14 total += array[ counter ];

15

16 Console.WriteLine( "Total of array elements: {0}", total );

17 } // end Main

18 } // end class SumArray

Total of array elements: 849

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

Jozef Goetz, 2012

24Using Histograms to Display Array Data Graphically

Present array values graphically Histogram

Plot each numeric value as bar of asterisks (*) Examine the distribution of grades

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

2002 Prentice Hall.All rights reserved.

Outline25

Histogram.cs

1 // Fig. 7.5 ed1: Histogram.cs2 // Using data to create a histogram. The nested for loops are used3 4 using System;5 using System.Windows.Forms;6 7 class Histogram8 {9 // main entry point for application10 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 output18 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 bar23 output += "*"; // using n [i]24 }25 26 MessageBox.Show( output, "Histogram Printing Program",27 MessageBoxButtons.OK, MessageBoxIcon.Information );28 29 } // end Main30 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.

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

Jozef Goetz, 2012

26 1 // Fig. 8.6: BarChart.cs

2 // Bar chart printing application.

3 using System;

4

5 public class BarChart

6 {

7 public static void Main( string[] args )

8 {

9 int[] array = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 };

10

11 Console.WriteLine( "Grade distribution:" );

12

13 // for each array element, output a bar of the chart

14 for ( int counter = 0; counter < array.Length; counter++ )

15 {

16 // output bar labels ( "00-09: ", ..., "90-99: ", "100: " )

17 if ( counter == 10 )

18 Console.Write( " 100: " );

19 else

20 Console.Write( "{0:D2}-{1:D2}: ", 21 counter * 10, counter * 10 + 9 ); // D2 – 2 digits must contain // as an integer format 22

23 // print bar of asterisks

24 for ( int stars = 0; stars < array[ counter ]; stars++ )

25 Console.Write( "*" );

Outline

BarChart.cs

26

27 Console.WriteLine(); // start a new line of output

28 } // end outer for

29 } // end Main

30 } // end class BarChart Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

For each array element, print associated number of asterisks

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

Jozef Goetz, 2012

278.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

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

Jozef Goetz, 2012

28 1 // Fig. 8.7: RollDie.cs

2 // Roll a six-sided die 6000 times.

3 using System;

4

5 public class RollDie

6 {

7 public static void Main( string[] args )

8 {

9 Random randomNumbers = new Random(); // random number generator

10 int[] frequency = new int[ 7 ]; // array of frequency counters

11

12 // roll die 6000 times; use die value as frequency index

13 for ( int roll = 1; roll <= 6000; roll++ )

14 ++frequency [ randomNumbers.Next( 1, 7 ) ]; // increase freq by 1

15

16 Console.WriteLine( "{0}{1,10}", "Face", "Frequency" );

17

18 // output each array element's value

19 for ( int face = 1; face < frequency.Length; face++ )

20 Console.WriteLine( "{0,4}{1,10}", face, frequency[ face ] );

21 } // end Main

22 } // end class RollDie Face Frequency 1 956 2 981 3 1001 4 1030 5 1035 6 997

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 ints

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

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

Jozef Goetz, 2012

29Using 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

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

2002 Prentice Hall.All rights reserved.

Outline30

RollDie.cs

1 // Fig. 7.6 ed1: RollDie.cs2 // 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 time4 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.Form13 {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 object

Declare an integer array frequency and allocate it enough memory to hold 7 integers

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

2002 Prentice Hall.All rights reserved.

Outline31

RollDie.cs

36 public RollDie()37 {38 InitializeComponent();39 }40 41 // Visual Studio .NET generated code42 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 will53 // randomly assign a face to each die54 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

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

2002 Prentice Hall.All rights reserved.

Outline32

RollDie.cs

// N – string as a decimal with 2 decimal places

71 72 displayTextBox.Text = "Face\tFrequency\tPercent\n"; // header73 74 // output frequency values75 for ( int x = 1; x < frequency.Length; x++ ) // starts from 176 {77 displayTextBox.Text += x + "\t" +78 frequency[ x ] + "\t\t" + String.Format( "{0:N}",79 frequency[ x ] / total * 100 ) + "%\n";80 }81 82 } // end Main83 84 // simulates roll, display proper85 // image and increment frequency86 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.

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

Jozef Goetz, 2012

33Using 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

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

2002 Prentice Hall.All rights reserved.

Outline34

StudentPoll.cs

1 // Fig. 7.7 ed1: StudentPoll.cs2 // A student poll program.3 4 using System;5 using System.Windows.Forms;6 7 class StudentPoll8 {9 // main entry point for application10 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 response20 for ( int answer = 0; answer < responses.Length; answer++ )21 ++frequency [responses [answer] ];22 23 output += "Rating\tFrequency\n";24 25 // output results26 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 Main33 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

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

Jozef Goetz, 2012

35 1 // Fig. 8.8 ed3: StudentPoll.cs console output

2 // Poll analysis application.

3 using System;

4

5 public class StudentPoll

6 {

7 public static void Main( string[] args )

8 {

9 // array of survey responses

10 int[] responses = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,

11 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,

12 4, 8, 6, 8, 10 };

13 int[] frequency = new int[ 11 ]; // array of frequency counters

14

15 // for each answer, select responses element and use that value

16 // as frequency index to determine element to increment

17 for ( int answer = 0; answer < responses.Length; answer++ )

18 ++frequency[ responses[ answer ] ];

19

20 Console.WriteLine( "{0}{1,10}", "Rating", "Frequency" );

Outline

StudentPoll.cs

Declare responses as array to store 40 responses

For each response, increment frequency values at index associated with that response

21

22 // output each array element's value

23 for ( int rating = 1; rating < frequency.Length; rating++ )

24 Console.WriteLine( "{0,6}{1,10}", rating, frequency[ rating ] );

25 } // end Main

26 } // end class StudentPoll

Rating Frequency 1 2 2 2 3 2 4 2 5 5 6 11 7 5 8 7 9 1 10 3

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

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

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

Jozef Goetz, 2012

378.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 anIndexOutOfRangeException to indicate thatan error occurred in the application at execution time.

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

Jozef Goetz, 2012

388.4  Examples Using Arrays (Cont.)

Error-Prevention Tip 8.1An 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.2When 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.

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

Jozef Goetz, 2012

398.5 Case Study: Card Shuffling and Dealing Simulation 1 // Fig. 8.9: Card.cs 2 // Card class represents a playing card.

3 public class Card

4 {

5 private string face; // face of card ("Ace", "Deuce", ...)

6 private string suit; // suit of card ("Hearts", "Diamonds", ...)

7

8 // two-parameter constructor initializes card's face and suit

9 public Card( string cardFace, string cardSuit )

10 {

11 face = cardFace; // initialize face of card

12 suit = cardSuit; // initialize suit of card

13 } // end two-parameter Card constructor

14

15 // return string representation of Card; see the output

16 public override string ToString()

17 {

18 return face + " of " + suit; // =>

19 } // end method ToString

20 } // end class Card

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

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

Jozef Goetz, 2012

40 1 // Fig. 8.10: DeckOfCards.cs

2 // DeckOfCards class represents a deck of playing cards.

3 using System;

4

5 public class DeckOfCards

6 {

7 private Card[] deck; // array of Card objects 8 private int currentCard; // index of next Card to be dealt

9 private const int NUMBER_OF_CARDS = 52; // constant number of Cards

10 private Random randomNumbers; // random number generator

11

12 // constructor fills deck of Cards 13 public DeckOfCards()

14 {

15 string[] faces = { "Ace", "Deuce", "Three", "Four", "Five", "Six",

16 "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

17 string[] suits = { "Hearts", "Diamonds", "Clubs", "Spades" };

18

19 deck = new Card[ NUMBER_OF_CARDS ]; // create array of Card objects

20 currentCard = 0; // set currentCard so first Card dealt is deck[ 0 ]

21 randomNumbers = new Random(); // create random number generator

22

23 // populate deck with Card objects 24 for ( int count = 0; count < deck.Length; count++ )

25 deck[ count ] =

26 new Card( faces[ count % 13 ], suits[ count / 13 ] );

27 } // end DeckOfCards constructor

Outline

DeckOfCards.cs

(1 of 2)

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

Jozef Goetz, 2012

4128

29 // shuffle deck of Cards with one-pass algorithm

30 public void Shuffle()

31 {

32 // after shuffling, dealing should start at deck[ 0 ] again

33 currentCard = 0; // reinitialize currentCard

34

35 // for each Card, pick another random Card and swap them 36 for ( int first = 0; first < deck.Length; first++ )

37 {

38 // select a random number between 0 and 51

39 int second = randomNumbers.Next( NUMBER_OF_CARDS );

40

41 // swap current Card with randomly selected Card 42 Card temp = deck[ first ];

43 deck[ first ] = deck[ second ];

44 deck[ second ] = temp;

45 } // end for

46 } // end method Shuffle

47

48 // deal one Card

49 public Card DealCard()

50 {

51 // determine whether Cards remain to be dealt

52 if ( currentCard < deck.Length ) 53 return deck[ currentCard++ ]; // return current Card object in array // and it’s the string representation ToString() method is used 54 else

55 return null; // return null to indicate that all Cards were dealt

56 } // end method DealCard

57 } // end class DeckOfCards

Outline

DeckOfCards.cs

(2 of 2)Swap current Card with randomly selected Card

Determine whether deck is empty

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

Jozef Goetz, 2012

42 1 // Fig. 8.11: DeckOfCardsTest.cs

2 // Card shuffling and dealing application.

3 using System;

4

5 public class DeckOfCardsTest

6 {

7 // execute application

8 public static void Main( string[] args )

9 {

10 DeckOfCards myDeckOfCards = new DeckOfCards();

11 myDeckOfCards.Shuffle(); // place Cards in random order

Outline

DeckOfCardsTest.cs

12

13 // print all 52 Cards in the order in which they are dealt

14 for ( int i = 0; i < 13; i++ )

15 {

16 // deal and print 4 concecutive Cards from deck

17 Console.WriteLine( "{0,-20}{1,-20}{2,-20}{3,-20}", // left justif.

18 myDeckOfCards.DealCard(), myDeckOfCards.DealCard(),

19 myDeckOfCards.DealCard(), myDeckOfCards.DealCard() ); //call //ToString() of class Card

20 } // end for

21 } // end Main

22 } // end class DeckOfCardsTest

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

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

Jozef Goetz, 2012

438.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

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

2002 Prentice Hall.All rights reserved.

Outline44

ForEach.cs

1 // Fig. 8.12 ed1: ForEach.cs2 // Demonstrating for/each structure.3 using System;4 5 class ForEach6 {7 // main entry point for the application8 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

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

Jozef Goetz, 2012

45

1 // Fig. 8.12: ForEachTest.cs

2 // Using the foreach statement to total integers in an array.

3 using System;

4

5 public class ForEachTest

6 {

7 public static void Main( string[] args )

8 {

9 int[] array = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

10 int total = 0;

11

12 // add each element's value to total

13 foreach ( int number in array )

14 total += number;

15

16 Console.WriteLine( "Total of array elements: {0}", total );

17 } // end Main

18 } // end class ForEachTest Total of array elements: 849

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.

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

Jozef Goetz, 2012

46Outline

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.

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

Jozef Goetz, 2012

478.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

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

Jozef Goetz, 2012

488.6  foreach Statement (Cont.)

Similarly, if myArray is an array of ints,

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.

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

Jozef Goetz, 2012

498.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 definitionpublic 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

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

Jozef Goetz, 2012

50Performance 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

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

Jozef Goetz, 2012

518.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.

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

2002 Prentice Hall.All rights reserved.

Outline52

PassArray.cs

1 // Fig. 8.13: PassArray.cs2 // 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.Form11 {12 private System.Windows.Forms.Button showOutputButton;13 private System.Windows.Forms.Label outputLabel;14 15 // Visual Studio .NET generated code16 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 a

Call method ModifyArray, pass array a as an argument by reference

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

2002 Prentice Hall.All rights reserved.

Outline53

PassArray.cs

36 37 outputLabel.Text += 38 "\n\nThe values of the modified array are:\n\t";39 40 // display elements of array a41 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-value49 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 modified57 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 it64 // original will not be modified65 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

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

2002 Prentice Hall.All rights reserved.

Outline54

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

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

Jozef Goetz, 2012

558.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 value 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

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

Jozef Goetz, 2012

568.8 Passing Arrays by Value and by Reference

Keyword ref may be used to pass arguments to method by reference: 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

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

Jozef Goetz, 2012

57Software 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.

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

2002 Prentice Hall.All rights reserved.

Outline58

ArrayReferenceTest.cs

1 // Fig. 8.14: ArrayReferenceTest.cs2 // Testing the effects of passing array references3 // 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.Form12 {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 firstArray26 int[] firstArray = { 1, 2, 3 };27 28 // copy firstArray reference29 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

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

2002 Prentice Hall.All rights reserved.

Outline59

ArrayReferenceTest.cs

36 37 // print contents of firstArray38 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 firstArray48 for ( int i = 0; i < firstArray.Length; i++ )49 outputLabel.Text += firstArray[ i ] + " ";50 51 // test whether reference was changed by FirstDouble52 if ( firstArray == firstArrayCopy )53 outputLabel.Text += 54 "\n\nThe references refer to the same array\n";55 else56 outputLabel.Text += 57 "\n\nThe references refer to different arrays\n";58 //part II59 // create and initialize secondArray60 int[] secondArray = { 1, 2, 3 };61 62 // copy secondArray reference63 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 firstArray

Test whether firstArray and firstArrayCopy reference the same object

Declare and initialize integer array secondArray

Declare integer array secondArrayCopy and set it to reference secondArray

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

2002 Prentice Hall.All rights reserved.

Outline60

ArrayReferenceTest.cs

71 // print contents of secondArray before method call72 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 call81 for ( int i = 0; i < secondArray.Length; i++ )82 outputLabel.Text += secondArray[ i ] + " ";83 84 // test whether reference was changed by SecondDouble85 if (secondArray == secondArrayCopy)86 outputLabel.Text += 87 "\n\nThe references refer to the same array\n";88 else89 outputLabel.Text += 90 "\n\nThe references refer to different arrays\n"; 91 92 } // end method showOutputButton_Click93 94 // modify elements of array and attempt to modify95 // reference 96 void FirstDouble( int[] array )97 {98 // double each element's value99 for ( int i = 0; i < array.Length; i++ )100 array[ i ] *= 2;101 102 // create new reference and assign it to array103 array = new int[] { 11, 12, 13 }; // reference copy is changed, not the original reference104 }105

Output contents of secondArray

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

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

2002 Prentice Hall.All rights reserved.

Outline61

ArrayReferenceTest.cs

Program Output

106 // modify elements of array and change reference array107 // to refer to a new array – the same body108 void SecondDouble( ref int[] array )109 {110 // double each element's value111 for ( int i = 0; i < array.Length; i++ )112 array[ i ] *= 2;113 114 // create new reference and assign it to array115 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

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

Jozef Goetz, 2012

628.9 Case Study: Class GradeBook Using an Array to Store Grades 1 // Fig. 8.15: GradeBook.cs extension in Fig.8.21

2 // Grade book using an array to store test grades.

3 using System;

4

5 public class GradeBook

6 {

7 private string courseName; // name of course this GradeBook represents

8 private int[] grades; // array of student grades

9

10 // two-parameter constructor initializes courseName and grades array

11 public GradeBook( string name, int[] gradesArray )

12 {

13 CourseName = name; // initialize courseName

14 grades = gradesArray; // initialize grades array

15 } // end two-parameter GradeBook constructor

16

17 // property that gets and sets the course name

18 public string CourseName

19 {

20 get

21 {

22 return courseName;

23 } // end get

24 set

25 {

26 courseName = value;

27 } // end set

28 } // end property CourseName

Outline

GradeBook.cs

(1 of 6)

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

Jozef Goetz, 2012

6329

30 // display a welcome message to the GradeBook user

31 public void DisplayMessage()

32 {

33 // CourseName property gets the name of the course

34 Console.WriteLine( "Welcome to the grade book for\n{0}!\n",

35 CourseName );

36 } // end method DisplayMessage

37

38 // perform various operations on the data

39 public void ProcessGrades()

40 { 41 // output grades array 42 OutputGrades();

43

44 // call method GetAverage to calculate the average grade

45 Console.WriteLine( "\nClass average is {0:F2}", GetAverage() );

46

47 // call methods GetMinimum and GetMaximum

48 Console.WriteLine( "Lowest grade is {0}\nHighest grade is {1}\n",

49 GetMinimum(), GetMaximum() );

Outline

GradeBook.cs

(2 of 6)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

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

Jozef Goetz, 2012

6450

51 // call OutputBarChart to print grade distribution chart

52 OutputBarChart();

53 } // end method ProcessGrades

54

55 // find minimum grade

56 public int GetMinimum()

57 {

58 int lowGrade = grades[ 0 ]; // assume grades[ 0 ] is smallest

59

60 // loop through grades array

61 foreach ( int grade in grades )

62 {

63 // if grade lower than lowGrade, assign it to lowGrade

64 if ( grade < lowGrade )

65 lowGrade = grade; // new lowest grade

66 } // end for

67

68 return lowGrade; // return lowest grade

69 } // end method GetMinimum

Outline

GradeBook.cs

(3 of 6)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

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

Jozef Goetz, 2012

6570

71 // find maximum grade

72 public int GetMaximum()

73 {

74 int highGrade = grades[ 0 ]; // assume grades[ 0 ] is largest

75

76 // loop through grades array

77 foreach ( int grade in grades )

78 {

79 // if grade greater than highGrade, assign it to highGrade

80 if ( grade > highGrade )

81 highGrade = grade; // new highest grade

82 } // end for

83

84 return highGrade; // return highest grade

85 } // end method GetMaximum

86

87 // determine average grade for test

88 public double GetAverage()

89 {

90 int total = 0; // initialize total

91

92 // sum grades for one student

93 foreach ( int grade in grades )

94 total += grade;

95

96 // return average of grades

97 return ( double ) total / grades.Length;

98 } // end method GetAverage

Outline

GradeBook.cs

(4 of 6)

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

Jozef Goetz, 2012

6699

100 // output bar chart displaying grade distribution

101 public void OutputBarChart()

102 {

103 Console.WriteLine( "Grade distribution:" );

104

105 // stores frequency of grades in each range of 10 grades

106 int[] frequency = new int[ 11 ];

107

108 // for each grade, increment the appropriate frequency

109 foreach ( int grade in grades )

110 ++frequency[ grade / 10 ];

111

112 // for each grade frequency, print bar in chart

113 for ( int count = 0; count < frequency.Length; count++ )

114 {

115 // output bar label ( "00-09: ", ..., "90-99: ", "100: " )

116 if ( count == 10 )

117 Console.Write( " 100: " );

118 else

119 Console.Write( "{0:D2}-{1:D2}: ",

120 count * 10, count * 10 + 9 );

121

122 // print bar of asterisks

123 for ( int stars = 0; stars < frequency[ count ]; stars++ )

124 Console.Write( "*" );

125

126 Console.WriteLine(); // start a new line of output

127 } // end outer for

128 } // end method OutputBarChart

Outline

GradeBook.cs

(5 of 6)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

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

Jozef Goetz, 2012

67129

130 // output the contents of the grades array

131 public void OutputGrades()

132 {

133 Console.WriteLine( "The grades are:\n" );

134

135 // output each student's grade

136 for ( int student = 0; student < grades.Length; student++ )

137 Console.WriteLine( "Student {0,2}: {1,3}",

138 student + 1, grades[ student ] );

139 } // end method OutputGrades

140 } // end class GradeBook

Outline

GradeBook.cs

(6 of 6)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

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

Jozef Goetz, 2012

68 1 // Fig. 8.16: GradeBookTest.cs

2 // Create GradeBook object using an array of grades.

3 public class GradeBookTest

4 {

5 // Main method begins application execution

6 public static void Main( string[] args )

7 {

8 // one-dimensional array of student grades

9 int[] gradesArray = { 87, 68, 94, 100, 83, 78, 85, 91, 76, 87 };

10

11 GradeBook myGradeBook = new GradeBook(

12 "CS101 Introduction to C# Programming", gradesArray );

13 myGradeBook.DisplayMessage();

14 myGradeBook.ProcessGrades();

15 } // end Main

16 } // end class GradeBookTest

Outline

GradeBookTest.cs

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Student 1: 87 Student 2: 68 Student 3: 94 Student 4: 100 Student 5: 83 Student 6: 78 Student 7: 85 Student 8: 91 Student 9: 76 Student 10: 87 Class average is 84.90 Lowest grade is 68 Highest grade is 100 Grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: * 70-79: ** 80-89: **** 90-99: ** 100: *

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

Jozef Goetz, 2012

69Using 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

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

Jozef Goetz, 2012

70

8.8  Passing Arrays by Value and by Reference (Cont.)

Software Engineering Observation 8.1When 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.2In 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.

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

Jozef Goetz, 2012

718.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

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

Jozef Goetz, 2012

728.10 Multiple-Subscripted Arrays

Fig. 8.17 Double-subscripted array with three rows and four columns.

Row 0

Row 1

Row 2

Column 1Column 0 Column 2 Column 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]

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

Jozef Goetz, 2012

738.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

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

Jozef Goetz, 2012

748.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 } };

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

Jozef Goetz, 2012

758.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}};

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

Jozef Goetz, 2012

76 1 // Fig. 8.19: InitArray.cs

2 // Initializing rectangular and jagged arrays.

3 using System;

4

5 public class InitArray

6 {

7 // create and output rectangular and jagged arrays

8 public static void Main( string[] args )

9 {

10 // with rectangular arrays,

11 // every column must be the same length.

12 int[ , ] rectangular = { { 1, 2, 3 }, { 4, 5, 6 } };

13

14 // with jagged arrays,

15 // we need to use "new int[]" for every row,

16 // but every column does not need to be the same length.

17 int[][] jagged = { new int[] { 1, 2 },

18 new int[] { 3 },

19 new int[] { 4, 5, 6 } };

20

21 OutputArray( rectangular ); // displays array rectangular by row

22 Console.WriteLine(); // output a blank line

23 OutputArray( jagged ); // displays array jagged by row

24 } // end Main

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

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

Jozef Goetz, 2012

7725

26 // output rows and columns of a rectangular array

27 public static void OutputArray( int[ , ] array )

28 {

29 Console.WriteLine( "Values in the rectangular array by row are" );

30

31 // loop through array's rows

32 for ( int row = 0; row < array.GetLength( 0 ); row++ )

33 {

34 // loop through columns of current row

35 for ( int column = 0; column < array.GetLength( 1 ); column++ )

36 Console.Write( "{0} ", array[ row, column ] );

37

38 Console.WriteLine(); // start new line of output

39 } // end outer for

40 } // end method OutputArray

Outline

Iterates through each of the array’s “rows”

Passes in a “rectangular” array

Iterates through each of the array’s “columns”,

2nd dimension

GetLength returns the length of 1st dimension

Values in the rectangular array by row are1 2 3 4 5 6 Values in the jagged array by row are1 2 3 4 5 6

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

Jozef Goetz, 2012

7841

42 // output rows and columns of a jagged array

43 public static void OutputArray( int[][] array )

44 {

45 Console.WriteLine( "Values in the jagged array by row are" );

46

47 // loop through array's rows

48 for ( int row = 0; row < array.Length; row++ )

49 {

50 // loop through columns of current row

51 for ( int column = 0; column < array[ row ].Length; column++ )

52 Console.Write( "{0} ", array[ row ][ column ] );

53

54 Console.WriteLine(); // start new line of output

55 } // end outer for

56 } // end method OutputArray

57 } // end class InitArray

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

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

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

Jozef Goetz, 2012©1992-2011 by Pearson Education, Inc. All Rights Reserved.

Values in the jagged array by row are1 2 3 4 5 6

Iterations in a “jagged” array use the foreach control structure

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

2002 Prentice Hall.All rights reserved.

Outline80

DoubleArray.cs

1 // Fig. 7.15 ed1 DoubleArray.cs2 // Manipulating a double-subscripted array.3 // Find min and max grade of any student for the semester4 // each row of the array represent a student5 // each column of the array represent a grade3 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.Form11 {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 code19 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 rows

Initialize each element in array grades

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

2002 Prentice Hall.All rights reserved.

Outline81

DoubleArray.cs

35 students = grades.Length; // number of students- # of rows36 exams = grades[ 0 ].Length; // number of exams37 38 // line up column headings39 outputLabel.Text += " ";40 41 // output the column headings42 for ( int i = 0; i < exams; i++ )43 outputLabel.Text += "[" + i + "] ";44 45 // output the rows46 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 row60 61 } // end method showOutputButton_Click62

Output each row

Output each element of the row

Output the minimum and maximum grades

Output the average for each row

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

2002 Prentice Hall.All rights reserved.

Outline82

DoubleArray.cs

63 // find minimum grade in grades array64 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 array79 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

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

2002 Prentice Hall.All rights reserved.

Outline83

DoubleArray.cs

Program Output

93 // determine average grade for a particular student94 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

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

Jozef Goetz, 2012

84 1 // Fig. 8.20: GradeBook.cs Console solution

2 // Grade book using rectangular array to store grades.

3 using System;

4

5 public class GradeBook

6 {

7 private string courseName; // name of course this grade book represents

8 private int[ , ] grades; // rectangular array of student grades

9

10 // two-parameter constructor initializes courseName and grades array

11 public GradeBook( string name, int[ , ] gradesArray )

12 {

13 CourseName = name; // initialize courseName

14 grades = gradesArray; // initialize grades array

15 } // end two-parameter GradeBook constructor

16

17 // property that gets and sets the course name

18 public string CourseName

19 {

20 get

21 {

22 return courseName;

23 } // end get

24 set

25 {

26 courseName = value;

27 } // end set

28 } // end property CourseName

Outline

GradeBook.cs

(1 of 7)

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

Jozef Goetz, 2012

8529

30 // display a welcome message to the GradeBook user

31 public void DisplayMessage()

32 {

33 // CourseName property gets the name of the course

34 Console.WriteLine( "Welcome to the grade book for\n{0}!\n",

35 CourseName );

36 } // end method DisplayMessage

37

38 // perform various operations on the data

39 public void ProcessGrades()

40 {

41 // output grades array

42 OutputGrades();

43

44 // call methods GetMinimum and GetMaximum

45 Console.WriteLine( "\n{0} {1}\n{2} {3}\n",

46 "Lowest grade in the grade book is", GetMinimum(),

47 "Highest grade in the grade book is", GetMaximum() );

48

49 // output grade distribution chart of all grades on all tests

50 OutputBarChart();

51 } // end method ProcessGrades

Outline

GradeBook.cs

(2 of 7)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: *** 70-79: ****** 80-89: *********** 90-99: ******* 100: ***

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

Jozef Goetz, 2012

8652

53 // find minimum grade

54 public int GetMinimum()

55 {

56 // assume first element of grades array is smallest

57 int lowGrade = grades[ 0, 0 ];

58

59 // loop through elements of rectangular grades array

60 foreach ( int grade in grades )

61 {

62 // if grade less than lowGrade, assign it to lowGrade

63 if ( grade < lowGrade )

64 lowGrade = grade;

65 } // end foreach

66

67 return lowGrade; // return lowest grade

68 } // end method GetMinimum

Outline

GradeBook.cs

(3 of 7)

Loop through array to find the lowest grade of any student

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

Jozef Goetz, 2012

8769

70 // find maximum grade

71 public int GetMaximum()

72 {

73 // assume first element of grades array is largest

74 int highGrade = grades[ 0, 0 ];

75

76 // loop through elements of rectangular grades array

77 foreach ( int grade in grades )

78 {

79 // if grade greater than highGrade, assign it to highGrade

80 if ( grade > highGrade )

81 highGrade = grade;

82 } // end foreach

83

84 return highGrade; // return highest grade

85 } // end method GetMaximum

86

87 // determine average grade for particular student

88 public double GetAverage( int student )

89 {

90 // get the number of grades per student

91 int amount = grades.GetLength( 1 );

92 int total = 0; // initialize total

93

94 // sum grades for one student

95 for ( int exam = 0; exam < amount; exam++ )

96 total += grades[ student, exam ];

Outline

GradeBook.cs

(4 of 7)

Loop through array to find the highest grade of any student

Calculate a particular student’s average

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

Jozef Goetz, 2012

8897

98 // return average of grades

99 return ( double ) total / amount;

100 } // end method GetAverage

101

102 // output bar chart displaying overall grade distribution

103 public void OutputBarChart()

104 {

105 Console.WriteLine( "Overall grade distribution:" );

106

107 // stores frequency of grades in each range of 10 grades

108 int[] frequency = new int[ 11 ];

109

110 // for each grade in GradeBook, increment the appropriate frequency

111 foreach ( int grade in grades )

112 {

113 ++frequency[ grade / 10 ];

114 } // end foreach

115

116 // for each grade frequency, print bar in chart

117 for ( int count = 0; count < frequency.Length; count++ )

118 {

119 // output bar label ( "00-09: ", ..., "90-99: ", "100: " )

120 if ( count == 10 )

121 Console.Write( " 100: " );

122 else

123 Console.Write( "{0:D2}-{1:D2}: ",

124 count * 10, count * 10 + 9 );

Outline

GradeBook.cs

(5 of 7)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: *** 70-79: ****** 80-89: *********** 90-99: ******* 100: ***

Calculate the distribution of all

student grades

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

Jozef Goetz, 2012

89125

126 // print bar of asterisks

127 for ( int stars = 0; stars < frequency[ count ]; stars++ )

128 Console.Write( "*" );

129

130 Console.WriteLine(); // start a new line of output

131 } // end outer for

132 } // end method OutputBarChart

133

134 // output the contents of the grades array

135 public void OutputGrades()

136 {

137 Console.WriteLine( "The grades are:\n" );

138 Console.Write( " " ); // align column heads

139

140 // create a column heading for each of the tests

141 for ( int test = 0; test < grades.GetLength( 1 ); test++ )

142 Console.Write( "Test {0} ", test + 1 );

143

144 Console.WriteLine( "Average" ); // student average column heading

Outline

GradeBook.cs

(6 of 7)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: *** 70-79: ****** 80-89: *********** 90-99: ******* 100: ***

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

Jozef Goetz, 2012

90145

146 // create rows/columns of text representing array grades

147 for ( int student = 0; student < grades.GetLength( 0 ); student++ )

148 {

149 Console.Write( "Student {0,2}", student + 1 );

150

151 // output student's grades

152 for ( int grade = 0; grade < grades.GetLength( 1 ); grade++ )

153 Console.Write( "{0,8}", grades[ student, grade ] );

154

155 // call method GetAverage to calculate student's average grade;

156 // pass row number as the argument to GetAverage

157 Console.WriteLine( "{0,9:F2}", GetAverage( student ) );

158 } // end outer for

159 } // end method OutputGrades

160 } // end class GradeBook

Outline

GradeBook.cs

(7 of 7)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: *** 70-79: ****** 80-89: *********** 90-99: ******* 100: ***

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

Jozef Goetz, 2012

91 1 // Fig. 8.21: GradeBookTest.cs

2 // Create GradeBook object using a rectangular array of grades.

3 public class GradeBookTest

4 {

5 // Main method begins application execution

6 public static void Main( string[] args )

7 {

8 // rectangular array of student grades

9 int[ , ] gradesArray = { { 87, 96, 70 },

10 { 68, 87, 90 },

11 { 94, 100, 90 },

12 { 100, 81, 82 },

13 { 83, 65, 85 },

14 { 78, 87, 65 },

15 { 85, 75, 83 },

16 { 91, 94, 100 },

17 { 76, 72, 84 },

18 { 87, 93, 73 } };

19

20 GradeBook myGradeBook = new GradeBook(

21 "CS101 Introduction to C# Programming", gradesArray );

22 myGradeBook.DisplayMessage();

23 myGradeBook.ProcessGrades();

24 } // end Main

25 } // end class GradeBookTest

GradeBookTest.cs

(1 of 2)

Welcome to the grade book for CS101 Introduction to C# Programming! The grades are: Test 1 Test 2 Test 3 Average Student 1 87 96 70 84.33 Student 2 68 87 90 81.67 Student 3 94 100 90 94.67 Student 4 100 81 82 87.67 Student 5 83 65 85 77.67 Student 6 78 87 65 76.67 Student 7 85 75 83 81.00 Student 8 91 94 100 95.00 Student 9 76 72 84 77.33 Student 10 87 93 73 84.33 Lowest grade in the grade book is 65 Highest grade in the grade book is 100 Overall grade distribution: 00-09: 10-19: 20-29: 30-39: 40-49: 50-59: 60-69: *** 70-79: ****** 80-89: *********** 90-99: ******* 100: ***

Declare gradesArray as 3-by-10 array

Each row represents a student; each column represents an exam grade

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

Jozef Goetz, 2012

928.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

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

Jozef Goetz, 2012

93 1 // Fig. 8.22: VarargsTest.cs

2 // Using variable-length argument lists.

3 using System;

4

5 public class VarargsTest

6 {

7 // calculate average

8 public static double Average( params double[] numbers )

9 { // params indicates the method receives a variable # of arguments // (all of the same type) with the array’s elements

10 double total = 0.0; // initialize total

11

12 // calculate total using the foreach statement

13 foreach ( double d in numbers )

14 total += d;

15

16 return total / numbers.Length;

17 } // end method Average

Outline

VarargsTest.cs

18

19 public static void Main( string[] args )

20 {

21 double d1 = 10.0;

22 double d2 = 20.0;

23 double d3 = 30.0;

24 double d4 = 40.0;

25

26 Console.WriteLine(

27 "d1 = {0:F1}\nd2 = {1:F1}\nd3 = {2:F1}\nd4 = {3:F1}\n",

28 d1, d2, d3, d4 );

29

30 Console.WriteLine( "Average of d1 and d2 is {0:F1}",

31 Average( d1, d2 ) );

32 Console.WriteLine( "Average of d1, d2 and d3 is {0:F1}",

33 Average( d1, d2, d3 ) );

34 Console.WriteLine( "Average of d1, d2, d3 and d4 is {0:F1}",

35 Average( d1, d2, d3, d4 ) );

36 } // end Main

37 } // end class VarargsTest

d1 = 10.0 d2 = 20.0 d3 = 30.0 d4 = 40.0 Average of d1 and d2 is 15.0 Average of d1, d2 and d3 is 20.0 Average of d1, d2, d3 and d4 is 25.0

Method Average receives a variable length sequence of doubles

Calculate the total of the doubles in the array

Access numbers.length to obtain the size of the numbers array

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

Jozef Goetz, 2012

94Common 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.

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

Jozef Goetz, 2012

958.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,…

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

Jozef Goetz, 2012

968.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 ]

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

Jozef Goetz, 2012

97 1 // Fig. 8.23: InitArray.cs

2 // Using command-line arguments to initialize an array.

3 using System;

4

5 public class InitArray

6 {

7 public static void Main( string[] args )

8 {

9 // check number of command-line arguments

10 if ( args.Length != 3 )

11 Console.WriteLine(

12 "Error: Please re-enter the entire command, including\n" +

13 "an array size, initial value and increment." );

14 else

15 {

16 // get array size from first command-line argument

17 int arrayLength = Convert.ToInt32( args[ 0 ] );

18 int[] array = new int[ arrayLength ]; // create array

19

20 // get initial value and increment from command-line argument

21 int initialValue = Convert.ToInt32( args[ 1 ] );

22 int increment = Convert.ToInt32( args[ 2 ] );

23

24 // calculate value for each array element

25 for ( int counter = 0; counter < array.Length; counter++ )

26 array[ counter ] = initialValue + increment * counter;

27 // display a header

28 Console.WriteLine( "{0}{1,8}", "Index", "Value" );

InitArray.cs (1 of 2)

C:\Examples\ch08\fig08_21>InitArray.exe 10 1 2 // 3 arguments are passed to appsIndex 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

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

Jozef Goetz, 2012

9829

30 // display array index and value

31 for ( int counter = 0; counter < array.Length; counter++ )

32 Console.WriteLine( "{0,5}{1,8}", counter, array[ counter ] );

33 } // end else

34 } // end Main

35 } // end class InitArray

C:\Examples\ch08\fig08_21>InitArray.exe Error: Please re-enter the entire command, including an array size, initial value and increment.

Outline

InitArray.cs

(2 of 2)

C:\Examples\ch08\fig08_21>InitArray.exe 5 0 4 // 3 arguments are passed to apps Index Value 0 0 1 4 2 8 3 12 4 16 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

Missing command-line arguments

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

Jozef Goetz, 2012

99Enter the size of an array by the userinstead 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