Quiz: Access the first element of a multidimensional array

Here is a quiz for you:

Create a method for printing the first element in a multidimensional array without knowing the number of dimensions (rank) of the array.

Explanation

In C# there one has the possibility of defining different types of arrays:

    • Single-Dimensional Arrays
int[] array1 = new int[10];
int[] array2 = new[] {1, 2, 3};
int[] array3 = {1, 2};
    • Multidimensional Arrays
int[,,] array1 = new int[2, 2, 3];
int[,] array2 = new int[,] 
{
    {1, 2, 3},
    {4, 5, 6},
};
int[,] array3 =
{
    {1, 2, 3},
    {4, 5, 6},
};
    • Jagged Arrays
int[][] array1 = new int[2][];
int[][] array2 = new []
{
    new [] {1, 2},
    new [] {3, 4, 5}
};

int[][] array3 =
{
    new [] {1, 2},
    new [] {3, 4, 5}
};

The base class for arrays in CLR is Array class. The Array class provides methods for creating, manipulating, searching and sorting arrays.

In order to solve the quiz we will use the Array class. Below there is a an example in which we print the first element of multidimensional array-s without knowing the number of dimensions (the rank) of the array-s:

class Program
{
    static void Main(string[] args)
    {
        int[,] array1 =
        {
            {1, 2, 3},
            {4, 5, 6},
        };

        int[,,] array2 =
        {
            {
                {8}, 
                {9}
            }
        };

        PrintFirst(array1); // Prints 1
        PrintFirst(array2); // Prints 8
    }

    static void PrintFirst(Array array)
    {
        // Create an array of indices initialized by default to 0
        var indices = new int[array.Rank]; 

        // Get the value of for first cell of the array
        var firstValue = array.GetValue(indices);

        Console.WriteLine(firstValue);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s