360 likes | 370 Views
Arrays. Ch 8. Array. A group of variables (elements) of the same type Reference type!. Declaring & Creating an Array. Declaring an array reference double[] hours; Instantiating array object using new hours = new double[5];. Initializing an Array.
E N D
Arrays Ch 8
Array • A group of variables (elements) of the same type • Reference type!
Declaring & Creating an Array • Declaring an array reference double[] hours; • Instantiating array object using new hours = new double[5];
Initializing an Array • Declaring, instantiating, and initializing double[] hours; hours = new double[5] {10.5, 21.5, 45, 37, 40}; • Simplified syntax double[] hours = {10.5, 21.5, 45, 37, 40};
Memory Allocation ?[4] 40 ?[3] 37 ?[2] 45 ?[1] 21.5 ?[0] 10.5 hours
Elements of an Array • Indexed starting at 0, not 1! • The Length property tells the number of elements for(int i=0; i<hours.Length; i++) total += hours[i];
foreach Loop • Loops through the elements of an array or collection • Simpler than for loop foreach(double h in hours) total += h;
Implicitly Typed Variable • Indicated by keyword var, rather than a particular type • The compiler infers the type of the variable. • Example for (var counter=0; counter<array.Length; counter++) • The compiler infers the type of counter is int, because it’s initialized with an int value.
Passing Arrays or Array Elements to Methods • Array is a reference type! • Type of array elements may be a value type or reference type • double[] hours; • GradeBook[] gradeBooks;
Passing Arguments • Value type, pass-by-value • Caller's variable CANNOT be changed • Value type, pass-by-reference • Caller's variable CAN be changed • Reference type, pass-by-value • Caller's object content CAN be changed • Caller's reference CANNOT • Reference type, pass-by-reference • Both caller's object and reference CAN be changed
Passing Arrays by Value and by Reference • Passing by value • Caller's array elements CAN be changed • Caller's array reference CANNOT • Passing by reference • Both caller's array reference and elements CAN be changed
Multidimensional Arrays • Two-dimensional • Rectangular array • Jagged array • High dimensional arrays are rare
Rectangular Array • Has m rows and n columns int[,] a = new int[3, 4];
Jagged Array • An array of arrays • A one-dimensional array • Each element refers to a 1D array • Rows of different lengths
Jagged Array Example int[][] jagged = {new int[] {1, 2}, new int[] {3}, new int[] {4, 5, 6 } };
Summary • Array • Group of elements of the same type • Passing array or array element to method • By value • By reference • Multidimensional array • Rectangular or Jagged