Arrays Array Class Array List Chapter Objectives Learn

Arrays, Array Class, Array List

Chapter Objectives Learn array basics Declare arrays and perform compile-time initialization of array elements Access elements of an array Become familiar with methods of the Array class

Chapter Objectives (continued) Write methods that use arrays as parameters Write classes that include arrays as members and instantiate user-defined array objects Create two-dimensional arrays including rectangular and jagged types Use multidimensional arrays

Chapter Objectives (continued) Use the Array. List class to create dynamic lists Learn about the predefined methods of the string class Work through a programming example that illustrates the chapter’s concepts

Array Basics Data structure that may contain any number of variables Variables must be of same type Single identifier given to entire structure Individual variables are called elements Elements accessed through an index Index also called subscript Elements are sometimes referred to as indexed or subscripted variables

Array Basics (continued) Arrays are objects of System. Array class includes methods and properties Methods for creating, manipulating, searching, and sorting arrays Create an array in the same way you instantiate an object of a user-defined class Use the new operator Specify number of individual elements
![Array Declaration Format for creating an array type [ ] identifier = new type Array Declaration Format for creating an array type [ ] identifier = new type](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-7.jpg)
Array Declaration Format for creating an array type [ ] identifier = new type [integral value]; Type can be any predefined types like int or string, or a class that you create in C# Integral value is the number of elements Length or size of the array Can be a constant literal, a variable, or an expression that produces an integral value

Array Declaration (continued) Creation of an array
![Array Declaration (continued) Array identifier, name, references first element Contains address where score[0] is Array Declaration (continued) Array identifier, name, references first element Contains address where score[0] is](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-9.jpg)
Array Declaration (continued) Array identifier, name, references first element Contains address where score[0] is located First index for all arrays is 0 Last element of all arrays is always referenced by an index with a value of the length of the array minus one Can declare an array without instantiating it The general form of the declaration is: type [ ] identifier;

Array Declaration (continued) Declaration of an array

Array Declaration (continued) If you declare array with no values to reference, 2 nd step required – dimension the array General form of the second step is: identifier = new type [integral value]; Examples const int size = 15; string [ ] last. Name = new string [25]; double [ ] cost = new double [1000]; double [ ] temperature = new double [size]; int [ ] score; score = new int [size + 15]; Two steps
![Array Initializers Compile-time initialization General form of initialization follows: type[ ] identifier = new Array Initializers Compile-time initialization General form of initialization follows: type[ ] identifier = new](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-12.jpg)
Array Initializers Compile-time initialization General form of initialization follows: type[ ] identifier = new type[ ] {value 1, value 2, …value. N}; Values are separated by commas Values must be assignment compatible to the element type Implicit conversion from int to double Declare and initialize elements in one step

Array Initializers (continued) Array length determined by number of initialization values placed inside curly braces Examples int [] an. Array = {100, 200, 400, 600}; char [ ] grade = new char[ ] { ‘A’, ‘B’, ‘C’, ‘D’, ‘F’}; double [ ] depth = new double [2] {2. 5, 3}; No length specifier is required

Array Initializers (continued) Methods of creating and initializing arrays at compile time

Array Access Specify which element to access by suffixing the identifier with an index enclosed in square brackets score[0] = 100; Length – special properties of Array class Last valid index is always the length of the array minus one

Array Access (continued) Index out of range exception Try to access the array using an index value larger than the array length minus one, a nonintegral index value, or a negative index value – Run-time error

Example : Create and Use an Array for (int i = 0; i < score. Length; i++) class Average. Diff { { total += score[i]; static void Main( ) } { avg = total / score. Length; int total = 0; Console. Write. Line("Average: {0}", avg); double avg, distance; Console. Write. Line("Scoret. Dist. from Avg. "); string in. Value; for (int i = 0; i < score. Length; i++) int [ ] score = new int[10]; { for (int i = 0; i < score. Length; i++) distance = Math. Abs((avg - score[i])); { Console. Write("Enter Score{0}: ", i + 1); Console. Write. Line("{0}tt{1}", score[i], distance); in. Value = Console. Read. Line( ); score[i] = Convert. To. Int 32(in. Value); } } //end of main } } //end of class

Example : Create and Use an Array (continued) Output from Average. Diff example

Using foreach with Arrays Used to iterate through an array Read-only access General format foreach (type identifier in expression) statement; Identifier is the iteration variable Expression is the array Type should match the array type
![Using foreach with Arrays (continued) string [ ] color = {"red", "green", "blue"}; foreach Using foreach with Arrays (continued) string [ ] color = {"red", "green", "blue"}; foreach](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-20.jpg)
Using foreach with Arrays (continued) string [ ] color = {"red", "green", "blue"}; foreach (string val in color) Console. Write. Line (val); Iteration variable, val represents a different array element with each loop iteration No need to increment a counter (for an index) D blu on s

Array Class Base array class All languages that target Common Language Runtime More power is available with minimal programming



Arrays as Method Parameters Can send arrays as arguments to methods Heading for method that includes array as a parameter modifiers return. Type identifier (type [ ] array. Identifier. . . ) Open and closed square brackets are required Length or size of the array is not included Example void Display. Array. Contents (double [ ] an. Array)

Pass by Reference Arrays are reference variables No copy is made of the contents Array identifier memory location does not contain a value, but rather an address for the first element Actual call to the method sends the address Call does not include the array size Call does not include the square brackets Example Display. Array. Contents (water. Depth);

Example : Using Arrays as Method Arguments class Static. Methods { static void Main( ) public static void Display. Output(double [ ] { double [ ] water. Depth={45, 16. 8, 190, 0. 8}; an. Array, string msg) { double [ ] w = new Double [20]; foreach(double w. Val in an. Array) Display. Output(water. Depth, "water. Depth Arraynn" ); if (w. Val > 0) Array. Copy(water. Depth, 2, w, 0, 4); Console. Write. Line(w. Val. To. String()); Array. Sort (w); } Display. Output(w, "Array w Sortednn" ); } Array. Reverse(w); Display. Output(w, "Array w Reversedn"); }

Output

Two-Dimensional Arrays Two-dimensional and other multidimensional arrays follow same guidelines as one-dimensional Two kinds of two-dimensional arrays Rectangular Visualized as a table divided into rows and columns Jagged or ragged

Two-Dimensional Representation Two-dimensional structure
![Two-Dimensional Arrays (continued) Declaration format type [ , ] identifier = new type [integral Two-Dimensional Arrays (continued) Declaration format type [ , ] identifier = new type [integral](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-30.jpg)
Two-Dimensional Arrays (continued) Declaration format type [ , ] identifier = new type [integral value, integral value]; Two integral values are required for a two-dimensional array Number of rows listed first Data values placed in array must be of the same base type Example (create a 7 x 3 matrix) int [ , ] calories = new int[7, 3];
![Two-Dimensional Arrays (continued) calories references address of calories[0, 0 ] Two-dimensional calories array Two-Dimensional Arrays (continued) calories references address of calories[0, 0 ] Two-dimensional calories array](http://slidetodoc.com/presentation_image_h2/e91ddf84460ad7c579d1d81e4cb5ec7e/image-31.jpg)
Two-Dimensional Arrays (continued) calories references address of calories[0, 0 ] Two-dimensional calories array

Two-Dimensional Arrays (continued) Length property gets total number of elements in all dimensions Console. Write. Line(calories. Length); // Returns 21 Get. Length( ) – returns the number of rows or columns Get. Length(0) returns number of rows Get. Length(1) returns number of columns Console. Write. Line(calories. Get. Length(1)); //Display 3 (columns) Console. Write. Line(calories. Get. Length(0)); //Display 7 (rows) Console. Write. Line(calories. Rank); // returns 2 (dimensions)

Jagged Arrays Rectangular arrays always have a rectangular shape, like a table; jagged arrays do not Also called ‘arrays of arrays’ Example int[ ] an. Array = new int[4] [ ]; an. Array [0] = new int[ ] {100, 200}; an. Array [1] = new int[ ] {11, 22, 37}; an. Array [2] = new int[ ] {16, 72, 83, 99, 106}; an. Array [3] = new int[ ] {1, 2, 3, 4};

Multidimensional Arrays Limited only by your imagination as far as the number of dimensions Format for creating three-dimensional array type [ , , ] identifier = new type [integral value, integral value]; Example (rectangular) int [ , , ] calories = new int [4 , 7 , 3]; (4 week; 7 days; 3 meals) Allocates storage for 84 elements

Multidimensional Arrays (continued) Figure Three-dimensional array Upper bounds on the indexes are 3, 6, 2

Array. List Class Limitations of traditional array Cannot change the size or length of an array after it is created Array. List class facilitates creating list like structure, BUT it can dynamically increase or decrease in length Similar to vector class found in other languages Includes large number of predefined methods

Array. List Class (continued)

Array. List Class (continued)

Chapter Summary Array declaration Compile-time initialization Accessing elements Array and Array. List class methods Arrays as parameters to methods Multidimensional arrays
- Slides: 39