Objects in this mirror are closer to Microsoft Technologies. DNM objective is to help users on Microsoft technologies by providing Articles, snippets, Interview Questions.

04 July 2012

Working with Arrays in C# - One dimensional array,two dimensional array, Jagged array with examples

In this article we will discuss how to handle array's in c# and different type of arrays with examples.

Definition: "Array is a group of related data items that share a common Name"

Example: if a class has 20 students with enrollment numbers then EnrollNo[12] represents 12th student enrollment number.
 Complete set of values from EnrollNo[1] to EnrollNo[20] represents array and individual value EnrollNo[12] called as element.

Array Types:
There are 3 types of array's are available
  1. One dimensional array
  2. Multi dimensional array
  3. Jagged array
 
One dimensional array:
Declaration of Array:
The general declaration of your array could be like
Datatype[] array_Name;
Eg : int[] myArray;
When you declare an array it will not create it in memory. We have to manually create the array using new operator.

Creating Array:
Generally creation of array will be like below
array_Name=new datatype[size]
Array_Name – yor array name(could be your notation)
Size – size of your array.

Example :
myArray=new int[10]. //creates a 10 element int array.
Note: If the size of array is 10 then the index starts from 0 and ends at 9. If you try to access 10th index which is outside the bound of array then it will throw run time error asIndexOutOfRangeException.

We can declare and create arrays at a time using below way.
 
float[] myNumber=new float[20]. //creates 20 element int array.
double[] myNumber=new double[5]. //creates 5 element dobule array.

Initialization of Arrays:
Putting the values to array elements is called array initialization.
Below code is for initialization one element in an array at a time
int[] myMarks = new int[5];
myMarks[0] = 10;
myMarks[1] = 20;
myMarks[2] = 30;
myMarks[3] = 40;
myMarks[4] = 50;

Error: For above code if you try to assign value to myMarks[4] it will throw IndexOutOfRangeException(error as “Index was outside the bounds of the array.”).

Declaratoin, Creation and Intiliazaton of any array at a time can be done using following code.
int[] myMarks = new int[5] {10,20,30,40,50};

Accessing Array elements:
We can access the array element individually or all at a time using foreach statement through iteration method.
Accessing array element by passing index will be like
int[] myMarks = new int[5];
myMarks[0] = 10;
myMarks[1] = 20;
myMarks[2] = 30;
myMarks[3] = 40;
myMarks[4] = 50;

//reading array Elements
Console.WriteLine(myMarks[0]);
Console.WriteLine(myMarks[1]);
Console.WriteLine(myMarks[2]);
Console.WriteLine(myMarks[3]);
Console.WriteLine(myMarks[4]);

Accessing array element using foreach statement:

int[] myMarks = new int[5];
myMarks[0] = 10;
myMarks[1] = 20;
myMarks[2] = 30;
myMarks[3] = 40;
myMarks[4] = 50;
 
//reading array elements
foreach (int myMark in myMarks)
{
Console.WriteLine(myMark);
}

Two dimensional Arrays:
In one dimensional array we stored list of values. But there will be a situation where we need to store table of values like
For Eg: In a class there are four students having three subject's(maths, physics, chemistry ). In order to represent term exam marks we will show like
Student name/Marks
Maths
Physics
Chemistry
Student_A
49
76
51
Student_B
50
40
60
Student_C
85
62
93
Student_D
87
59
67

Above table contains total 9 values consisting of 4rows (students) and 3 columns (subject wise marks). So the table looks like matrix.
In mathematics we represent matrix value as Vij. From above table V32(3rd row student and 2nd column marks) value is  62.

Memory representation of two dimensional arrays:
 
Column 0
 
Column 1
Column 2

E[0 , 0]
E[0 , 1]
E[0 , 2]
Row 0
49
76
51
 
E[1 , 0]
E[1 , 1]
E[1 , 2]
Row 1
50
40
60
 
E[2 , 0]
E[2 , 1]
E[2 , 2]
Row 2
85
62
93
 
E[3 , 0]
E[3 , 1]
E[3 , 2]
Row 3
87
59
67


E[i ,j] – array element of ith row and jth column.
 
Array element value
 
Array element representation

Declaration of 2-D Array:
The general declaration of your array could be like
Datatype[ , ] array_Name;
Eg : int[ , ] myArray;
When you declare an array it will not create it in memory. We have to manually create the array using new operator.

Creating 2-D Array:
myArray=new int[3,4]. //creates a 12 integer array elements.

We can declare and create arrays at a time using below way.
float[ , ] myNumber=new float[5,6]. //creates 30 elements int array.
double[ , ] myNumber=new double[2,4]. //creates 8 element dobule array.

Initialization of Arrays:
Putting the values to array elements is called array initialization.
Below code is for initialization one element in an array at a time
int[,] myMarks = new int[3,2];
myMarks[0,0] = 10;
myMarks[0,1] = 20;
myMarks[1,0] = 30;
myMarks[1,1] = 40;
myMarks[2,1] = 40;
myMarks[2,2] = 40;

Declaration, Creation and initialization of 2-D array at a time can be done using following code.
int[,] myMarks = new int[3,2] {{10,20},{30,40},{50,60}};

Accessing Array elements:
We can access array element individually or all at a time using foreach statement through iterations.
Accessing array element by passing index will be like
int[,] myMarks = new int[3,2];
myMarks[0,0] = 10;
myMarks[0,1] = 20;
myMarks[1,0] = 30;
myMarks[1,1] = 40;
myMarks[2,0] = 50;
myMarks[2,1] = 60;
//reading array Elements
Console.WriteLine(myMarks[0,0]);
Console.WriteLine(myMarks[0,1]);
Console.WriteLine(myMarks[1,0]);
Console.WriteLine(myMarks[1,1]);
Console.WriteLine(myMarks[2,0]);
Console.WriteLine(myMarks[2,1]);

Accessing array element using for each statement:

int[,] myMarks = new int[3,2];
myMarks[0,0] = 10;
myMarks[0,1] = 20;
myMarks[1,0] = 30;
myMarks[1,1] = 40;
myMarks[2,1] = 50;
myMarks[2,2] = 60;
 
//reading array elements
foreach (int myMark in myMarks)
{
Console.WriteLine(myMark);
}
Output: 10 20 30 40 50 60


If you want to access particular array element then you should know i and j positions. In this case you can use for statement.
for (int i = 0; i < myMarks.GetLength(0); i++)
{
                for (int j = 0; j < myMarks.GetLength(1); j++)
                {
                    Console.Write(myMarks[i, j]);
                }
}
Explanation:
myMarks.GetLength(0) – will return max lenth of first dimension in array
myMarks.GetLength(1) – will return max lenth of second dimension in array
myMarks.GetLength(2) – throws IndexoutofRange exception because above define are dimenstion are only 2.
 

Jagged Arrays:
It is also called as “array of arrays” or variable size arrays. Elements would be of different size and dimension.

Declaration of Jagged Array:
int[][] myJagArr = new int[3][]; //creates 3 rows array.
myJagArr[0] = new int[2];//first row has 2 elements
myJagArr[1] = new int[5];//second row has 5 elements
myJagArr[2] = new int[3];//third row has 3 elemetns

Initialization of Jagged Arrays:
Putting the values to array elements is called array initialization.
int[][] myJagArr = new int[3][]; //creates 3 rows array.
myJagArr[0] = new int[2];//first row has 2 elements
myJagArr[1] = new int[5];//second row has 5 elements
myJagArr[2] = new int[3];//third row has 3 elemetns

// Initializing jagged arrays
myJagArr[0] = new int[2] { 10, 20 };
myJagArr[1] = new int[5] { 30, 40, 50, 60,70 };
myJagArr[2] = new int[3] { 80, 90, 100};

Accessing Jagged Array elements:
We can access array element individually or all at a time using foreach statement through iterations.
Accessing array element by passing index will be like
int[][] myJagArr = new int[3][]; //creates 3 rows array.
myJagArr[0] = new int[2];//first row has 2 elements
myJagArr[1] = new int[5];//second row has 5 elements
myJagArr[2] = new int[3];//third row has 3 elemetns
// Initializing jagged arrays
 
myJagArr[0] = new int[2] { 10, 20 };
myJagArr[1] = new int[5] { 30, 40, 50, 60,70 };
myJagArr[2] = new int[3] { 80, 90, 100};
 
//reading array Elements
Console.WriteLine(myJagArr[0][0]);
Console.WriteLine(myJagArr[0][1]);
Console.WriteLine(myJagArr[1][0]);
Console.WriteLine(myJagArr[1][1]);
Console.WriteLine(myJagArr[1][2]);
Console.WriteLine(myJagArr[1][3]);
Console.WriteLine(myJagArr[1][4]);
Console.WriteLine(myJagArr[2][0]);
Console.WriteLine(myJagArr[2][1]);
Console.WriteLine(myJagArr[2][2]);

Note: while reading rectangular dimensional array we will use all indices in one set of brackets (like myarr[0,1]) but in jagged array each element in within its own square bracket(like myJagArr[0][1]).

Accessing array element using for each statement:
 
//reading array elements
foreach (int[] myEachRowJagArr  in myJagArr)
{
                foreach (int myJagArrVal in myEachRowJagArr)
                {
                    Console.Write(myJagArrVal);
                }
}
Output: 10 20 30 40 50 60 70 80 90 100

If you want to access particular array element then you should know i and j positions. In this case you can use for statement.
 
            for (int i = 0; i < myJagArr.Length; i++)
            {
                System.Console.Write("Elements in {0} row are: ", i + 1);
                for (int j = 0; j < myJagArr[i].Length; j++)
                {
                  System.Console.Write(myJagArr[i][j] + "\t");
                }
                System.Console.WriteLine();
            }
Output:

 
  


0 Comments:

Post a Comment