You are on page 1of 11

Arrays

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.

How Arrays are different from normal variables


How to Work with C# simple Arrays, Multi-Dimensional Arrays
How to use different methods available with Arrays
What are Jagged Arrays and how to work with them
How to use System.Array Class

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.

Working with Multidimensional Arrays


C# and the CLR contain direct support for multidimensional arrays, also known as
rectangular Arrays. You can easily declare an array with multiple rank within C#.
Multidimensional arrays are declared by placing commas within the square brackets.
The syntax for this is as follows:
type[,] arrayname;
For example, the following declaration creates a two-dimensional array of four rows and
two columns:
int[,] myArray = new int[4,2];
Also, the following declaration creates an array of three dimensions, 4, 2, and 3:
int[,,] myArray = new int [4,2,3];
Array Initialization
You can initialize the array upon declaration as shown in the following example:
int[,] myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};
int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};
You can also assign a value to an array element, for example:
myArray[2,1] = 25;
Example:
class Program
{
static void Main(string[] args)
{
int[,] Myarray = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < Myarray.GetLength(0); i++)
{
for (int j = 0; j < Myarray.GetLength(1); j++)
Page 5

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

for (int x = 0; x < 3; x++)


for (int y = 0; y < 3; y++)
for (int z = 0; z < 3; z++)
m[x, y, z] = n++;

sum = m[0, 0, 0] + m[1, 1, 1] + m[2, 2, 2];


Console.WriteLine("Sum of first diagonal: " + sum);
}
Jagged Arrays
A jagged array is an array whose elements are arrays. The elements of a jagged array
can be of different dimensions and sizes. A jagged array is sometimes called an "array of
arrays." The following examples show how to declare, initialize, and access jagged
arrays.
The following is a declaration of a single-dimensional array that has three elements, each
of which is a single-dimensional array of integers:
int[][] jaggedArray = new int[3][];
Before you can use jaggedArray, its elements must be initialized. You can initialize the
elements like this:
jaggedArray[0] = new int[5];
jaggedArray[1] = new int[4];
jaggedArray[2] = new int[2];
Each of the elements is a single-dimensional array of integers. The first element is an
array of 5 integers, the second is an array of 4 integers, and the third is an array of 2
integers.
Different ways to Initialize Jagged Array:
jaggedArray[0] = new int[] { 1, 3, 5, 7, 9 };
jaggedArray[1] = new int[] { 0, 2, 4, 6 };
jaggedArray[2] = new int[] { 11, 22 };
You can also initialize the array upon declaration like this:
Page 7

Arrays

int[][] jaggedArray2 = new int[][]


{
new int[] {1,3,5,7,9},
new int[] {0,2,4,6},
new int[] {11,22}
};
You can use the following shorthand form. Notice that you cannot omit the new operator
from the elements initialization because there is no default initialization for the elements:

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

Console.WriteLine("display values in first array");


for (i = 0; i < 4; i++)
Console.Write(jagged[0][i] + " ");
Console.WriteLine();
Console.WriteLine("display values in second array");
for (i = 0; i < 3; i++)
Console.Write(jagged[1][i] + " ");
Console.WriteLine();
Console.WriteLine("display values in third array");
for (i = 0; i < 5; i++)
Console.Write(jagged[2][i] + " ");
Console.WriteLine();
}
}
It is possible to mix jagged and multidimensional arrays. The following is a declaration
and initialization of a single-dimensional jagged array that contains two-dimensional
array elements of different sizes:
int[][,] jaggedArray4 = 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} }
};
Points to Remember
An array allows a collection of values of the same type to be stored and accessed
via a single variable.
The Microsoft .NET Common Language Runtime (CLR) supports singledimensional arrays, multidimensional arrays, and jagged arrays.
Array elements will be accessed by using index of the array.
All arrays are reference types which are allocated on the managed heap.
Arrays lower boundary start from 0.
If you step off the end of one of Array, thus going out of bounds, the runtime will
Page 9

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};

5.) What is Jagged Array?


a.) A jagged array is an array of arrays.
b.) Array which can hold multiple data types
c.)each row is a multidimensional arrays
d.)None of the above
6.) What is the base class for Array types?
a.) System.Array
b.)System.Collections.ArrayList
c.) Both the Above
d.) None of the Above

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

You might also like