Chapter Three
3.2 Using Arrays
1
Objectives
• How to declare an array and assign values to
array elements
• How to initialize an array
• How to use subscripts to access array elements
• How to use the Length field
• How to use foreach to control array access
2
Objectives
• How to manually search an array to find an exact
match
• How to search an array to find a range match
• How to use the BinarySearch() method
• How to use the Sort() and Reverse() methods
3
Objectives
• How to pass an array to a method
• How to use parameter arrays
• How to declare an array of objects
• How to use the BinarySearch() and Sort() methods
with object arrays
4
Array
• Sometimes storing just one value in memory at a time is not
adequate
• An array is a list of data items that all have the same type,
same name and stored in consecutive memory address.
Array Types
• An array has a rank that determines the number of indices
associated with each array element.
• The rank of an array is also referred to as the dimensions of
the array. There are 2 types of arrays in C# programming:
– Single Dimensional Array - an array with a rank of one
– Multidimensional Array - an array with a rank greater than one
5
Single Dimensional Array
Declaring single dimensional Array
• General syntax:
datatype [] arrayName;
where,
• datatype is used to specify the type of elements in the
array.
• [ ] specifies the rank of the array. The rank specifies the
size of the array.
• arrayName specifies the name of the array and it
should be a valid identifier.
• Example of array declaration:
double[] salesFigure; 6
Declaring single dimensional Array
• Like objects, memory is not actually reserved until
the new keyword is used.
• Syntax:
arrayName = new datatype [size];
Example: salesFigure = new double[20];
• You can put the two step together as follow
datatype[] arrayName = new datatype [size];
Example: double[] balance = new double[10];
7
Declaring an Array and Assigning Values to Array
Elements
• A subscript or index is an integer contained within square
brackets that indicate the position of one of an array’s
variables, or elements
• An array’s elements are numbered beginning with 0
• A common mistake is to forget that the first element in an
array is element 0
8
Declaring an Array and Assigning Values to Array
Elements
• Output of the ArrayDemo1 program
9
Initializing an Array
• Arrays, like object fields, have default values
• You can assign nondefault values to array elements upon
creation
• You can initialize the array during or after declaration.
• The general syntax during declaration
– datatype[] arrayName = new datatype [size] { array_elements}; or
– datatype[] arrayName = new datatype [] { array_elements}; or
– datatype[] arrayName = { array_elements};
• Examples:
int[] myScores = new int[5] {100,76,88,100,90};
int[] myScores = new int[] {100,76,88,100,90};
int[] myScores = {100,76,88,100,90};
10
Initializing an Array
• The general syntax after declaration:
– arrayName [index] = value; or
– Use loop statement to accept array elements from a user
// Using for loop
for (int i = 0; i < size; i++)
{
[Link](“Enter the {0} array element : ”, (i+1));
//convert if the data type of the array is other than string
arrayName[i]=[Link]()
}
• Examples:
int[] myScores = new int[5];
myScores [0] = 50;
myScores [1] = 60; . . . 11
Accessing Array Elements
• The power of arrays become apparent when you begin to use
subscripts that are variables rather than constant values
• The subscript used to access an array must be between the range of
0 to Length-1
• Because every array is automatically a member of the class
[Link], you can use the fields and methods that are part of
the [Link] class
• The Length field is a member of the [Link] class.
• The general syntax to access array elements is :
arrayName[index];
• A loop can be used to cycle through the elements of an array
// Using for loop
for (int i = 0; i < [Link]; i++)
{
[Link](arrayName[i]);
} 12
Using foreach to Control Array Access
• C# supports a foreach statement that you can use to cycle
through every array element without using subscripts
• With the foreach statement, the programmer provides a
temporary variable that automatically holds each array value
in turn
foreach (dataType varName in collection/array)
{
[Link](varName);
}
13
class SingleDArray
{
static void Main(string[] args)
{
int[] num = new int[10];
int sum = 0;
//Accept input from the keyboard
for (int a = 0; a < [Link]; a++)
{
[Link]("Enter the {0} array element : ", (a + 1));
num[a] = Convert.ToInt32([Link]());
}
//Display odd numbers and find the sum of even numbers only
for (int b = 0; b < [Link]; b++)
{
if (num[b] % 2 == 0)
sum = sum + num[b];
else
[Link]("{0} , ", num[b]);
}
[Link]("\nThe sum of even numbers : {0}", sum);
//Display the whole elements of the array
foreach (int number in num)
[Link]("{0} , ", number);
14
}
Manually Searching an Array for an Exact Match
• One way to determine if some variable holds one of many
possible valid values is to use a series of if statements
• Instead of creating a long series of if statements, a more
efficient solution is to compare the variable against the items
in an array
• In certain situations, where arrays are involved, it might be a
good idea to use parallel arrays
15
Manually Searching an Array for an Exact Match
Accessing information in parallel arrays
16
The BinarySearch() Method
• The BinarySearch() method finds a requested value in a
sorted array
• This method accepts two arguments: an array and the field to
be searched for
• The method returns –1 if the value is not found in the array,
otherwise it returns the index where the value is located
17
The BinarySearch() Method
• This method does NOT work under the following
conditions:
– If the array items are not arranged in ascending order, the
BinarySearch() method does not work correctly
– If the array holds duplicated values, then the BinarySearch
may not work
– If you want to find a range match rather that an exact
match, the BinarySearch() method does not work
18
Using the Sort() and Reverse() Methods
• The Sort() method arranges array items in ascending order
19
Using the Sort() and Reverse() Methods
• The Reverse() method reverses the order of items in an array
20
Writing Methods That Accept Array Parameters
• When you pass an array to a method, changes you make to
array elements within the method are permanent
• Arrays, like all objects, are passed by reference
• Within the method header, a parameter is declared as an
array using square brackets after the argument type
21
Using Parameter Arrays
• When you don’t know how many arguments you might
eventually send to a method, you can declare a local array
within the method header using the keyword param
• For example:
public static void DisplayStrings (param string[] people)
22
Using Parameter Arrays
ParamsDemo program and the output
23
Declaring an Array of Objects
• You can declare arrays that hold elements of objects
• To use a method that belongs to an object that is part of an
array, insert the appropriate subscript notation after the array
name and before the dot-method
• Example:
– empArray[x].SetId(999)
– empArray[x].SetSalary(7.25)
24
Using the BinarySearch() and Sort() Methods
with Object Arrays
• The use of methods like BinarySearch() and Sort() become
complicated when you use them with arrays of user-defined
objects
• When you create a class containing many fields, you must tell
the compiler which field to use when making comparisons
• An interface is a collection of methods that can be used by
any class, as long as the class provides a definition to override
the interface’s abstract definition
25
Using the BinarySearch() and Sort() Methods
with Object Arrays
• C# contains an interface named IComparable, which contains
the definition for the CompareTo() method that compares
one object to another and returns an integer
26
Using the BinarySearch() and Sort() Methods
with Object Arrays
• When you create a class whose members you will want to
compare, you must include two additional features in your
class:
– A single colon and the interface name IComparable after the class
name
– You must write a method containing the header
int [Link](Object o)
27
Using the BinarySearch() and Sort() Methods
with Object Arrays
• The CompareTo() method must return an integer value
28
Using the BinarySearch() and Sort() Methods
with Object Arrays
• [Link]() method for Employee class
29
Multidimensional Arrays
• A multidimensional is an 'array of arrays'.
• Arrays can have any number of dimensions. The most
common are two-dimensional arrays (2D).
• It is similar to tables in a database where each primary
element (row) is a collection of secondary elements
(columns).
• There are two types of multidimensional arrays in C#:
– Rectangular array (one in which each row contains an equal
number of columns)
– Jagged array (one in which each row does not necessarily
contain an equal number of columns)
30
31
Declaring Multidimensional Arrays
• Rectangular array declaration syntax
dataType [,] arrayName ;
arrayName = new dataType[rowsSize, columnsSize];
Or
dataType [,] arrayName = new dataType[rowsSize, columnsSize];
Example : int [,] myTable = new int[2,3];
• Jagged array declaration syntax
dataType [] [] arrayName = new dataType [rowsSize] [] ;
arrayName[rowIndex] = new dataType [columnsSize] ;
Example : int [] [] myTable = new int [3] [] ;
myTable[O] = new int [3] ;
myTable[1] = new int [5] ;
myTable[2] = new int [2]; 32
Initializing Multidimensional Arrays
• You can initialize the multidimensional array during or after
declaration.
Initializing Rectangular Array
• The general syntax during declaration
– dataType [,] arrayName = new dataType[rowSize,colSize]
{ {1strow_array_elements} , {2ndrow_array_elements}, … }; or
– dataType [,] arrayName = new dataType[,] { {1strow_array_elements}
, {2ndrow_array_elements}, … }; or
– dataType [,] arrayName = { {1strow_array_elements} ,
{2ndrow_array_elements}, … }; or
• Example
• int[,] recArray = new int[2,3] { { 100, 76, 88 }, { 100, 90, 55 } };
• int[,] recArray = new int[,] { { 100, 76, 88 }, { 100, 90, 55 } };
• int[,] recArray = { { 100, 76, 88 }, { 100, 90, 55 } }; 33
Initializing Rectangular Array
• The general syntax after declaration:
– arrayName[rowIndex, columnIndex] = value; or
– Use nested loop statement to accept array elements from a user
// Using for loop
for (int i = 0; i < rowSize; i++)
{
for (int j = 0; j < columnSize; j++)
{
//convert if the data type of the array is other than string
arrayName[i,j]=[Link]()
}
}
• Examples:
int[,] myScores = new int[2,3];
myScores [0,0] = 50;
myScores [1,0] = 60; . . . 34
Initializing Jagged Arrays
• The general syntax during declaration
– dataType [][] arrayName = new dataType[rowSize][];
arrayName[rowIndex] = new dataType[]
{array_elements}; or
– dataType [][] arrayName = new dataType[][]{
new dataType[] {array_elements}, …
};
or
– dataType [][] arrayName = {
new dataType[] {array_elements}, …
};
35
Initializing Jagged Array
• The general syntax after declaration:
– arrayName[rowIndex, columnIndex] = value; or
– Use nested loop statement to accept array elements from a user
// Using for loop
for (int i = 0; i < [Link]; i++)
{
for (int j = 0; j < arrayName[i].Length; j++)
{
//convert if the data type of the array is other than string
arrayName[i][j]=[Link]()
}
}
• Examples:
int[,] myScores = new int[2,3];
myScores [0,0] = 50;
myScores [1,0] = 60; . . . 36
Example
• int[][] jagged_arr1 = new int[2][];
jagged_arr1[0] = new int[] { 1, 2, 3, 4 };
jagged_arr1[1] = new int[] { 11, 34, 67 };
• int[][] jagged_arr2 = new int[][]
{
new int[] {1, 2, 3, 4},
new int[] {11, 34, 67}
};
• int[][] jagged_arr =
{
new int[] {1, 2, 3, 4},
new int[] {11, 34, 67}
};
37
Accessing Array Elements
• Rectangular array
– arrayName[rowIndex, columnIndex];
• Jagged array
– arrayName[rowIndex][columnIndex]
• Note: - Use loop statement to access the whole elements
of the array
38
Example
39
Example
40
Chapter Summary
• An array is a list of data items, all of which have the same
type and the same name
• In C#, arrays are objects of a class named [Link]; like
all objects, their fields are initialized to default values
• The power of arrays becomes apparent when you begin to
use subscripts that are variables rather than constant values
• When you work with array elements, you must ensure that
the subscript you use remains in the range 0 through length -
1
41
Chapter Summary
• You can use the foreach statement to cycle through every
array element without using subscripts
• When you want to determine whether some variable holds
one of many possible valid values, you can compare the
variable to a list of values in an array
• You can create parallel arrays to more easily perform a range
match
• The BinarySearch() method finds a requested value in a
sorted array
• The Sort() method arranges array items in ascending order.
The Reverse() method reverses the order of items in an array.
42
Chapter Summary
• You can pass a single array element to a method in exactly
the same manner as you would pass a variable. Alternatively,
instead of passing a single array element to a method, you
can pass an entire array.
• When you don’t know how many arguments you might
eventually send to a method, you can declare a local array
within the method header by using the keyword params
• Just as you can declare arrays of integers or doubles, you can
declare arrays that hold elements of any type
• When you create a class containing fields, you must create an
IComparable interface containing a CompareTo() method
43