Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
Visual C# - Penn P. Wu, PhD. 163
Lecture #6 C# Arrays, ArrayList, and Lists
Introduction Storing groups of related objects is a basic requirement of most software applications. The two
primary ways of doing this are with arrays and collections. The term “collection” refers to a
logical container that hosts a list of objects. According to the definition, “arrays” are
collections of objects of the same type. List and ArrayList are two collection classes. In terms
programming, a “collection class” is an object-oriented paradigm (OOP) replacement for the traditional array data structure. Much like an array, a collection contains member elements,
although these tend to be objects rather than simpler types such as strings and integers.
C# arrays An array in C# is actually an ordered list that stores multiple values. All items in the list have
at least one thing in common that sets the sequence of values of the item. For example, there
are four seasons in a year. Winter must come before spring, spring must come before summer,
and so on. That’s being said, “Season” is the name of array, which contains four elements in
sequence: spring, summer, fall, and winter.
In C#, the format to declare an array is:
DataType[] ArrayName;
After the declaration, use the new keyword to create the array with a fixed number of element
(known as size or length of the array). The size is enclosed by brackets. Once defined, the size
cannot change its value.
ArrayName = new DatayType[size];
It is very common to declare and creates an array in one single statement.
DataType[] ArrayName = new DatayType[size];
The following example declares and create an array of five integers:
int[] x = new int[5];
An array that stores 6 string elements can be declared in the same way. For example:
string[] city = new string[6];
Each element of an array is represented in the format of: arrayName[index], where index is a
positive integer in the range from 0 to size-1 with 0 being the first and size-1 being the last. By
the way, some books refer the term “index” as “key”. These indexes also specify the sequence.
Since array is an indexed list of data, the first piece of data stored in an array is assigned an
index position of 0. The next piece of data is assigned an index position of 1, and so on.
Programmers can reference any data stored in the array based on its index position. Value of
every element may be assigned with the assignment operator (=) in the form of:
arrayName[index] = value;
The following x array contains five elements from x[0] to x[4]. Their values are 6, 9, 4, 5, and
7 respectively. In other words, x is an int array with a size (or length) of 5.
using System;
using System.Windows.Forms;
Visual C# - Penn P. Wu, PhD. 164
public class MyCollect
{
public static void Main()
{
int[] x = new int[5];
x[0] = 6;
x[1] = 9;
x[2] = 4;
x[3] = 5;
x[4] = 7;
}
}
The following is the sample code that creates a string array to handle the four seasons.
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
string[] seasons = new string[4];
seasons[0]="Winter";
seasons[1]="Spring";
seasons[2]="Summer";
seasons[3]="Fall";
}
}
In the seasons array, Winter, Spring, Summer, and Fall are the elements of the seasons array.
Each element is given an index (also known as a key), starting with 0, which indicates its
sequence in the array. Therefore, Winter is the first season and Fall is the fourth season.
There is a short-hand way for declaring and creating arrays as shown below which simply
declares the type and name of the array. All the elements are defined within curly brackets.
The number of elements enclosed by the curly brackets is the size of the array. The order of elements constitutes the indexes.
string[] majors = new String[] { "CIS","ECT","HIT","NCM" };
or, further simplify to:
string[] majors = { "CIS","ECT","HIT","NCM" };
The following is another example.
double[] price = new double[] {3.75, 2.99, 4.87, 6.52};
or,
double[] price = {3.75, 2.99, 4.87, 6.52};
The seasons array can be declared and created using:
string[] seasons = new string[] {"Winter", "Spring", "Summer",
"Fall"};
or, string[] seasons = {"Winter", "Spring", "Summer", "Fall"};
Visual C# - Penn P. Wu, PhD. 165
The following is a declaration of a string array where each array element is initialized by a
name of a weekday:
using System;
using System.Windows.Forms;
public class myArr
{
public static void Main()
{
string[] weekDays = new string[] { "Sun", "Mon", "Tue",
"Wed", "Thu", "Fri", "Sat" };
MessageBox.Show(weekDays[3]);
}
}
C# uses the following format to retrieve value of a specified element in an array:
ArrayName[index]
The following retrieves the value of the third element of the seasons array.
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
string[] seasons = new string[4];
seasons[0]="Winter";
seasons[1]="Spring";
seasons[2]="Summer";
seasons[3]="Fall";
MessageBox.Show(seasons[2]);
}
}
The output loos:
In the following example, the value of x[2] is 4, and x[4] is 7; therefore, the output is 11
because 4 +7 = 11.
using System;
using System.Windows.Forms;
public class lab4_0
{
public static void Main()
{
int[] x = {6, 9, 4, 5, 7};
Visual C# - Penn P. Wu, PhD. 166
MessageBox.Show((x[2] + x[4]) + "");
}
}
In the following example, majors[3] is initially given “NCM” as values. Yet, the majors[3]=
"BIZ"; statement assigns a new value to it.
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
String str="";
string[] majors = { "CIS","ECT","HIT","NCM" };
str = "majors[3] is " + majors[3] +"\n";
majors[3]="BIZ";
str += "majors[3] becomes " + majors[3] +"\n";
MessageBox.Show(str);
}
}
The output should be:
The following uses a for loop to retrieve values from all the elements of an array. It also uses
the arrayName[index] format to identify elements. The Length property of the Array class
of the .NET Framework represents the total number of elements in the array. In other words,
the Length property stores the size of a C# array.
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
String str="";
string[] majors = { "CIS","ECT","HIT","NCM" };
for (int i=0; i<majors.Length; i++)
{
str += majors[i] + "\n";
}
MessageBox.Show(str);
}
}
Visual C# - Penn P. Wu, PhD. 167
The following uses a while loop to produce the same result as the above.
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
String str="";
string[] majors = { "CIS","ECT","HIT","NCM" };
int i=0;
while(i<majors.Length)
{
str += majors[i] + "\n";
i++;
}
MessageBox.Show(str);
}
}
C# also provides the foreach statement to iterate through the elements of an array. The syntax
is:
foreach (dataType variableName in arrayName)
where variableName is the name of a variable that will be used to represent each element of the array during the iteration. The following code creates an array named x and iterates
through it with the foreach statement:
using System;
using System.Windows.Forms;
public class MyCollect
{
public static void Main()
{
String str="";
int[] x = { 3, 8, 5, 1, 7, 6, -2, -1, 9 };
foreach (int i in x)
{
str += i + "\n";
}
MessageBox.Show(str);
}
}
Multi-
dimensional
array
All the above examples are single-dimensional arrays, which means that each element has only
one index in the format of arrayName[index]. C# arrays can have more than one dimension,
which means every element is identified by two or more indexes. In the case of two-
dimensional array, the format is: arrayName[r, c], where r indicate row while c indicates
column. As shown in the following table, the value of an element of a two-dimensional array
is referenced by two indexes: r and c. If the name of array is “fruit”, then the value of fruit[2,
0] is “banana”. By the way, the number of dimensions of an array is known as “rank”.
Visual C# - Penn P. Wu, PhD. 168
r\c 0 1
0 orange grape
1 cranberry apple
2 banana tangerine
3 mango watermelon
C# use the following syntax to declare and initialize a two-dimensional array, where r and c
are the total number of rows and columns respectively.
dataType[, ] arrayName = new dataType[r, c];
The following creates a two-dimensional array of four rows and two columns:
int[,] arr2D = new int[4, 2];
In the above statement, 4 indicates that there will be 4 rows which means the size of first dimension is 4. 2 indicates that there will be 2 columns. The following creates a 4-by-2
(meaning 4 rows, 2 columns) array with values assigned to every element.
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
int[,] arr2D = new int[4,2];
arr2D[0,0] = 1; // row 1
arr2D[0,1] = 2;
arr2D[1,0] = 3; // row 2
arr2D[1,1] = 4;
arr2D[2,0] = 5; // row 3
arr2D[2,1] = 6;
arr2D[3,0] = 7; // row 4
arr2D[3,1] = 8;
}
}
r\c 0 1
0 1 2
1 3 4
2 5 6
3 7 8
The following is the sample code of the “fruit” array.
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
string[,] fruit = new string[4,2];
fruit[0,0] = "orange"; // row 1
fruit[0,1] = "grape";
fruit[1,0] = "cranberry"; // row 2
fruit[1,1] = "apple";
fruit[2,0] = "banana"; // row 3
Visual C# - Penn P. Wu, PhD. 169
fruit[2,1] = "tangerine";
fruit[3,0] = "mango"; // row 4
fruit[3,1] = "watermelon";
}
}
The following is another example of 2×3 array of double type named “x”.
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
double[,] x = new double[2,3];
x[0,0] = 3.75; // row 1
x[0,1] = 2.65;
x[0,2] = 4.35;
x[1,0] = 9.95; // row 2
x[1,1] = 1.85;
x[1,2] = 7.05;
MessageBox.Show(x[1, 0]+""); //9.95
}
}
r\c 0 1 2
0 3.75 2.65 4.35
1 9.95 1.85 7.05
The following illustrates the short-hand way to create two-dimension array.
using System;
class myArray
{
static void Main()
{
int[,] arr2D = new int[,] { {1, 2}, {3, 4},
{5, 6}, {7, 8} };
}
}
or,
using System;
class myArray
{
static void Main()
{
int[,] arr2D = { {1, 2}, {3, 4},
{5, 6}, {7, 8} };
}
}
To retrieve the value of a given element, programmers need to clearly indicate the indexes of
row (r) and column (c). The order of indexes is r-first-c-second.
ArrayName[r, c];
Visual C# - Penn P. Wu, PhD. 170
In the following example, the “arr2D” array contains two elements: {'A', 'B', 'C', 'D'}, and {'E',
'F', 'G', 'H'}. Each of the two elements is an individual array of Char type.
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
r/c 0 1 2 3
0 A B C D
1 E F G H
Char[,] arr2D = new Char[,] { {'A', 'B', 'C', 'D'},
{'E', 'F', 'G', 'H'} };
String str = arr2D[0,0] + "\n"; // A
str += arr2D[0,1] + "\n"; // B
str += arr2D[0,2] + "\n"; // C
str += arr2D[0,3] + "\n"; // D
str += arr2D[1,0] + "\n"; // E
str += arr2D[1,1] + "\n"; // F
str += arr2D[1,2] + "\n"; // G
str += arr2D[1,3] + "\n"; // H
MessageBox.Show(str);
}
}
The output looks:
The following creates a two-dimensional array of string type. The identifier is “names”.
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
r/c 0 1
0 "Helen" "Chen"
1 "Peter" "Garcia"
string[,] names = new string[2, 2];
names[0,0] = "Helen";
names[0,1] = "Chen";
names[1,0] = "Peter";
names[1,1] = "Garcia";
String str = "First\tLast\n";
str += names[0,0] + "\t" + names[0,1] + "\n";
str += names[1,0] + "\t" + names[1,1] + "\n";
Visual C# - Penn P. Wu, PhD. 171
MessageBox.Show(str);
}
}
The following is a sample output.
The following demonstrates how to create the same array using the short-hand way.
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
string[,] names = new string[2, 2] {
{"Helen","Chen"},
{"Peter","Garcia"} };
String str = "First\tLast\n";
str += names[0,0] + "\t" + names[0,1] + "\n";
str += names[1,0] + "\t" + names[1,1] + "\n";
MessageBox.Show(str);
}
}
The following demonstrates how to use two nested for loops to retrieve every element of a 2D
array. The outer for loop iterates through the row while the inner iterates through columns.
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
string[,] names = new string[2, 2];
names[0,0] = "Helen";
names[0,1] = "Chen";
names[1,0] = "Peter";
names[1,1] = "Garcia";
String str = "Elements are:\n";
for (int r=0; r<2; r++)
{
for (int c=0; c<2; c++)
{
str += "names[" + r +"," + c + "] is " + names[r,c] + "\n";
}
Visual C# - Penn P. Wu, PhD. 172
}
str += "Dimension: " + names.Rank;
MessageBox.Show(str);
}
}
The output looks:
The foreach loop can also retrieve all the values. In C#, the foreach loop requires a delegate
such as s in the following example. The delegate represents the element being accessed during
the iteration. The delegate must be declared as the same data type as the array. The foreach
loop is simpler in structure, except it is difficult to display the indexes.
using System;
using System.Windows.Forms;
public class Example {
static void Main(string[] args) {
string[,] names = new string[2, 2];
names[0,0] = "Helen";
names[0,1] = "Chen";
names[1,0] = "Peter";
names[1,1] = "Garcia";
String str = "Elements are:\n";
foreach (string s in names)
{
str += s + "\n";
}
MessageBox.Show(str);
}
}
The Rank property returns the number of dimensions of an array. When an array has two
dimensions (such as rows and columns), the value of Rank is 2.
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
int[,] a = new int[5, 10];
MessageBox.Show("The array has " + a.Rank + " dimensions.");
}
}
Visual C# - Penn P. Wu, PhD. 173
The output is:
The array has 2 dimensions.
In this lecture, the instructor has been using “row” and “column” to depict the concept of two-
dimensional array. In the case of a three-dimensional array, the third dimensional is described
as the “layer”. The syntax to create a 3D array in C# is:
dataType[, ,] arrayName = new dataType[r, c, l];
The following figure illustrates the three dimensions with respect to a 3D space. It has 2 rows,
3 columns, and 4 layers. Every cube represents an element, and its value is placed inside the
cube.
The following declaration creates an array of three dimensions with indexes of 2, 3, and 4.
int[, ,] my3d = new int[2, 3, 4];
where,
• 2 indicates that there will 2 rows.
• 3 indicates that there will be 3 columns.
• 4 indicates that there will be 4 layers.
The complete code that creates this 3D array is:
using System;
class myArray
{
static void Main()
{
int[, ,] my3d = new int[2, 3, 4];
// row 1
my3d[0,0,0]=1; // column 1
my3d[0,0,1]=7;
my3d[0,0,2]=13;
my3d[0,0,3]=19;
my3d[0,1,0]=2; // column 2
my3d[0,1,1]=8;
my3d[0,1,2]=14;
my3d[0,1,3]=20;
my3d[0,2,0]=3; // column 3
my3d[0,2,1]=9;
my3d[0,2,2]=15;
my3d[0,2,3]=21;
22 23 24
19 20 21
16 17 18
13 14 15
10 11 12
7 8 9
4 5 6
1 2 3
Visual C# - Penn P. Wu, PhD. 174
// row2
my3d[1,0,0]=4; // column 1
my3d[1,0,1]=10;
my3d[1,0,2]=16;
my3d[1,0,3]=22;
my3d[1,1,0]=5; // column 2
my3d[1,1,1]=11;
my3d[1,1,2]=17;
my3d[1,1,3]=23;
my3d[1,2,0]=6; // column 3
my3d[1,2,1]=12;
my3d[1,2,2]=18;
my3d[1,2,3]=24;
}
}
The following shows the shorthand way to create this 3D array. The logic is: the array has 2
rows, each row has 3 columns, and each column has 3 layers. In other words, the first
dimension is an array consisting of two elements. Each element of the second dimension is
made of 3 elements. Each elements of the third dimension contains 4 integers.
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
int[, ,] my3d = new int[2, 3, 4] {
{ {1, 7, 13, 19}, {2, 8, 14, 20}, {3, 9, 15, 21} }, //row1
{ {4, 10, 16, 22}, {5, 11, 17, 23}, {6, 12, 18, 24} } //row2
};
String str = "Value of elements:\n";
for (int r=0; r<2; r++)
{
for (int c=0; c<3; c++)
{
for (int l=0; l<4; l++)
{
str += "my3d[" + r + "," + c + "," + l +"] is " +
my3d[r,c,l] + "\n";
}
}
}
str += "Size: " + my3d.Length + "\nRank: " + my3d.Rank;
MessageBox.Show(str);
}
}
The above code also demonstrates how to use nested for loops to retrieve every values of the
array. It also uses the Length and Rank properties to get the size and dimension.
Visual C# - Penn P. Wu, PhD. 175
Jagged array While a “multi-dimensional array” is a collection of equal-sized one-dimensional arrays, a
“jagged array” is an array whose elements are arrays of variable sizes. In other words, a
“jagged array” is an array of equal- or unequal-sized arrays. Some experts even refer a jagged
array as the “parent” array of a number of “child” arrays.
C# uses the following syntax to declare and initialize a jagged array, in which new is a
keyword and size is the number of the “parent” array. The size of “child” arrays are not
defined during the declaration because the elements of a jagged array can be of different sizes.
dataType[][] arrayName = new dataType[size][]
The following declares a jagged array named ja with 3 elements. It also specifies that each of
the three elements is a single-dimensional array of int type.
int[][] ja = new int[3][];
In the following code, there are three single-dimensional arrays of int type: x, y, and z. Their
sizes are 5, 4, and 2 respectively. Then, the code declares and initializes an array named “ja”
which uses three single-dimensional arrays as its elements.
using System;
using System.Windows.Forms;
class Example
{
static void Main()
{
int[] x = new int[5] {1, 2, 3, 4, 5};
int[] y = new int[4] {6, 7, 8, 9};
int[] z = new int[2] {0, 10};
int[][] ja = new int[3][] {x, y, z}; // array of arrays
}
}
The above code uses the short-hand way to create three single-dimensional arrays. It, then,
uses the short-hand way to create the jagged array. The following code, on the other hand,
demonstrates how to declare and initialize a jagged array before declaring and initializing its
elements.
using System;
class Example
{
static void Main()
{
int[][] ja = new int[3][];
ja[0] = new int[5]; // size of 5
ja[1] = new int[4]; // size of 4
ja[2] = new int[2]; // size of 2
}
}
Like any generic single-dimension array, every element of a jagged array is denoted in the
format of: arrayName[index]. The value of index starts at 0. The first element of “ja” is
“ja[0]”, the second “ja[1]”, and so on. In the following statement, the new keyword also
Visual C# - Penn P. Wu, PhD. 176
declares that “ja” has three elements and each element is a single-dimensional array of int
type.
int[][] ja = new int[3][];
The following illustrates how to create the first elements of “ja”, which is array of 5 integers.
ja[0] = new int[5];
Since every element of a jagged array can have a different size. The above sample code sets
the second to be an array of 4 integers and the third is an array of 2 integers.
Within a jagged array, programmers use the following format to identify every element of the “child” arrays, in which i is the index of “parent” array and j is the index of “child” array.
arrayName[i][j]
The following code illustrates how to identify every elements of each “child” array and assign
values to them.
using System;
class Example
{
static void Main()
{
int[][] ja = new int[3][];
ja[0] = new int[5]; //child 1
ja[0][0]=1; //element 1
ja[0][1]=3; //element 2
ja[0][2]=5;
ja[0][3]=7;
ja[0][4]=9;
ja[1] = new int[4]; //child 2
ja[1][0]=0; //element 1
ja[1][1]=2; //element 2
ja[1][2]=4;
ja[1][3]=6;
ja[2] = new int[2]; //child 3
ja[2][0]=11; //element 1
ja[2][1]=22; //element 2
}
}
r\c 0 1 2 3 4
0 1 3 5 7 9
1 0 2 4 6
2 11 22
The following demonstrates the short-hand way to create the above jagged array. All “child”
arrays are created using the short-hand way, too.
using System;
using System.Windows.Forms;
class Example
{
static void Main()
{
int[][] ja = new int[3][];
Visual C# - Penn P. Wu, PhD. 177
ja[0] = new int[5] { 1, 3, 5, 7, 9 };
ja[1] = new int[4] { 0, 2, 4, 6 };
ja[2] = new int[2] { 11, 22 };
}
}
By the way, in C#, the short-hand way to create a single-dimensional array allows the
programmer to skip the declaration of size.
using System;
using System.Windows.Forms;
class Example
{
static void Main()
{
int[][] ja = new int[3][];
ja[0] = new int[] { 1, 3, 5, 7, 9 };
ja[1] = new int[] { 0, 2, 4, 6 };
ja[2] = new int[] { 11, 22 };
MessageBox.Show(ja[1][2]+"");
}
}
Interestingly, C# programmer can even initialize the entire jagged array upon declaration of
the “parent” array as shown below.
using System;
using System.Windows.Forms;
class Example
{
static void Main()
{
int[][] ja = new int[][]
{
new int[] {1, 3, 5, 7, 9},
new int[] {0, 2, 4, 6},
new int[] {11, 22}
};
}
}
The following is most shorthand form.
using System;
using System.Windows.Forms;
class Example
{
static void Main()
{
int[][] ja = {
new int[] {1, 3, 5, 7, 9},
Visual C# - Penn P. Wu, PhD. 178
new int[] {0, 2, 4, 6},
new int[] {11, 22}
};
MessageBox.Show(ja[1][2]+"");
}
}
It is possible to mix jagged and multidimensional arrays. The following is a declaration and
initialization of a jagged array that contains two-dimensional array of different sizes as
elements.
int[][,] ja = new int[3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
r\c 0 1 2
0 {1,3} {5,7}
1 {0,2} {4,6} {8,10}
2 {11,22} {99,88} {0,9}
According to the above declaration, the element of “ja”, which is denoted as “ja[0]”, has two
element, {1, 3} and {5, 7}. Therefore, ja[0][0,0] is 1, ja[0][0,1] is 3, ja[0][1,0] is 5, ja[0][1,1]
is 7.
using System;
using System.Windows.Forms;
public class Example
{
public static void Main()
{
int[][,] ja = new int[3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
MessageBox.Show(ja[0][0,0] + "\n" +
ja[0][0,1] + "\n" +
ja[0][1,0] + "\n" +
ja[0][1,1] + "\n"
);
}
}
The method Length returns the number of arrays contained in the jagged array. The following
example will return a value of 3.
MessageBox.Show(ja.Length + "");
The following uses nested for loops to retrieve all values. It also uses the Length property to
dynamically get the size of “child” arrays because they vary. Again, ja[i] represents the “child”
arrays of “ja”; therefore, ja[i].Length returns the size of a given “child” array. The Rank
properties returns the dimension of “ja” which is 1.
using System;
using System.Windows.Forms;
public class Example
{
Visual C# - Penn P. Wu, PhD. 179
public static void Main()
{
int[][] ja =
{
new int[] {1, 3, 5, 7, 9},
new int[] {0, 2, 4, 6},
new int[] {11, 22}
};
string str = "Elements\n";
for (int i=0; i<ja.Length; i++)
{
for (int j=0; j<ja[i].Length; j++)
{
str += "ja[" + i + "][" + j + "]" + ja[i][j] + "\n";
}
}
str += "Length: " + ja.Length + "\nDimension: " + ja.Rank;
MessageBox.Show(str);
}
}
There is a benefit for using jagged arrays, as opposed to multidimensional arrays. A jagged
array is an array whose elements are arrays. The arrays that make up the elements can be of
different sizes, leading to less wasted space for some sets of data.
Copying Arrays
Arrays are defined as “reference” types because an array’s name is a variable that contains a
reference to an array instance. This means that when you assign an existing array’s name to
another new variable, you end up with two references to the same array instance; therefore,
you can make alias of an existing array. For example:
using System;
using System.Windows.Forms;
public class Example {
static void Main(string[] args) {
int[] a = { 9, 3, 7, 2 };
// hooks and a refer to the same array instance
int[] b = a;
String str;
str = "The a array: " + a[0] + " " + a[1] + " " + a[2] + " "
+ a[3] + "\n";
str += "The b array: " + b[0] + " " + b[1] + " " + b[2] + " "
+ b[3] + "\n";
MessageBox.Show(str);
}
}
The output looks:
Visual C# - Penn P. Wu, PhD. 180
In this example, b is the alias of a. if you modify the value of a[1], the change will also be
visible by reading b[1].
If you want to make a copy of the array instance (the data on the heap) that an array variable
refers to, you have to do two things. First, you need to create a new array instance of the same
type and the same length as the array you are copying, as in this example: using System;
using System.Windows.Forms;
public class Example {
static void Main(string[] args) {
int[] a = { 9, 3, 7, 2 };
int[] c = new int[4];
c[0] = a[0];
c[1] = a[1];
c[2] = a[2];
c[3] = a[3];
String str = "The c array: " + c[0] + " " + c[1] + " " + c[2]
+ " " + c[3];
MessageBox.Show(str);
}
}
The above method works, but if you later modify the code to change the length of the original
array, you must remember to also change the size of the copy. It’s better to determine the
length of an array by using its Length property, as shown in this example:
using System;
using System.Windows.Forms;
public class Example {
static void Main(string[] args) {
int[] a = { 9, 3, 7, 2 };
int[] c = new int[a.Length];
c[0] = a[0];
c[1] = a[1];
c[2] = a[2];
c[3] = a[3];
String str = "The c array: " + c[0] + " " + c[1] + " " + c[2]
+ " " + c[3];
MessageBox.Show(str);
}
}
The values inside copy are now all initialized to their default value of 0.
Visual C# - Penn P. Wu, PhD. 181
The second thing you need to do is set the values inside the new array to the same values as
the original array. You could do this by using a for statement (just an example in this lecture,
details is given in later lecture), as shown in this example:
using System;
using System.Windows.Forms;
class myArray {
static void Main() {
int[] a = { 9, 3, 7, 2 };
int[] c = new int[a.Length];
for (int i = 0; i != c.Length; i++) {
c[i] = a[i];
}
MessageBox.Show("The c array is: " +
c[0] + "," + c[1] + "," + c[2] + "," + c[3]);
}
}
Copying arrays is actually a fairly common requirement. So much so, that the System.Array
class provides some useful methods that you can use to copy an array rather than writing your
own code. For example, the CopyTo, method, which copies the contents of one array into
another array given a specified starting index:
using System;
using System.Windows.Forms;
class myArray {
static void Main() {
int[] a = { 9, 3, 7, 2 };
int[] c = new int[a.Length];
a.CopyTo(c, 0);
MessageBox.Show("The c array is: " +
c[0] + "," + c[1] + "," + c[2] + "," + c[3]);
}
}
Another way to copy the values is to use the System.Array static method called Copy. As with CopyTo, the target array must be initialized before the Copy call is made:
using System;
using System.Windows.Forms;
class myArray {
static void Main() {
int[] a = { 9, 3, 7, 2 };
int[] c = new int[a.Length];
Array.Copy(a, c, c.Length);
MessageBox.Show("The c array is: " +
c[0] + "," + c[1] + "," + c[2] + "," + c[3]);
}
}
Yet another alternative is to use the System.Array instance method called Clone, which can be
used to create an entire array and copy it in one action:
Visual C# - Penn P. Wu, PhD. 182
using System;
class myArray {
static void Main() {
int[] a = { 9, 3, 7, 2 };
int[] c = (int[])a.Clone();
Console.Write("The c array is: {0}, {1}, {2}, {3}",
c[0], c[1], c[2], c[3]);
}
}
Notice that the Clone method actually returns an object, which is why you must cast it to an
array of the appropriate type when you use it. Furthermore, all three methods create a shallow
copy of an array—if the array being copied contains reference types, the methods simply copy
the references, rather than the objects being referred to. After copying, both arrays refer to the
same set of objects.
The ArrayList
class
One of the annoying problems of array in C# as well as many programming language is that
array must have a fixed size. Once the size of an array is declared, it cannot change. The
ArrayList class is a subclass of the System.Collections which allows creating an array whose
size is dynamically increased as required. Microsoft uses the term capacity to describe the
dynamic size of an ArrayList which is the number of elements the ArrayList can hold. As
elements are added to an ArrayList, the capacity is automatically increased as required through
reallocation.
To create an ArrayList object, it is necessary to use the System.Collections namespace as
shown below.
using System.Collections;
The following is a complete code illustrating how to create an ArrayList object without
defining the size. While the Capacity property sets the number of elements that the ArrayList
can contain, the Count property actually returns the number of elements actually contained in
the ArrayList. Capacity is always greater than or equal to Count. If Count exceeds Capacity
while adding elements, the capacity is automatically increased by reallocating the internal
array before copying the old elements and adding the new elements. The capacity grows in 2n.
It starts with 4, advances to 8, 16, and so on.
using System;
using System.Windows.Forms;
using System.Collections;
public class myList
{
static void Main()
{
ArrayList course = new ArrayList();
course.Add("CIS211");
course.Add("CIS212");
course.Add("CIS213");
string str = "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
MessageBox.Show(str);
}
}
Visual C# - Penn P. Wu, PhD. 183
Elements in this collection can be accessed using an integer index. Indexes in this collection
are zero-based. For example,
using System;
using System.Windows.Forms;
using System.Collections;
public class myList
{
static void Main()
{
ArrayList course = new ArrayList();
course.Add("CIS211");
course.Add("CIS212");
course.Add("CIS213");
string str="";
for (int i=0; i < course.Count; i++)
{
str += course[i] + "\n";
}
MessageBox.Show(str);
}
}
The Add() method adds an object to the end of the ArrayList. The Clear() method removes all
elements from the ArrayList. The following uses a foreach loop to list all elements. It also
demonstrates how the Clear() method works.
using System;
using System.Windows.Forms;
using System.Collections;
public class myList
{
static void Main()
{
ArrayList course = new ArrayList();
course.Add("CIS211");
course.Add("CIS212");
course.Add("CIS213");
string str = "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
foreach(string c in course)
{
str += c + "\n";
}
MessageBox.Show(str);
course.Add("CIS214");
course.Add("CIS215");
str = "New list\n";
str += "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
foreach(string c in course)
Visual C# - Penn P. Wu, PhD. 184
{
str += c + "\n";
}
MessageBox.Show(str);
course.Clear();
course.TrimToSize();
str = "After clearance\n";
str += "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
MessageBox.Show(str);
}
}
The output looks:
and and
The ArrayList class creates and implements an array whose size is dynamically increased as
required. The following compare an ArrayList object with a traditional array. A traditional
array must have a fixed size while an ArrayList object can grow in size.
using System;
using System.Windows.Forms;
using System.Collections;
public class myArrayList
{
public static void Main()
{
ArrayList AL = new ArrayList(); // ArrayList
int[] arr = new int[10]; // traditional array
for (int i=0; i<10; i++)
{
AL.Add(i);
arr[i] = i;
}
}
}
The capacity can be decreased by calling TrimToSize or by setting the Capacity property
explicitly.
course.Capacity = 2;
By the way, using multidimensional arrays as elements in an ArrayList collection is not
supported.
Visual C# - Penn P. Wu, PhD. 185
Interestingly, the ArrayList collection accepts Null (meaning empty value) as a valid value,
allows duplicate elements; therefore, Microsoft warns that ArrayList may not always offer the
best performance for a given task. Microsoft recommends the List<T> class which will be
discussed later.
Lists<T> Lists are dynamic arrays in the C# language. They can grow as needed when you add
elements. They are considered generics and constructed types; therefore, it is more convenient
to add the following directive to the code.
using System.Collections.Generic;
The List represents a strongly typed list of objects that can be accessed by index. It provides methods to search, sort, and manipulate lists. The data type must be defined within a pair of <
and >. In the following example, “lst” is an instance of List<string> class in which string
specifies the acceptable data type.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList
{
public static void Main()
{
List<string> lst = new List<string>();
lst.Add("Chemistry");
lst.Add("Biology");
lst.Add("Physics");
lst.Add("Mathematics");
String str = "";
foreach (String s in lst)
{
str += s + "\n";
}
str += "Count : " + lst.Count + "\n";
str += "Capacity : " + lst.Capacity + "\n";
MessageBox.Show(str);
}
}
The Capacity property is the number of elements that the List can store before resizing is
required, while Count property is the number of elements that are actually in the List.
Capacity is always greater than or equal to Count. If Count exceeds Capacity while adding
elements, the capacity is increased by automatically reallocating the internal array before
copying the old elements and adding the new elements. The Add() method adds an object to
the end of the List.
In the following example, “list” is an instce of List<int> in which int specifies the
acceptable data type.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList
{
Visual C# - Penn P. Wu, PhD. 186
static void Main()
{
List<int> list = new List<int>();
list.Add(1);
list.Add(3);
list.Add(5);
list.Add(7);
String str="";
for (int i=0; i<list.Count; i++)
{
str += list[i] + "\n";
}
MessageBox.Show(str);
}
}
The above example shows how you can add a primitive type such as integer to a List
collection, but the List collection can receive reference types and object instances. This code
also include a for loop that demonstrates how you can display every elements in the list. By
the way, the foreach loop is another option. For example,
foreach (int i in list)
{
str += i + "\n";
}
The Insert() method can also increase the number of elements of a List. The difference between Insert() and Add() is that Add() will also place the new elements as the last one, while
Insert() allows the programmers to specify the index. In the following example, the string
"Seattle" is inserted with an index of “1” which make "Seattle" become the second element in
the List. The rest all got pushed to an index next to its original one.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList {
static void Main() {
List<String> list = new List<String>();
list.Add("New York");
list.Add("Boston");
list.Add("Chicago");
String str="Original List:\n";
for (int i=0; i<list.Count; i++)
{
str += list[i] + "\n";
}
str += "\nAfter inserting:\n";
list.Insert(1, "Seattle");
foreach (String s in list)
{
str += s + "\n";
}
Visual C# - Penn P. Wu, PhD. 187
MessageBox.Show(str);
}
}
One differences between array and List is that array has length but List has Count. The way to
get the number of elements in a List is through the Count property. Count is equal to Length
on arrays. For example,
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList
{
static void Main()
{
List<bool> list = new List<bool>();
list.Add(true);
list.Add(false);
list.Add(true);
list.Clear();
MessageBox.Show(list.Count+"");
}
}
Since a List is a dynamic array, you can copy an array to a List. The trick is creating a new
List and passing the name of an existing array as a parameter of the List. For example,
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList
{
static void Main()
{
String[] str = new String[4];
str[0] = "Spring";
str[1] = "Summer";
str[2] = "Fall";
str[3] = "Winter";
List<String> Season = new List<String>(str);
String newList="";
foreach (String s in Season) {
newList += s + "\n";
}
MessageBox.Show(newList);
}
}
Similar to the array, there are two ways to copy a List: formal way and short-hand way. The
above is the formal way, while the following is the short-hand way. You can also create a new
array inside a List. For example,
using System;
Visual C# - Penn P. Wu, PhD. 188
using System.Windows.Forms;
using System.Collections.Generic;
public class myList {
static void Main() {
List<int> list = new List<int>(new int[] {1, 3, 5, 7});
String str="";
for (int i=0; i<list.Count; i++) {
str += list[i] + "\n";
}
MessageBox.Show(str);
}
}
The List class provide a BinarySearch() method that searches the entire sorted List for an
element using the default comparer and returns the zero-based index of the element. In other
words, it returns the index starting at 0. However, BinarySearch() method will not work if the
List or array is not already sorted.
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList {
static void Main() {
List<int> list = new List<int>(new int[]
{6,11,23,37,45,52,67,74,81,96,102});
String str="";
str += list.BinarySearch(74) + "\n";
str += list.BinarySearch(45) + "\n";
str += list.BinarySearch(37) + "\n";
MessageBox.Show(str);
}
}
The AddRange() method can adds the specified collection of elements to a List. For example,
using System;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList {
static void Main() {
List<int> list = new List<int>();
list.Add(1);
list.Add(3);
list.Add(5);
list.Add(7);
String str="Original List:\n";
for (int i=0; i<list.Count; i++) {
str += list[i] + "\n";
}
str += "After adding an array:\n";
Visual C# - Penn P. Wu, PhD. 189
int[] x = new int[4];
x[0] = 9;
x[1] = 11;
x[2] = 13;
x[3] = 15;
list.AddRange(x);
foreach (int s in list) {
str += s + "\n";
}
MessageBox.Show(str);
}
}
Practical Examples
Have you ever been to a Chinese restraunt that gives customers fortune cookies after the meal? The following is a simple program that uses the Random class to randomly pick an integer
from 0 to 14. Then, it uses a switch..case structure to match the case and display the fortune
cookie saying. It can simulate a fortune cookie.
using System;
using System.Windows.Forms;
public class Example
{
public static void Main()
{
// an arry of fortune sayings
String[] fortune = new String[15];
fortune[0] = "Land is always on the mind of a flying bird.";
fortune[1] = "The man or woman you desire feels the same
about you.";
fortune[2] = "Meeting adversity well is the source of your
strength.";
fortune[3] = "A dream you have will come true.";
fortune[4] = "Our deeds determine us, as much as we determine
our deeds.";
fortune[5] = "Never give up. You're not a failure if you
don't give up.";
fortune[6] = "You will become great if you believe in
yourself.";
fortune[7] = "There is no greater pleasure than seeing your
loved ones prosper.";
fortune[8] = "You must try, or hate yourself for not
trying.";
fortune[9] = "You can make your own happiness.";
fortune[10] = "The greatest risk is not taking one.";
fortune[11] = "Love can last a lifetime, if you want it to.";
fortune[12] = "Adversity is the parent of virtue.";
fortune[13] = "Serious trouble will bypass you.";
fortune[14] = "Wealth awaits you very soon.";
int n = (new Random()).Next(0, 15); // random number
MessageBox.Show(fortune[n]);
}
}
The following is a sample output.
Visual C# - Penn P. Wu, PhD. 190
Summary C# supports single-dimensional arrays, multidimensional arrays, and array-of-arrays (jagged
arrays). The following examples shows how you declare them,
Single-dimensional Multidimensional Jagged int[] numbers; string[,] names; byte[][] scores;
Declaring them does not actually create the arrays. In C#, arrays are objects and must be
instantiated. The following examples, show how to create arrays:
Single-dimensional Multidimensional Jagged int[] n=new int[5]; string[,] x=new string[5,4]; byte[][] s=new byte[5][];
To initialize arrays, you can simply enclose the initial values in curly braces ({}). For example,
// Single-dimensional int[] n=new int[5] {0, 1, 2, 3, 4};
string[] s = new string[2] {"apple", "orange"};
int[] n=new int[] {0, 1, 2, 3, 4};
string[] s = new string[] {"apple", "orange"};
int[] n= {0, 1, 2, 3, 4};
string[] s = {"apple", "orange"};
// Multidimensional int[,] x = new int[3,2] { {0,1}, {2,3}, {4,5} };
string[,] s = new string[2,2] { {"T", "Tokyo"}, {"H", "Hiroshima"} };
int[,] x = new int[,] { {0,1}, {2,3}, {4,5} };
string[,] s = new string[,] { {"T", "Tokyo"}, {"H", "Hiroshima"} };
int[,] x = { {0,1}, {2,3}, {4,5} };
string[,] s = { {"T", "Tokyo"}, {"H", "Hiroshima"} };
// Jagged int[][] n = new int[2][] {new int[] {2,3,4}, new int[] {5,6,7,8,9} };
int[][] n = new int[][] {new int[] {2,3,4}, new int[] {5,6,7,8,9} };
int[][] n = {new int[] {2,3,4}, new int[] {5,6,7,8,9} };
Review
Questions
1. Given the following C# code, the output is __.
int[] n = new int[] {1, 2, 3, 4};
MessageBox.Show(n[3] + "");
A. 1 B. 2 C. 3 D. 4
2. Given the following C# code, the output is __.
int[] n = new int[] {1, 2, 3, 4};
MessageBox.Show(n[0] + n[3] + "");
A. 5 B. 6 C. 7 D. 8
Visual C# - Penn P. Wu, PhD. 191
3. Given the following C# code, which yields the output 3?
int[] n = new int[4];
n[0] = 1;
n[1] = 2;
n[2] = 3;
n[3] = 4;
A. MessageBox.Show (n[0] + "");
B. MessageBox.Show (n[1] + "");
C. MessageBox.Show (n[2] + "");
D. MessageBox.Show (n[3] + "");
4. Given the following C# code, what is the output?
int[] n = new int[10];
n[2] = 1;
n[3] = 2;
n[6] = 3;
n[9] = 4;
MessageBox.Show(n[2] + "");
A. 1 B. 2 C. 3 D. 4
5. Given the following C# code,
string[] course = new string[4];
course[0] = "Perl Programming";
course[1] = "PHP Programming";
course[2] = "Python Programming";
course[3] = "Plank Programming";
which generate the following output?
PHP Programming
A. MessageBox.Show( course[0] + "");
B. MessageBox.Show( course[1] + "");
C. MessageBox.Show( course[2] + "");
D. MessageBox.Show( course[3] + "");
6. Given the following C# code, the correct output is __.
string[] items = { "apple","orange","banana","tangerine" };
items[3]="grape";
MessageBox.Show(items[1] + items[3]);
A. orangegrape
B. applebanana
C. orange grape
D. apple banana
7. Given the following C# code, the output is __.
string[][] myJarr = new string[1][];
myJarr[0] = new string[4] { "Alaska", "Alabama",
"California", "Nevada" };
Visual C# - Penn P. Wu, PhD. 192
MessageBox.Show(myJarr[0][2]);
A. Alabama
B. Alaska
C. California
D. Nevada
8. Given the following C# code, which combination can yield a result of 10?
using System;
class myArray {
static void Main() {
int[] x = { 9, 6, 4, 2, 5, 8, 9};
}
}
A. Console.Write(x[2] + x[5]);
B. Console.Write(x[0] + x[4] - x[2]);
C. Console.Write(x[2] * x[4]);
D. Console.Write(x[1] + x[6]);
9. Given the following code, which displays the value 6?
int[,] arr2D = new int[,] { { 1, 2 }, { 3, 4 },
{ 5, 6 }, { 7, 8 } };
A. MessageBox.Show(arr2D[0,1] + "");
B. MessageBox.Show(arr2D[1,1] + ""); C. MessageBox.Show(arr2D[2,1] + "");
D. MessageBox.Show(arr2D[2,2] + "");
10. Given the following code, which displays the value Chen?
string[,] names = new string[2, 2] { {"Helen","Chen"},
{"Peter","Garcia"} };
A. names[0,0]);
B. names[0,1]);
C. names[1,1]);
D. names[1,0]);
Visual C# - Penn P. Wu, PhD. 193
Lab #6 C# Arrays and Lists
Learning Activity #1: Different array types in C#
1. Create a new directory called C:\CIS218 if it does not exist.
2. Launch the Development Command Prompt (not the Windows Command Prompt). (See Lab #1 for details)
3. Under the C:\cis218 directory, use Notepad to create a new source file called lab6_1.cs with the following contents:
using System;
using System.Windows.Forms;
public class Example
{
static void Main(string[] args)
{
// Declare a single-dimensional array
int[] array1 = new int[5];
array1[0] = 100;
array1[1] = 101;
array1[2] = 102;
array1[3] = 103;
array1[4] = 104;
string str = "1D arrays\narray1 : ";
for (int i=0; i<array1.Length; i++)
{
str += array1[i] + " ";
}
// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };
str += "\narray2 : ";
int j=0;
while(j<array2.Length)
{
str += array2[j] + " ";
j++;
}
// Alternative syntax
int[] array3 = { 2, 4, 6, 8, 10 };
str += "\narray3 : ";
foreach (int k in array3)
{
str += k + " ";
}
// Declare a two dimensional array
int[,] mArray1 = new int[2, 3];
mArray1[0,0] = 27;
mArray1[0,1] = 28;
mArray1[0,2] = 29;
Visual C# - Penn P. Wu, PhD. 194
mArray1[1,0] = 37;
mArray1[1,1] = 38;
mArray1[1,2] = 39;
str += "\n\n2D arrays\n1st element are made of : " + mArray1[0,0] + ", " +
mArray1[0,1] + ", " +mArray1[0,2] + "\n";
str += "2nd element are made of : " + mArray1[1,0] + ", " + mArray1[1,1] + ", "
+mArray1[1,2] + "\n";
// Declare and set array element values
int[,] mArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };
str += "1st element are made of : " + mArray2[0,0] + ", " + mArray2[0,1] + ", "
+mArray2[0,2] + "\n";
str += "2nd element are made of : " + mArray2[1,0] + ", " + mArray2[1,1] + ", "
+mArray2[1,2] + "\n";
str += "\n\nApplication of arrays:\n";
int m, d, y, w;
DateTime today=DateTime.Now;
y=today.Year;
m=today.Month - 1; //because the first key of array is 0
d=today.Day;
w=(int) today.DayOfWeek;
string[] Months = {"January","February","March","April","May",
"June","July","August","September","October",
"November","December"};
string[] Weekdays = { "Sun", "Mon","Tue","Wed","Thu","Fri","Sat" };
str += "Today is " + Weekdays[w] + ", " + d + ", " + Months[m] + ", " + y;
MessageBox.Show(str);
}
}
4. In the prompt, type csc /t:winexe lab6_1.cs and press [Enter] to compile the source code. The compiler
creates a new file called lab6_1.exe.
5. Test the lab6_1.exe file. A sample output looks:
6. Download the “assignment template”, and rename it to lab6.doc if necessary. Capture a screen shot similar to
the above and paste it to the Word document named lab6.doc (or .docx).
Learning Activity #2: 3D Arrays
1. Under the C:\cis218 directory, use Notepad to create a new source file called lab6_2.cs with the following
contents:
Visual C# - Penn P. Wu, PhD. 195
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
int[, ,] my3d = new int[2, 3, 4];
// row 1
my3d[0,0,0]=1; // column 1
my3d[0,0,1]=7;
my3d[0,0,2]=13;
my3d[0,0,3]=19;
my3d[0,1,0]=2; // column 2
my3d[0,1,1]=8;
my3d[0,1,2]=14;
my3d[0,1,3]=20;
my3d[0,2,0]=3; // column 3
my3d[0,2,1]=9;
my3d[0,2,2]=15;
my3d[0,2,3]=21;
// row2
my3d[1,0,0]=4; // column 1
my3d[1,0,1]=10;
my3d[1,0,2]=16;
my3d[1,0,3]=22;
my3d[1,1,0]=5; // column 2
my3d[1,1,1]=11;
my3d[1,1,2]=17;
my3d[1,1,3]=23;
my3d[1,2,0]=6; // column 3
my3d[1,2,1]=12;
my3d[1,2,2]=18;
my3d[1,2,3]=24;
// Shorthand way
string[,,] name = {
{ {"Nancy", "Helen", "Jane", "Marie"}, {"Akiko", "Megumi", "Keiko", "Narumi"},
{"Xiafeng", "Minna", "Liping", "Xiaoyeng"} }, //row1
{ {"Alicia", "Leticia", "Rosa", "Silvia"}, {"Astha", "Brijal", "Janaki",
"Neha"}, {"Kyungmi", "Eunkyung", "Heajung", "Misu"} } //row2
};
String str = "Value of elements:\n";
for (int r=0; r<2; r++)
{
for (int c=0; c<3; c++)
{
for (int l=0; l<4; l++)
{
// elements of my3d
str += "my3d[" + r + "," + c + "," + l +"] is " + my3d[r,c,l] + "\t";
// elements of name
Visual C# - Penn P. Wu, PhD. 196
str += "name[" + r + "," + c + "," + l +"] is " + name[r,c,l] + "\n";
}
}
}
str += "\nSize: " + my3d.Length + "\nRank: " + my3d.Rank;
MessageBox.Show(str);
}
}
2. Compile and test the program. A sample output looks:
3. Capture a screen shot similar to the above and paste it to the Word document named lab6.doc (or .docx).
Learning Activity #3: Jagged array
1. Under the C:\cis218 directory, use Notepad to create a new source file called lab6_3.cs with the following contents:
using System;
using System.Windows.Forms;
class myArray
{
static void Main()
{
int[][] ja = new int[3][];
ja[0] = new int[5]; //child 1
ja[0][0]=1; //element 1
ja[0][1]=3; //element 2
ja[0][2]=5;
ja[0][3]=7;
ja[0][4]=9;
ja[1] = new int[4]; //child 2
ja[1][0]=0; //element 1
ja[1][1]=2; //element 2
ja[1][2]=4;
ja[1][3]=6;
ja[2] = new int[2]; //child 3
ja[2][0]=11; //element 1
ja[2][1]=22; //element 2
// shorthand way
Visual C# - Penn P. Wu, PhD. 197
char[][] c = new char[][] {
new char[] {'D', 'M', 'C', 'W', 'P'},
new char[] {'K', 'Y', 'R', 'E'},
new char[] {'Z', 'Q'}
};
string str = "Elements\n";
for (int i=0; i<ja.Length; i++)
{
for (int j=0; j<ja[i].Length; j++)
{
// elements of ja
str += "ja[" + i + "][" + j + "]" + ja[i][j] + "\t";
// elements of c
str += "c[" + i + "][" + j + "]" + c[i][j] + "\n";
}
}
str += "\nLength: " + ja.Length + "\nDimension: " + ja.Rank;
MessageBox.Show(str);
}
}
2. Compile and test the program. A sample output looks:
3. Capture a screen shot similar to the above and paste it to the Word document named lab6.doc (or .docx).
Learning Activity #4: ArrayList
1. Under the C:\cis218 directory, use Notepad to create a new source file called lab6_4.cs with the following
contents:
using System;
using System.Windows.Forms;
using System.Collections;
public class myList
{
static void Main()
{
ArrayList course = new ArrayList();
course.Add("CIS211");
course.Add("CIS212");
course.Add("CIS213");
string str = "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
Visual C# - Penn P. Wu, PhD. 198
foreach(string c in course)
{
str += c + "\n";
}
MessageBox.Show(str);
course.Add("CIS214");
course.Add("CIS215");
str = "New list\n";
str += "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
foreach(string c in course)
{
str += c + "\n";
}
MessageBox.Show(str);
course.Clear();
course.TrimToSize();
str = "After clearance\n";
str += "Capacity: " + course.Capacity + "\n";
str += "Count: " + course.Count + "\n";
MessageBox.Show(str);
}
}
2. Compile and test the program. A sample output looks:
and and
3. Capture a screen shot similar to the above and paste it to the Word document named lab6.doc (or .docx).
Learning Activity #5:
1. Under the C:\cis218 directory, use Notepad to create a new source file called lab6_5.cs with the following
contents:
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;
public class myList
{
static void Main()
{
Form form1 = new Form();
Label label1 = new Label();
label1.Location = new Point(10, 10);
Visual C# - Penn P. Wu, PhD. 199
label1.AutoSize = true;
form1.Controls.Add(label1);
Label label2 = new Label();
label2.Location = new Point(150, 10);
label2.AutoSize = true;
form1.Controls.Add(label2);
// code
List<int> lst = new List<int>();
lst.Add(1);
lst.Add(3);
lst.Add(5);
lst.Add(7);
label1.Text = "Original List:\n";
for (int i=0; i<lst.Count; i++) {
label1.Text += lst[i] + "\n";
}
label1.Text += "\nCount: " + lst.Count + "\n";
label1.Text += "Capacity: " + lst.Capacity+ "\n";
// add a range of items
int[] x = new int[5];
x[0] = 9;
x[1] = 11;
x[2] = 13;
x[3] = 15;
x[4] = 17;
lst.AddRange(x);
label2.Text += "After adding an array:\n";
foreach (int s in lst) {
label2.Text += s + "\n";
}
label2.Text += "\nCount: " + lst.Count + "\n";
label2.Text += "Capacity: " + lst.Capacity+ "\n";
// initialize Windows form
Application.Run(form1);
}
}
2. Compile and test the program. A sample output looks:
Visual C# - Penn P. Wu, PhD. 200
3. Capture a screen shot similar to the above and paste it to the Word document named lab6.doc (or .docx).
Submittal
1. Complete all the 5 learning activities.
2. Create a .zip file named lab6.zip containing ONLY the following self-executable files.
• Lab6_1.exe
• Lab6_2.exe
• Lab6_3.exe
• Lab6_4.exe
• Lab6_5.exe
• Lab6.doc (or .docx) [You may be given zero point if this Word document is missing]
3. Log in to course site and enter the course site.
4. Upload the zipped file as response to question 11.
Programming Exercise: Array
1. Use Notepad to create a new file named ex06.cs with the following heading lines (be sure to replace
YourFullNameHere with the correct one):
//File Name: ex06.cs
//Programmer: YourFullNameHere
2. Under the above two heading lines, write C# codes to create an array named “campus” with the following
elements: “Cypress”, “Pomona”, “Cerritos”, “Long Beach”, “Irvine”, and “San Diego.”
3. Write codes using a for loop to display the value of each element using ArrayName[key] format in a message
box, as shown below. Your codes must create the array and its elements. You will receive zero if you simply
display the message.
4. Download the “programming exercise template”, and rename it to ex06.doc. Capture a screen shot similar to the
above figure and then paste it to the Word document named “ex06.doc” (or .docx).
5. Compress the source code (ex06.cs), the executable (ex06.exe), and the Word document (ex06.doc or .docx) to
a .zip file named “ex06.zip”. You may be given zero point if any of the required file is missing.
Grading Criteria:
• You must be the sole author of the codes.
• You must meet all the requirements in order to earn credits.
• No partial credit is given.