240 likes | 429 Views
Arrays. Part 9 dbg. Arrays. An array is a fixed number of 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 a fixed number of 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
Declaring and Initializing 1-Dimensional Arrays in C# vs. C++ and Java C++: int scores[SIZE]; //just declare name and set aside //memory for SIZE elements int scores[SIZE] = {num1 … numn};//initialize int scores[ ] = {num1…numn}; //initialize Java and C#: int[ ]scores;//just declare; memory is not set aside yet 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:
Extract an Element Value from an Array • Given an array, temps, of type integer, store the third element value in a variable:
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 the array element value extracted in each iteration of the loop. • Syntax: foreach(data-typesomeVariableinarrayName) Foreach
foreach Example int sum = 0; int[ ] grades = new int [10] {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. • A string has a Length property which holds the number of characters in a string. • A string may be converted to an array of type char using the ToCharArray() method of the string type. • An array has a GetUpperBound() method which returns the highest index in an array. 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.
Declaring and Initializing 2-Dimensional Arrays in C++ and Java C++: int scores[ROWS][COLS]; //just declare name and set // aside memory int scores[SIZE] [COLS] = {num1 … numn};//initialize with values int scores[ ] [COLS] = {num1…numn}; //initialize w values Java: int[ ][ ]scores;//just declare name; memory not set aside yet int[ ][ ] scores = new int[ROWS][COLS]; // sets aside memory for array elements int[ ][ ] scores = {{row0col0, … row0coln}, {row1col0, … row1coln}, {row2col0, … row2coln}}; //initialize w values
Declare and Initialize a Two-dimensional Array in C# decimal [ , ] postalRates;//declares name only decimal [ , ] = new decimal [2,6];//initializes array with //default value for datatype decimal[,] postalRates = new decimal[2,6] {{4.50, 5.00, 5.50, 6.50, 7.50, 9.00}, {9.99, 11.25, 11.99, 14.99, 16.99, 20.00}};//initialize w values
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). • Make up the exam grades.
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) but does happen in Java as well.
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