Doing Arrays - C#

Introduction


An Array is a collection of same type variables which can be accessed using numeric index. The numeric index is written in square brackets after the array name.

Following is the declaration of a single dimension Array.
  1. int[ ] Roll = new int[5];
roll.png

Characteristics


The numeric index is zero based. It goes from 0 to n-1 where n is the size of the array (The total number of elements in the Array).

On declaration, the default value of numeric type Arrays are set to 0, and Reference types are set to null.

Arrays are stored in continuous memory locations as shown in figure.

In C#, Arrays are objects, and they have certain properties like Length, which can be used by using (.) and property name. All arrays are derived from abstract Class Arrays so many built-in Methods can be called.
  1. //Rank propety Return number of dimensions  
  2. int[ ] single = new int[4] { 1, 2, 3, 4 };  
  3. int dimension = single.Rank;  

Single Dimension Arrays


It is the simplest form of Arrays; it's kind of a Row with n columns where each column is accessed with the zero based index. The preceding two examples show single dimension arrays.

In C#, declaration of an array is a bit different from C or C++. In C# the square brackets are placed after the type name instead of after the array-name, which (in C#) is followed by the keyword new and then the type followed with square brackets containing the size of the array.

Type[] arrayname = new Type[size];

The following code initializes a single dimension Integer Array of size 5. It contains 5 elements which can be accessed by arr[0] to arr[4].
  1. //Integer Array declaration  
  2. int[ ] arr = new int[5];   
  3. Character type Arrays are declared as following   
  4.   
  5. //Charahcetr Type array  
  6. char[ ] name = new char[10];
NAME.jpg

The same way, String Type Arrays are declared
  1. //String Array declaration  
  2. string[ ] days = new string[7];
DAYS.jpg

In above example, days has referee type elements all assigned to null. Before using elements of days Array, we need to initialize them. Each element can vary in length, this point will get clear after reading Jagged Arrays.

There are many ways to assign values to an Array. An Array can be initialized in a declaration line by placing the values between curly braces { } in comma separated fashion. Characters are placed in single quotes and Strings are placed in double quotes.
  1. //Integer Array Initialization  
  2. int[ ] arr = new int[5] { 1, 2, 3, 4, 5 };  
  3. //Charahcetr Array Initialization  
  4. char[ ] name = new char[10] { 'i'' ''a''m'' ''f''i''n''e''.' };  
  5. //String Array Initialization  
  6. tring[ ] DAYS = new string[7] { "SATURDAY""SUNDAY""MONDAY""TUESDAY""WEDNESDAY""THURSDAY""FRIDAY""SATURDAY" };  
While initializing the Array, the size of the Array may be omitted. If it is then the size of the array will be calculated from the number of elements written in curly braces.

Another way of declaring and initializing an Array is

  1. //Integer Array Declaration, Initialization  
  2. int[ ] arr;  
  3. arr = new int[5] { 1, 2, 3, 4, 5 };  
The following way of assigning values to an Array will cause an error.
  1. //Wrong Way of Writing  
  2. int[ ] arr = new int[5];  
  3. arr = { 1, 2, 3, 4, 5 };  

Iterating Through Single Dimension Array


In C#, Arrays are objects and retain certain built-in properties. The Length property returns the total number of elements in the Array. Right now we are dealing with a single dimension, so the total number of elements is equal to the size of the array.
  1. for (int i = 0; i < arr.Length; i++)  
  2. {  
  3.     Console.WriteLine(i);  
  4. }  
  5. Console.ReadLine();
array4.gif

Multi Dimensional Arrays


Arrays can be multidimensional. The most widely used are two-dimensional Arrays, often Matrices form 2D Arrays. In 2D Array, 2 zero based indexes are used to access a particular value in the Array.
  1. //Integer 2D Array  
  2. int[,] matrix = new int[10, 10];  
  3.   
  4.   
  5. //Accessing Value  
  6. int val = matrix[5, 7];
array5.gif

The Value of an element stored in 5th Row, 7th Column is 58, which will be assigned to Variable val. Rows and Columns have zero based index. The total number of values which can be stored in 2D array is equal to the product of rows and columns. For the above case it is 100.

A single dimension Array is a single Row with columns >0. 2D Arrays have more than one Row, thus form a table.

array6.gif

Accessing the element stored in 3rd row, 4th column in balances table.

To initialize 2D array, each row values are placed in curly braces as in case of single dimensional array and then these set of curly braces for all rows are placed in another set of curly braces in same fashion.
  1. //2D Array Initializtion  
  2. int[,] arr_2d = new int[3, 2] { { 1, 2 }, { 3, 4 }, { 5, 6 } };  
  3. //Initializing 2Dimensional Array  
  4. char[,] day = new char[2, 3] { { 'o''n''e' }, { 't''w''o' } };  

In the preceding piece of code, there are 3 rows and 2 columns; thus the total number of elements is 2 x 3 = 6. It's hard to initialize 2D array shown in 1st figure, where it has 10 rows and 10 columns. Loops can be used to assign values to each location.

  1. //Assigning Values to matrix[10,10] array  
  2. for (int i = 0; i < 10; i++)  
  3. {  
  4.     for (int j = 0; j < 10; j++)  
  5.     {  
  6.         matrix[i, j] = i * 10 + j + 1;                      
  7.     }                  
  8. }  
In the case of multidimensional Arrays, knowing the number of dimensions is sometimes necessary to have more grip over the Array. Rank property returns number of dimensions of the Array.
  1. //Getting Number of dimensions of Array  
  2. int dim = matrix.Rank;  
The GetUpperBound function returns the upper bound of the array in a particular dimension.
  1. for (int i = 0; i <= matrix.GetUpperBound(0);i++)  
  2. {  
  3.     for (int j = 0; j <= matrix.GetUpperBound(1); j++)  
  4.     {  
  5.         Console.Write(matrix[i, j].ToString() + "\t");  
  6.     }  
  7.     Console.WriteLine();  
  8. }  
Output of above piece of code.

array7.gif

GetLowerBound method gets the lower bound of the Array in a particular dimension. Following figure shows the difference between length, upper bound and lower bound.

array8.gif

We can have more than two dimensions for Arrays as well. For three dimensional arrays, we need three indexes to access each element in the Array. An example of a 3 dimension array can be a point in space. Consider a block of small bricks, as shown in figure below, to address each small brick, there is one index for row, one for column and one for depth.

array9.gif
  1. //Block code 3D array  
  2. int[, ,] block_3d = new int[2, 3, 4];  
Example of 4-dimensional array can be taken as one second in a week, there are 60 seconds in one hour, 60 mins in one hour, 24 hours a day and 7 day a week.

array10.gif
  1. //Week 4D array  
  2. int[, , ,] week = new int[7, 24, 60, 60];
array11.gif

Jagged Arrays


Array of Arrays are called Jagged Arrays.

array12.gif

The statement might be confusing but consider the example of saving marks of few students who are studying different number of subjects.

Student-1 marks 65, 60, 76
Student-2 marks 78, 92, 68, 90, 55
Student-3 marks 45, 59, 88, 72

If we use a 2-Dimension Array to store the above marks, then an Array of 3 rows and 5 columns is needed. The extra info needs to be added at locations for which marks don't exist.
 
65 60 76 0 0
78 92 68 90 55
45 53 88 72 0

Jagged Arrays come handy in such situation. Jagged Arrays may have different sizes and dimensions. For this situation, we need one single dimension Array with three elements, and each of its elements is a single dimension array with length 3, 5, 4 respectively.

  1. //Jagged arrays  
  2. int[ ][ ] student = new int[3][ ];  
In the above piece of code, two sets of square brackets are used. Now each element of Jagged Array needs to be assigned to a single dimension Array.
  1. //Declaring Each Element of Jagged Array  
  2. student[0] = new int[3];  
  3. student[1] = new int[5];  
  4. student[2] = new int[4];  
Values can also be assigned just like single dimension Array by placing after square brackets.
  1. //Initializing Each Element of Jagged Array  
  2. student[0] = new int[3] { 65, 60, 76 };  
  3. student[1] = new int[5] { 78, 92, 68, 90, 55 };  
  4. student[2] = new int[4] { 45, 59, 88, 72 };  
A short way of doing this is
  1. //Jagged arrays  
  2. int[ ][ ] student = new int[3][ ]  
  3. {  
  4. new int[3] { 65, 60, 76 },  
  5. new int[5] { 78, 92, 68, 90, 55 },  
  6. new int[4] { 45, 59, 88, 72 }  
  7. };  
Jagged Arrays are a reference type, thus they are initialized to null. To access elements in a Jagged Array in the student example, 2 indexes are used.
  1. //Accessing elements in Jagged Array  
  2. student[2][2] = 80;  
  3. for (int i = 0; i < student.Length; i++)  
  4. {  
  5.     for (int j = 0; j < student[i].Length; j++)  
  6.     {  
  7.         Console.Write(student[i][j]);  
  8.         Console.Write('\t');  
  9.     }  
  10.     Console.WriteLine();  
  11. }
array13.gif

Mixed Arrays


Combination of jagged and multidimensional Arrays is known as mixed Arrays. In case of multidimensional arrays of different sizes, mixed Arrays are used. Consider there are three tables, each with a different number or rows and columns.

Table-1 3 rows, 5 columns
Table-2 4 rows, 3 columns
Table-2 6 rows, 4 columns
  1. //Mixed Arrays  
  2. int [ ][,]mixed=new int[3][ ]  
  3. {  
  4.     new int[3,5],  
  5.     new int[4,3],  
  6.     new int[6,4]  
  7. };  
Have Nice Time.

Do suggest, comment and vote to keep it Alive.


Similar Articles