07 - C# Arrays

7.1 Introduction to Arrays

An array is a data structure that contains a number of elements of the same type. An array is declared by defining the type of elements inside an array followed by empty brackets and a variable name. The array index starts with zero. The first element starts at 0th position. The last position of the array element will be the total number of items – 1.

In C# arrays can be of two types as fixed length and dynamic. A fixed length array can store a predefined number of items. The length of the dynamic array increases when the user adds new elements to it. The declaration of array in C# is as shown below:

Where, datatype is used to specify the type of elements to be stored in an array. The [ ] specifies the rank of the array. The rank specifies the size of the array. arrayName specifies the name of the array.

The code snippet for declaring an array that can store 4 elements is as shown below:

int [ ] array1;
array1 = new int[4];

Initializing Arrays: Once an array is declared, user needs to initialize it. The initialization is the process of adding actual data to an array. The code snippet to add values to an array is as shown below:

Initializing a fixed array:

int [ ] numArray = new int [4] {1, 3, 5, 7 };

Initializing a fixed array for every element:

int [ ] numArray = new int [4];
numArray [0] = 1;
numArray [1] = 3;
numArray [2] = 5;
numArray [3] = 7;

 

7.2 Accessing Arrays Elements

User can access array items by passing item index in the array. The following code snippet uses the console method to display items:

int[ ] numArray = new int [4];
numArray [0] = 1;
numArray [1] = 3;
numArray [2] = 5;
numArray [3] = 7;

Console.WriteLine(numArray[0]);
Console.WriteLine(numArray[1]);
Console.WriteLine(numArray[2]);
Console.WriteLine(numArray[3]);

Using the foreach loop

User can access the elements of an array using the loop structure. The foreach statement can iterate through the array. A code sample for arrays using the foreach loop is as shown below:

 

class Demo
{
    static void Main ( string[ ] args )
    {
        int [ ] numArray = new int [4];
        
        for ( int i = 0; i<4; i++)
        {
            numArray [i] = i+1;
        }
        foreach ( int j in numArray )
        {
            int i = j-1;
            Console.WriteLine(“Element [ {0} = {1}”, i, j );
            i++;
        }
        Console.Read();
    }
}

 

The output for the code is as shown below:

7.3 C# Arrays in detail

Arrays can be defined into four types as follows:

1) Single – dimensional array

2) Multi – dimensional array

3) Jagged Array

4) Param Array

1) Single – dimensional array

Single dimensional array are used to store the number of items of a predefined type. All the items are stored in the contiguous memory location starting from 0 to size of the array – 1. The declaration and initialization of a single – dimensional array are as shown below:

2) Multidimensional array

Multi dimensional array has more than one dimension. The multidimensional array has a matrix form. A multidimensional array can be declared as follows:

A multidimensional array can be fixed or dynamic in size. The following code snippet defines the multidimensional array with matrix 2x2.

The initialization of multidimensional array is as shown below:

A multidimensional array items are represented in a matrix format. To access the elements user needs to define the matrix dimension. The following code snippet is used to define the access to members of an array.

class Demo
{
    static void Main ( string[ ] args )
    {
        int [ , ] num2 = new int [2,2];
        num2 [0,0] = 1;
        num2 [1,0] = 2;
        num2 [0,1] = 4;
        num2 [1,1] = 8;

        //Access members of multidimensional array
        Console.WriteLine(“The array value is:”+num2[0,0] );
        Console.WriteLine(“The array value is:”+num2[0,1] );
        Console.WriteLine(“The array value is:”+num2[1,0] );
        Console.WriteLine(“The array value is:”+num2[1,1] );
        Console.Read();
    }
}

 

The output of the following code is:

3) Jagged Array

Jagged Array is arrays of arrays. The elements of a jagged array are other arrays. While declaring jagged array, add two brackets. While initialization of array, first element is the size that defines the number of rows is set. The second brackets that define the number of elements inside the row are kept as every row has different number. The following code snippet is used to initialize the jagged array.

A code sample to demonstrate the jagged array is as shown below:

class Demo
{
    static void Main ( string [ ] args )
    {
         int [ ] [ ] jagedarray = new int [3] [ ];
         jagedarray [0] = new int [2] {1,2};
             jagedarray [1] = new int [6] {1,2,3,4,5,6};
             jagedarray [2] = new int [3] { 9,10,11};
             for ( int i = 0; i<jagedarray.Length;i++)
             {
            Console.Write(“Element{0}:”, i+1);
            for ( int j=0; j<jagedarray[i].Length;j++)
            {
           Console.Write(jagedarray[i][j]+”\t”);
            }
            Console.WriteLine();
              }
              Console.Read();
        }
}

The output for the code is as shown below:

4) Param Arrays

Param arrays are used when the number of parameters is not fixed. It is useful when the number of parameters is to be accepted at run time.

A code sample to demonstrate the Param arrays is as shown below:

class Demo
{
    static int add ( params int [ ] number )
    {
        int sum = 0;
        foreach ( int n in number )
        {
            sum=sum+n;
        }
        return sum;
    }
    static void Main ( string[ ] args )
    {
        int sum;
        sum = Demo.add(1,3,5);
        Console.WriteLine(“Sum of 1, 3, 5 is \t {0}”, sum );
    
        sum = Demo.add(3,4,5,6,7);
        Console.WriteLine(“Sum of 3,4,5,6,7 is \t {0}”, sum );
    
        Console.Read();
    }
}

The output for the code is as shown below:

7.4 Array Class

An array is declared with brackets is a C# notation of using the Array class. Using the C# syntax, a new class deriving from the abstract base class Array is created. It is possible for the user to use the properties and methods defined in the Array class.

The Array class contains the following properties and methods that user can write for every array instance.

Property

Description

Length

The Length property returns the number of elements inside the array. If the array is multidimensional array, user can get the number of elements of all ranks.

LongLength

The Length property returns a int value, the LongLength returns the length into a long value.

Rank

The Rank property is used to get the number of dimensions of the array

The code snippet for demonstrate the Length property is as shown below:

class Demo
{
    static void Main( string [ ] args )
    {
        int [ ] intArray = new int [5];
        int length = intArray.Length;
        Console.WriteLine(”The length of the array is”+length);
        Console.Read();
    }
}

The output of the code is as shown below:

The code snippet to demonstrate the LongLength property is as shown below:

class Demo
{
    static void Main ( string [ ] args )
    {
        long [ ] larray = new long [4];
        long length = larray.LongLength;
        Console.WriteLine(“The length of the array is”+length);
        Console.Read();
    }
}

 

The output for the code is as shown below:

The code snippet to demonstrate the Rank property is as shown below:

class Demo
{
    static void Main ( string [ ] args )
    {
        int [ , ] myarray = new int [2,5]{ {2,3,4,5,6}, {2,3,4,5,6} };
        Console.WriteLine(“Total dimensions of the array is:”+myarray.Rank);
        Console.Read();
    }
}

 

The output for the code is as shown below:

Methods of the Array class

The following table lists some of the methods of Array class.

Methods

Description

Sort

It is used to perform the sort operation on an array passed as a parameter

Clear

It removes all the items of an array and sets the range of items of an array to 0

GetLength

It returns the number of items in an array

GetValue

It returns the value of the specified item in an array

IndexOf

It returns the index of the first occurrence of a value in an array

The code snippet for the Sort method is as shown below:

class Program
{
    static void Main ( string [ ] args )
    {
        char [ ] array ={‘a’,’i’,’e’,’o’,’u’};
        Array.Sort(array);
        foreach ( var c in array )
            Console.WriteLine(c);
        Console.ReadLine();
    }
}

 

The output for the code is as shown below:

The code for the Clear method is as shown below:

class Program
{
    static void Main ( string [ ] args )
    {
        int [ ] intarray = new int[ ]
        {
            4,5,6,8
        };
        Console.WriteLine(“The values of the array before the method are”);
        foreach ( int value in intarray )
        {
            Console.WriteLine(value);
        }
        Array.Clear(intarray, 0, intarray.Length);
        Console.WriteLine(“The value of the array after the method are”);
        foreach ( int value in intarray )
        {
            Console.WriteLine(value);
        }
        Console.ReadLine();
          }
 } 

The output for the code is as shown below:

The code for the GetLength method is as shown below:

class Program
{
    static void Main ( string[ ] args )
    {
        int [ , ] arr = new int [5, 5];
        Console.WriteLine(“The value is”+arr.GetLength(0));
        Console.WriteLine(“The value is”+arr.GetLength(1));

        Console.ReadLine();
    }
}

 

The output for the code is as shown below:

The code for the GetValue method is as shown below:

class Program 
{
    static void Main ( string[ ] args )
    {
        string [ ] myarr1 = new string[5];
        myarr1.SetValue (“three”, 3);
        Console.WriteLibe(“[3]:{0}”, myarr1.GetValue(3) );
        Console.ReadLine();
    }
}

 

The output for the code is as shown below:

The code for the IndexOf method is as shown below:

class Program
{
    static void Main ( string [ ] args )
    {
        int [ ] arr1 = new int [6];
        arr1[0] = 1;
        arr1[1] = 2;
        arr1[2] = 3;
        arr1[3] = 5;
        arr1[4] = 6;
        arr1[5] = 7;

        int i = Array.IndexOf(arr1, 3 );
        Console.WriteLine(“The value is”+i);
        
        Console.ReadLine();
    }
}

 

The output for the code is as shown below:

Like us on Facebook