220 likes | 344 Views
Arrays. Part 9 dbg. Arrays. An array is several contiguous memory locations, all containing data of the same type, identified by one variable name. Refer to a particular location by specifying the name of the array and the index (position number) of the location.
E N D
Arrays Part 9 dbg
Arrays • An array is several contiguous memory locations, all containing data of the same type, identified by one variable name. • Refer to a particular location by specifying the name of the array and the index (position number) of the location. • Index positions of arrays start at 0. • Values stored at the positions are called items or elements.
Declare and Allocate an Array in C# • Declare the array: //assigns name int[ ] scores; • Allocate memory for the array: scores = new int[10]; //room for 10 integers • Declare and allocate in one step: int[ ] scores = new int[10]; //all in 1 step; assigns //default value for data type to all elements
Initialize an Array • Space for an array can be automatically allocated by initializing the array with a set of values • string[ ] weekDays = new string [ ] {″Monday″, ″Tuesday″, ″Wednesday″, ″Thursday″, ″Friday″}; - or - • string[ ] weekDays = {″Monday″, ″Tuesday″, ″Wednesday″, ″Thursday″, ″Friday″}; • Note that this initialization creates an array just big enough to contain the set of assigned values
Arrays in C# and C++ • Be sure to note the difference in syntax between C# and C++ when declaring and initializing arrays: • C++: int scores[SIZE]; //just declare with no values int scores[SIZE] = {num1 … numn};//initialize int scores[ ] = {num1…numn}; //initialize • C#: int[ ] scores = new int[SIZE]; //declare and // initialize with default values for datatype int[ ] scores = new int[] {num1…numn};//declare and initialize int[ ] scores = {num1…numn};//declare and //initialize
Let’s Try Some Exercises • Declare an array named homeruns that will hold the number of homeruns scored by a particular team in each of the 162 games of the season. • Declare an array named prices that will store the following product prices: 12.99, 25.00, 3.75, 8.23, 0.97, 59.98
Assign a Value to an Array Element • Given an array, temps, of type integer, assign a value to first element of array: temps[0] = 33;
Extract an Element Value from an Array • Given an array, temps, of type integer, store the third element value in a variable: int firstTemp = temps[2];
Filling/Printing Array Values • Arrays are handy containers for data generated by a loop. • In this example, values are generated by a loop and stored in an array. • The values are then printed to the output window as they are extracted from the array using a second loop. DataToArray
foreach loop • A foreach loop is similar to a for loop, but you do not have to worry about the index variable; the foreach loop will automatically iterate though all elements of the array. • You will need some variable to store array element value extracted in each iteration of the loop. • Syntax: foreach(data-typesomeVariableinarrayName) Foreach
foreach Example int sum = 0; int[ ] grades = new int [] {81, 69, 93, 100, 90, 82, 70, 94, 88, 95}; foreach(int gradeingrades) { sum = sum + grade; //adds array element // value to sum variable }
Strings and Arrays of Type Char • A string is a data type designed to contain text. • It is not possible to directly gain access to single characters in a string. • A string may be converted to an array of type char using the ToCharArray() method of the string type. • This allows iterating through all characters. StringToChars
Multiple Dimension Arrays • An array with one dimension is a list. • An array with two dimensions is a table. • Adding a second dimension means that each position in the first dimension now behaves like a row in a table that has several columns. • The sizes of the dimensions of an array are separated by commas in the declaration/allocation bracket.
Declare and Initialize a Two-dimensional Array • decimal[,] postalRates = new decimal[,] {{4.50, 5.00, 5.50, 6.50, 7.50, 9.00}, {9.99, 11.25, 11.99, 14.99, 16.99, 20.00}}; • This array could store postal rates for 6 different zones. • Regular rates could be stored in the first row and priority rates could be stored in the second row.
Let’s Try Some Exercises • We want an array named grades that will store 3 exam grades (in columns) for each of 5 students (in rows). • Suppose the data is:
Array Bounds • You can determine the UpperBound of an array with the array’s GetUpperBound()method, which returns index of the last element in the array. • Call GetUpperBound() with a 0 parameter for 1st dimension of array; with a 1 for upper bound of 2nd-dimension of a multi-dimensioned array. • There is a Length property for a one-dim array and there is a GetLength()method with a 0 parameter will return the number of elements for 1st dimension of array; with a 1 for upper bound of 2nd-dimension of a multi-dimensioned array.
Arrays • C# will throw an Exception, if you attempt to use an index that is “out of range” for an array. This did not happen in C++. (The programmer had to be careful.)
Compound Data Types Structs
New Data Types • So far we have used only the primitive data types such as int, string, bool, and double. • C# also provides for the definition of structs, or compound data types. • We can think of a struct as being a package of variables of different data types.
Structs • The different variables within the definition of a struct are analogous to the fields of a database record. • We might define a struct called person that could store several attributes to define a human. • Use the public keyword to declare fields. StructData
An Array of Structs • We can construct a simple table of data by creating an array where each element is a struct. • Declare an array of structs: Person[ ] faculty = new Person[10]; StructArray