Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 1

2  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

3 Arrays hold a fixed number of elements, all of the same type. Initialized to 0 3

4 Zero- based 4

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

6 6

7 public class ArraysBasics { public static void Main(string[] args) { int[] manyValues = {100, 101, 103, 200}; manyValues[5] = 100; } 7

8  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

9 9

10 Format Strings in Console.WriteLine method Positive values add padding to the left, negative add padding to the right Sample Output String.Format("[{0, 10}]", "Foo"); [·······Foo] String.Format("[{0, 5}]", "Foo"); [··Foo] String.Format("[{0, -5}]", "Foo"); [Foo··] String.Format("[{0, -10}]", "Foo"); [Foo·······] 10

11 11

12 12 Named Constant

13 13

14 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++) { … }

15 15

16 16

17 // 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

18 18

19 19

20 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

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

22 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

23  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

24 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

25 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

26 26

27 27

28 28

29 29

30 30

31 31

32 32

33 33

34 34

35 35

36 36 using System;

37 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

38 38

39  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

40 40

41 41

42 42

43  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 ref  If you want to pass a value-type array element to a method by reference, you must use the ref keyword. 43

44 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

45 45

46 46

47 47

48 48

49 49

50 50

51 51

52 52

53 53

54 54

55 55

56 56

57 57

58 58

59 59

60 60

61 61

62 62 rowrow column

63 63

64 64

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

66 int[][] 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

67 67

68 68

69 69

70 70

71 71

72 72

73 73

74 74

75 75

76 76

77 77

78 78

79 79

80 80

81 81

82 82

83 83

84 84

85 85

86 86

87 87


Download ppt "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."

Similar presentations


Ads by Google