1 / 87

Chapter 8 Arrays

Chapter 8 Arrays. 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. 8.2 Arrays.

tuwa
Télécharger la présentation

Chapter 8 Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8Arrays

  2. Collections • Collections are data structures that holds data in different ways for flexible operations . • C# Collection classes are defined as part of the • System.Collectionsor • System.Collections.Genericnamespace.

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

  4. 8.2 Arrays Zero-based

  5. 8.3 Declaring and Creating Arrays int[] c; // declare the array variable c = new int[ 12 ]; // create the array; assign to array variable

  6. Array Initializing

  7. Bounds Checking classArraysBasics { staticvoid Main(string[] args) { int[] manyValues = {100, 101, 103, 200}; manyValues[5] = 100; } }

  8. 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. • Remainder: array elements are all the same type

  9. 8.4 Examples Using Arrays

  10. Format Strings in Console.WriteLinemethod 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·······]

  11. Named Constant

  12. Named Constants constint SIZE= 100; int[]intList = newint[SIZE]; String[] strList=newString[SIZE]; … for (index = 0; index< SIZE;index++) { … } for (index = 0; index< SIZE;index++) { … } int[] intList = newint[100]; String[] strList=new String[100]; … for (index = 0;index<100; index++) { … } for (index = 0; index<100;index++) { … }

  13. // Fig. 8.6: BarChart.cs // Bar chart displaying application. using System; publicclassBarChart { publicstaticvoid 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 } // end Main }

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

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

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

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

  18. trycatch block ThetryStatement 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.

  19. 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 IndexOutOfRangeExceptionto 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.

  20. 8.5 Case Study: Card Shuffling and Dealing Simulation

  21. 8.6 foreach Statement

  22. Arrays are Objects using System;

  23. Ex: Arrays are Objects using System; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; namespace Arrays { classProgram { staticvoid 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(); } } }

  24. 8.7 Passing Arrays and Array Elements to Methods

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

  26. 8.8 Passing Arrays by Value and by Reference

  27. 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 refkeyword.

  28. Passing Reference-type by Reference! cont 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.

More Related