Professional Documents
Culture Documents
Chapter 4:
Arrays
Objectives
This chapter focuses on different kinds of Arrays available in C#. At the end of this
chapter delegate would be in a position to accomplish the following activities.
Page 1
Arrays
Introduction
An array allows a collection of values of the same type to be stored and accessed
via a single variable. Each item is accessed in the array variable through the use of an
index value into the array.
Arrays are mechanisms that allow you to treat several items as a single collection.
The Microsoft .NET Common Language Runtime (CLR) supports single-dimensional
arrays, multidimensional arrays, and jagged arrays (arrays of arrays). All array types
are implicitly derived from System.Array, which itself is derived from System.Object.
This means that all arrays are always reference types which are allocated on the
managed heap, and your app's variable contains a reference to the array and not the array
itself. Each array, no matter what concrete type of array it is, implements all of the
methods and properties of System.Array.
Creating Arrays
Declaring an array with C# is quite straightforward. The way that you declare an array
within C# is similar to C/C++. A C# array may be created in a number of different ways.
One way is to simply declare an array without initializing it with any values. The syntax
for this is as follows:
type[] arrayname;
In the above example, type represents the type of data to be stored in the array (or
example, string, int, decimal etc). The square brackets ([]) indicate that this is the
declaration for an array and arrayname is the name by which the array is to referred.
For example, we can declare an array of strings called IIBC as follows:
string[] IIBC;
In this example, we have declared the array but not assigned any values to it. To assign
values after an array has been declared the new statement must be used combined with a
comma separated list of values. The following example shows different ways to create an
array.
string[] IIBC1 = new string[] {"red", "green", "yellow", "orange"};
An array may also be initialized in the declaration line simply by placing the comma
separated list of values after the declaration:
string[] IIBC2 = {"red", "green", "yellow", "orange", "blue"};
Another option is to declare the size of the array when it is created. For example, to
declare an array of size 5 simply place the size value within the square brackets of the
new statement:
Page 2
Arrays
IIBC3 = new string[5];
This will reserve the space required for the full array without actually placing any values
into the array.
Notice that in all cases, you must first allocate the array instances on the heap using the
new operator. The same thing happens with the IIBC2 instance, but the compiler does it
for you in order to facilitate the notational shorthand. One of the conveniences of .NET
arrays is that they are range-checked. Therefore, if you step off the end of one of them,
thus going out of bounds, the runtime will throw an IndexOutOfRangeException instead
of changing random memory, as in native C/C++.
Examples:
class Program
{
static void Main(string[] args)
{
int[] sample = new int[10];
int i;
for (i = 0; i < 10; i = i + 1)
sample[i] = i;
for (i = 0; i < 10; i = i + 1)
Console.WriteLine("sample[" + i + "]: " + sample[i]);
}
}
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 2, 3, 4, 5 };
Console.Write("Original order: ");
foreach (int i in nums)
Console.Write(i + " ");
Console.WriteLine();
//Reversing the Array
Array.Reverse(nums);
Console.Write("Reversed order: ");
foreach (int i in nums)
Page 3
Arrays
Console.Write(i + " ");
Console.WriteLine();
//Split Method
string s = "A B C D E";
char[] separators = { ' ' };
string[] words = s.Split(separators);
foreach (object obj in words)
Console.WriteLine("Word: {0}", obj);
}
}
Example: Sorting, Searching and Copying the Array
class Program
{
static void Main(string[] args)
{
//Sorting the Array
int[] intArray = { 5, 2, 3, 1, 6, 9, 7, 14, 25 };
Array.Sort(intArray);
int index = Array.BinarySearch(intArray, 5);
Console.WriteLine("Array.BinarySearch(intArray, 5) = " + index);
//Copying the Array using Array Class
int[] source = { 21, 22, 23, 24, 25 };
int[] target = new target[source.Length];
Array.Copy(source, target, source.Length);
Console.Write("target after copy: ");
foreach(int i in target)
Console.Write(i + " ");
Console.WriteLine();
//Copying the Array
int[] srcArray=new int[]{1,2,3,4};
int[] destArray = new int[srcArray.Length];
srcArray.CopyTo(destArray,0);
}
}
Page 4
Arrays
Note: Notice that many members of System.Array are defined as static members and are
therefore called at the class level (for example, the Array.Sort() or Array.Reverse()
methods). Methods such as these are passed in the array you wish to process.
Arrays
{
Console.Write(Myarray[i, j] + "\t");
}
Console.WriteLine();
}
foreach (int i in Myarray)
{
Console.Write(i + "\t");
}
}
}
In the example, I listed the items in the array using the foreach loop as shown. foreach
iterates over all items in the array in a row-major fashion. I could have achieved the same
goal using two nested for loops, and I definitely would have needed to do that if I needed
to iterate over the array elements in any other order. When doing so, keep in mind that the
Array.Length property returns the total amount of items in the array. In order to get the
count of each dimension, you must call the Array.GetLength method supplying the
dimension that youre interested in. When mapping multidimensional arrays to
mathematical concepts, the rectangular array is the most natural and preferred way to go.
Example:
int t, i;
int[,] table = new int[3, 4];
for (t = 0; t < 3; ++t)
{
for (i = 0; i < 4; ++i)
{
table[t, i] = (t * 4) + i + 1;
Console.Write(table[t, i] + " ");
}
Console.WriteLine();
}
//3x3 Array Example
static void Main(string[] args)
{
int[, ,] m = new int[3, 3, 3];
int sum = 0;
int n = 1;
Page 6
Arrays
Arrays
int[][] jaggedArray3 =
{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
A jagged array is an array of arrays, and therefore its elements are reference types and are
initialized to null.
Examples:
class Program
{
static void Main(string[] args)
{
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
int i;
Console.WriteLine("store values in first array");
for (i = 0; i < 4; i++)
jagged[0][i] = Int32.Parse(Console.ReadLine());
Console.WriteLine("store values in second array");
for (i = 0; i < 3; i++)
jagged[1][i] = Int32.Parse(Console.ReadLine());
Console.WriteLine("store values in third array");
for (i = 0; i < 5; i++)
jagged[2][i] = Int32.Parse(Console.ReadLine());
Page 8
Arrays
Arrays
throw an IndexOutOfRangeException.
Using foreach loop we can get the elements inside the array, we cannot assign
values to the elements.
A jagged array is an array whose elements are arrays.
It is possible to mix jagged and multidimensional arrays.
Check YourSelf
1.) Array in C# belongs to which type?
a.) Value Type
b.)Reference Type
c.)Both the Above
d.)None of the Above
2.) Which of the following is correct
a.) int arr[]=new int[10];
b.) int[] arr=new int[5];
c.) int[][] arr=new int[10][10];
d.) string names[]=new string[10];
3.) Which of the following is correct declaration for the multi dimensional array?
[
]
a.)int[] [] arr=new int[] [];
b.)int arr[][]=new int[][];
c.)int arr[,]=new int[3,3];
d.)int[,] arr=new int[2,2];
4.) which of the following statements are not valid? [
a.)int[] a=new int[]{1,2,3};
b.)int[] a=new int[4]{1,2,3,4};
c.) int[] a = { 1, 2, 3 };
d.)int a[]=new int[4]{1,2,3,4};
Page 10
Arrays
7.) Which of the following Interface can provide foreach iteration to arrays in C#?
[
]
a.)IDictionary
b.)IEnumerable
c.)IClonable
d.) None
8.)How many Types of arrays available in C#?
1.) one
2.) Three
3.) two
4.) five
Exercise:
Write a Program to sort the elements of the Array without using the Array.Sort
method.
Write a Program to create an array with non zero based lower-boundary value.
Create an Array by using System.Array class and read elements into the array and
display them using foreach loop.
Write the differences between static arrays and dynamic arrays.
Write a program to perform Arithmetic operations on two Arrays.
Write a Program to read the size of jagged Array, elements into the Array from the
Console and Output them.
Page 11