1. collections are data structures that holds data in different ways for flexible operations c#...

87
Chapter 8 Arrays 1

Upload: abel-hampton

Post on 16-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Chapter 8Arrays

1

Page 2: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Collections

Collections are data structures that holds data in different ways for flexible operations

C# Collection classes are defined as part of the◦ System.Collections or ◦ System.Collections.Generic namespace.

2

Page 3: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.2 Arrays Arrays hold a fixed number of elements, all of the same type.

Initializ

ed to 0

3

Page 4: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.2 Arrays

Zero-

based

4

Page 5: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.3 Declaring and Creating Arrays

int[] c; // declare the array variablec = new int[ 12 ]; // create the array; assign to array variable

5

Page 6: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Array Initializing

6

Page 7: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Bounds Checking

public class ArraysBasics

{

public static void Main(string[] args)

{

int[] manyValues = {100, 101, 103, 200};

manyValues[5] = 100;

}

}

7

Page 8: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

size

Arrays are fixed in size, once declared, that's just how big they are

This allows arrays to be contiguous somewhere in the computer's memory, which is very efficient for the processor to access and change them.

Array elements are all the same type

8

Page 9: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.4 Examples Using Arrays

9

Page 10: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Format Strings in Console.WriteLine methodPositive values add padding to the left, negative add padding to the right

Sample OutputString.Format("[{0, 10}]", "Foo"); [·······Foo]String.Format("[{0, 5}]", "Foo"); [··Foo]String.Format("[{0, -5}]", "Foo"); [Foo··]String.Format("[{0, -10}]", "Foo"); [Foo·······]

10

Page 11: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

11

Page 12: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

12

Named

Constant

Page 13: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

13

Page 14: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Named Constants

int[] intList = new int[100];String[] strList=new String[100];…for (index = 0;index<100; index++) { …}for (index = 0; index<100;index++) { …}

const int SIZE= 100;int[] intList = new int[SIZE];String[] strList=new String[SIZE];…for (index = 0; index< SIZE;index++) { …}for (index = 0; index< SIZE;index++) {…}

Page 15: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

15

Page 16: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

16

Page 17: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

// Fig. 8.6: BarChart.cs// Bar chart displaying application.using System;

public class BarChart{ public static void Main( string[] args ) { int[] array = { 0, 0, 0, 0, 0, 0, 1, 2, 4, 2, 1 }; // distribution

Console.WriteLine( "Grade distribution:" );

// for each array element, output a bar of the chart for ( int counter = 0; counter < array.Length; counter++ ) { // output bar labels ( "00-09: ", ..., "90-99: ", "100: " ) if ( counter == 10 ) Console.Write( " 100: " ); else Console.Write( "{0:D2}-{1:D2}: ", counter * 10, counter * 10 + 9 );

// display bar of asterisks for ( int stars = 0; stars < array[ counter ]; stars++ ) Console.Write( "*" );

Console.WriteLine(); // start a new line of output } // end outer for }} 17

Page 18: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

18

Page 19: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

19

Page 20: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

IndexOutOfRangeException

Ex: Twenty students were asked to rate on a scale of 1 to 5

the quality of the food in the student cafeteria, with 1 being “awful” and 5 being “excellent.”

Place the 20 responses in an integer array and determine the frequency of each rating.

20

Page 21: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

21

six-element array frequency counts the number of occurrences of each response. Each element is used as a counter for one of the possible types of survey responses—frequency[1] counts the number of students who rated the food as 1, frequency[2] counts the number of students who rated the food as 2, and so on.

Page 22: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

How it works

When the counter answer is 0, responses[answer] is the value of responses[0]

(that is, 1—see line 10). In this case, frequency[responses[answer]] is interpreted

as frequency[1], and the counter frequency[1] is incremented by one.

To evaluate the expression, we begin with the value in the innermost set of brackets

(answer, currently 0). The value of answer is plugged into the expression, and

the next set of brackets (responses[answer]) is evaluated. That value is used as

the index for the frequency array to determine which counter to increment (in

this case, frequency[1]).

The next time through the loop answer is 1, responses[answer] is the value of

responses[1] (that is, 2—see line 10), so frequency[responses[answer]] is interpreted

as frequency[2], causing frequency[2] to be incremented.

When answer is 2, responses[answer] is the value of responses[2] (that is, 5—

see line 10), so frequency[responses[answer]] is interpreted as frequency[5],

causing frequency[5] to be incremented, and so on.

22

Page 23: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Exception Handling Basics

An exception indicates a problem that occurs while a program executes.

The name “exception” suggests that the problem occurs infrequently—if the “rule” is that a statement normally executes correctly, then the problem represents the “exception to the rule.”

Exception handling enables you to create fault-tolerant programs that can resolve (or handle) exceptions. In many cases, this allows a program to continue executing as if no

problems were encountered.

23

Page 24: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

try catch block

The try Statement

To handle an exception, place any code that might throw an exception in a try statement

The try block contains the code that might throw an exception,

and the catch block contains the code that handles the exception if one

occurs.

You can have many catch blocks to handle different types of exceptions that might

be thrown in the corresponding try block.

The braces that delimit the bodies of the try and catch blocks are required.

24

Page 25: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Executing the catch Block

When the program encounters the value 14 in the responses array, it attempts to add 1

to frequency[14], which does not exist—the frequency array has only six elements.

Because array bounds checking is performed at execution time, the Common Language

Runtime generates an exception—specifically line 20 throws an

IndexOutOfRangeException to notify the program of this problem. At this point the try block terminates and the catch block begins executing—if you declared any variables in the try block, they’re now out of scope and are not accessible in the catch block.

The catch block declares a type (IndexOutOfRangeException) and an exception

parameter (ex). The catch block can handle exceptions of the specified type. Inside the

catch block, you can use the parameter’s identifier to interact with a caught exception object.

25

Page 26: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

26

Page 27: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

27

Page 28: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.5 Case Study: Card Shuffling and Dealing Simulation

28

Page 29: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

29

Page 30: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

30

Page 31: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

31

Page 32: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

32

Page 33: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

33

Page 34: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.6 foreach Statement

34

Page 35: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

35

Page 36: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Arrays are Objects

36

using System;

Page 37: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Ex: Arrays are Objects

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Arrays

{

class Program

{

static void Main(string[] args)

{

int[] manyValues = { 1, 18, 745, 34, 16, 94, 73, 4, 17, 200 };

Console.WriteLine("The fourth number is {0}", manyValues[3]);

int[] otherValues = manyValues;

otherValues[3] = 0;

Console.WriteLine("The fourth number is {0}", manyValues[3]);

Console.WriteLine("The fourth number is {0}", otherValues[3]);

Array.Sort(manyValues);

Console.WriteLine("The fourth number is {0}", manyValues[3]);

Console.ReadLine();

}

}

}37

Page 38: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.7 Passing Arrays and Array Elements to Methods

38

Page 39: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Passing by Reference (by Value!)

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.

However, 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 as an argument in the method call.

39

Page 40: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

40

Page 41: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

41

Page 42: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.8 Passing Arrays by Value and by Reference

42

Page 43: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Passing Reference-type by Reference! cont

In C#, a variable that “stores” an object, such as an array, does not actually store the object itself. Instead, such a variable stores a reference to the object.

The distinction between reference-type variables and value-type variables raises some subtle.

When an application passes an argument to a method, the called method receives a copy of that argument’s value. Changes to the local copy in the called method do not affect the original variable in the caller. ◦ If the argument is of a reference type, the method makes a copy of the reference,

not a copy of the actual object that’s referenced.◦ The local copy of the reference also refers to the original object, which means

that changes to the object in the called method affect the original object

If you want to pass a value-type array element to a method by reference, you must use the ref keyword.

43

Page 44: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Passing Reference-type by Reference! Cont(ref and out)

ref can be used to pass a reference-type variable by reference,

which allows the called method to modify the original variable in the caller and make that variable refer to a different object. This is a subtle capability, which, if misused, can lead to problems.

For instance, when a reference-type object like an array is passed with ref, the called method actually gains control over the reference itself, allowing the called method to replace the original reference in the caller with a reference to a different object, or even with null!

Such behavior can lead to unpredictable effects, which can be disastrous in mission-critical applications.

44

Page 45: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

45

Page 46: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

46

Page 47: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

47

Page 48: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

48

Page 49: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

49

Page 50: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

50

Page 51: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

51

Page 52: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.9 Case Study: Class GradeBook Using an Array to Store Grades

52

Page 53: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

53

Page 54: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

54

Page 55: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

55

Page 56: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

56

Page 57: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

57

Page 58: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

58

Page 59: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

59

Page 60: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

60

Page 61: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

61

Page 62: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Multidimensional Arrays

62

ro

wcolumn

Page 63: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Multidimensional Arrays Initialization(ex.: 3x3)

63

Page 64: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.10 Multidimensional Arrays

64

Page 65: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.10 Multidimensional Jagged Arrays

65

• A jagged array is maintained as a one-dimensional array in which each element refers to a one-dimensional array.

• The manner in which jagged arrays are represented makes them quite flexible, because the lengths of the rows in the array need not be the same.

• Ex: jagged arrays could be used to store a single student’s exam grades across multiple classes, where the number of exams may vary from class to class.

• We can access the elements in a jagged array by an array-access expression of the form

arrayName[row][column]

• similar to the array-access expression for rectangular arrays, but with a separate set of square brackets for each dimension.

Page 66: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

Ex.: Jagged Arrayint[][] jagged = { new int[] { 1, 2 },

new int[] { 3 },

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

1 initializes jagged[0][0]

2 initializes jagged[0][1]

3 initializes jagged[1][0]

4 initializes jagged[2][0]

5 initializes jagged[2][1]

6 initializes jagged[2][2] jagged in the preceding declaration is actually composed of four

separate one-dimensional arrays—one that represents the rows, one containing the values in the first row ({1, 2}), one containing the value in the second row ({3}) and one containing the values in the third row ({4, 5, 6}).

Thus, array jagged itself is an array of three elements, each a reference to a one-dimensional array of int values.

66

Page 67: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

67

Page 68: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

68

Page 69: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

69

Page 70: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

70

Page 71: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.11 Case Study: Class GradeBook Using a Rectangular Array

71

Page 72: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

72

Page 73: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

73

Page 74: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

74

Page 75: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

75

Page 76: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

76

Page 77: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

77

Page 78: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

78

Page 79: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

79

Page 80: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

80

Page 81: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

81

Page 82: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.12 Variable-Length Argument Lists

82

Page 83: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

83

Page 84: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

84

Page 85: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

8.13 Using Command-Line Arguments

85

Page 86: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

86

Page 87: 1.  Collections are data structures that holds data in different ways for flexible operations  C# Collection classes are defined as part of the ◦ System.Collections

87