1. collections are data structures that holds data in different ways for flexible operations c#...
TRANSCRIPT
Chapter 8Arrays
1
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
8.2 Arrays Arrays hold a fixed number of elements, all of the same type.
Initializ
ed to 0
3
8.2 Arrays
Zero-
based
4
8.3 Declaring and Creating Arrays
int[] c; // declare the array variablec = new int[ 12 ]; // create the array; assign to array variable
5
Array Initializing
6
Bounds Checking
public class ArraysBasics
{
public static void Main(string[] args)
{
int[] manyValues = {100, 101, 103, 200};
manyValues[5] = 100;
}
}
7
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
8.4 Examples Using Arrays
9
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
11
12
Named
Constant
13
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
16
// 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
19
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
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.
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
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
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
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
26
27
8.5 Case Study: Card Shuffling and Dealing Simulation
28
29
30
31
32
33
8.6 foreach Statement
34
35
Arrays are Objects
36
using System;
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
8.7 Passing Arrays and Array Elements to Methods
38
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
40
41
8.8 Passing Arrays by Value and by Reference
42
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
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
45
46
47
48
49
50
51
8.9 Case Study: Class GradeBook Using an Array to Store Grades
52
53
54
55
56
57
58
59
60
61
Multidimensional Arrays
62
ro
wcolumn
Multidimensional Arrays Initialization(ex.: 3x3)
63
8.10 Multidimensional Arrays
64
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.
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
67
68
69
70
8.11 Case Study: Class GradeBook Using a Rectangular Array
71
72
73
74
75
76
77
78
79
80
81
8.12 Variable-Length Argument Lists
82
83
84
8.13 Using Command-Line Arguments
85
86
87