arrays part 9 dbg. arrays an array is a fixed number of contiguous memory locations, all containing...
TRANSCRIPT
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 JavaC++: 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-type someVariable in arrayName)
Foreach
11
foreach Example
int sum = 0;
int[ ] grades = new int [10] {81, 69, 93, 100, 90, 82, 70, 94, 88, 95};
foreach(int grade in grades)
{
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 JavaC++:
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
Zone 1 [0]
Zone 2 [1]
Zone 3 [2]
Zone 4 [3]
Zone 5 [4]
Zone 6 [5]
Regular [0] 4.50 5.00 5.50 6.50 7.50 9.00
Priority [1]9.99 11.25 11.99 14.99 16.99 20.00
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.
18
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
first middle last age sex
Person[0] Dee B Gudmundsen 29 F
Person[1] Michael Kuhrt 49 M
Person[2] John P Avitabile 39 M
Load EventUse with Form
Event “Fires” Immediately before the form displays for the first time.
Example You want to set some values (perhaps a timestamp) via code before the form appears. You might want to fill a ListBox with items, or fill an array with values via code before the form displays.
private void frmOrder_Load(object sender, System.EventArgs e)
{
// store current time in a variable
DateTime currentTime = DateTime.Now;
//display current time as hh:mm:ss AM/PM
lblTransactionDate.Text = currentTime.ToString(“T”);
}