csharp

C# Multidimensional Array and Jagged Array with examples

Description:

C# Multidimensional Array and jagged array with examples: this is a very detailed article about multidimensional or 2d array in c#, in this article you will learn how an array is defined, initialized, and accessing the array elements with full programming examples.



C# Multidimensional array:

Before you read any further, we need to do some terminology work again. Because while in many other programming languages ​​multidimensional arrays are to be equated with arrays of arrays, C# draws a dividing line here:

  • Multidimensional arrays are C# arrays, the elements of which are logically divided into several dimensions are.
  • Arrays of arrays or jagged arrays are C# arrays, the elements of which are physically divided into multiple arrays.

This distinction has consequences for programming. There are different forms of syntax for declaration, initialization, and element access. And while you have the elements of one to iterate through multidimensional arrays with a single for or foreach loop, you must for an array of arrays, iterate through the child arrays one at a time (i.e. you have to for loops nest). For this, arrays of arrays are more flexible. Because while e.g. a two-dimensional array always consists of exactly x * y elements (where x and y are dimensions), an array of Arrays consist of x arrays with y1, y2 … yx elements (see Figure 1).

C# multidC# multidimensional arrayimensional array
Figure 1


C# Multidimensional Array Definition:

To define a C# multidimensional array, enter the sizes of the individual dimensions Commas separated one after the other in the square array brackets.

int [,] table = new int [5,3];

For example, the above definition creates a two-dimensional array of 5 by 3 numbers. If they imagine the array as a table, it would consist of 5 rows (first dimension) and 3 columns (second Dimension) exist. Just as you define the array, you access its elements:

table [4, 1] = 12;

The second element in the fifth line is accessed here.


C# Multidimensional Array initialization:

C# Multidimensional array can also be initialized using lists. You have to do this for each Array dimension create your own list and the lists in the order of the associated array Nest dimensions within each other. The dimension on the far left stands for the outermost one Nesting.

// two-dimensional array

// The 1st dimension comprises the three lists {11, 12}, {21, 22} and {31, 32}

// The 2nd dimension comprises two int values ​​each

int [,] twoDim = new int [3,2]

{

{11, 12},

{21, 22},

{31, 32}

};

// three-dimensional array

int [,,] threeDim = new int [2,3,4]

{

{{111,112,113,114}, {121,122,123,124}, {131,132,133,134}},

{{211,212,213,214}, {221,222,223,224}, {231,232,233,234}}

};

// The same array in a different formatting showing the levels of nesting

// can be seen more clearly

int [,,] threeDim = new int [2,3,4]

{

{

{111,112,113,114},

{121,122,123,124},

{131,132,133,134}

},

{

{211,212,213,214},

{221,222,223,224},

{231,232,233,234}

}

};


C# Multidimensional Array Rank Property:

One-dimensional arrays (and in the sense of C# this also includes the arrays of arrays) always have rank 1. In the case of c# multidimensional array, the rank indicates the number of dimensions and is equal to that number of dimensions in the declaration.

The array

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo
{
    class Program
    {

        static void Main()
        {
            int[, ,] demo = new int[2, 3, 4]
                {
                   {{1,2,3,4}, {9,10,11,12}, {17,18,19,20}},
                    {{5,6,7,8}, {13,14,15,16}, {21,22,23,24}}

                };

            Console.WriteLine("Rank:" + demo.Rank);
            Console.ReadKey();

        }

    }
}

thus has rank 3. You can query the rank from the Rank property:

C# multidimensional array

The length of an array is equal to the number of elements in the array. In C# you can get the length of the property Query length. For C# multidimensional array, Length returns the total number of all elements in the array back (ultimately the product of the dimensions):

Console.WriteLine (demo.Length); // output 24 (equal to 2 * 3 * 4)

If you are interested in the length of individual dimensions of a C# multidimensional array, use Use the GetLength() method and pass it the zero-based index of the desired dimension:

Console.WriteLine ("Length of the 1st dimension:" + demo.GetLength (0)); // output 2

Console.WriteLine ("Length of the 2nd dimension:" + demo.GetLength (1)); // output 3

Console.WriteLine ("Length of the 3rd dimension:" + demo.GetLength (2)); // output 4

You can loop through multidimensional arrays like one-dimensional arrays:

foreach (int e in threeDim)

{

Console.Write (e + "");

}


or, if necessary, run through dimension by dimension:

for (int d1 = 0; d1 <threeDim.GetLength (0); ++ d1)

{

for (int d2 = 0; d2 <threeDim.GetLength (1); ++ d2)

{

Console.Write ("(");

for (int d3 = 0; d3 <threeDim.GetLength (2); ++ d3)

{

Console.Write (threeDim [d1, d2, d3] + "");

}

Console.Write (")");

}

Console.WriteLine ();

}

C# Multidimensional arrays store the values ​​stored in them just like one-dimensional arrays as a linear sequence but have the advantage that they impose a logical order on it. It sounds maybe a little complicated, but it is nothing more than the implementation of one frequently in everyday life used principle. Imagine the seats in the stalls of a theater or cinema (see Figure 2). Imagine 200 seats, distributed in 10 rows of 20 seats each.

C# multidimensional array
Figure 2

Your task should be to manage the occupancy of these seats with a program. It makes sense to manage the places in the form of an array:

bool [] seats = new bool [200];

However, this approach is unsuitable in that the natural arrangement of the seats in 10 rows of each 20 places in the flat, one-dimensional array is lost. You notice this, for example, when someone books the 11th place in the 3rd row and they want to set this element in the array to true (where true stands for “occupied”). It is more clever to create a suitable two-dimensional array.

bool [,] seats = new bool [10.20];



C# Jagged Array or Arrays of arrays:

Jagged Array or Arrays of arrays are one-dimensional arrays, the elements of which are in turn arrays.

definition of Jagged Array:

int [] [] jaggedArray = new int [2] [];

The above definition creates an array that contains two int arrays as elements. Note that the sub-array has no dimension set. This only happens when the sub-arrays are created:

jaggedArray [0] = new int [2] {1, 2};

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

Just as you define the array, you access its elements:

jaggedArray [1] [3] = 12;

The fourth element in the second sub-array is accessed here.

C# Jagged Array initialization:

Jagged Array or Arrays of arrays can also be initialized using lists. You have to do this for each sub-array create a new object and initialize it with its own list :.

int [] [] jaggedArray = new int [2] [] {

new int [] {1, 2, 3},

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

};


Array of Array or Jagged Array Rank Property:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo
{
    class Program
    {

        static void Main()
        {
            int[][] jaggedArray = new int[2][] {
                new int [] {1, 2, 3},
                new int [] {1, 2, 3, 4, 5}
                    };


            Console.WriteLine("Rank:" + jaggedArray.Rank);
            Console.ReadKey();

        }

    }
}

Arrays of arrays or Jagged Array always have rank 1. You can get the rank from the Rank property:

C# multidimensional array

The length is equal to the number of sub-arrays in the array. It is returned by the Length property.

Console.WriteLine (jaggedArray.Length); // output 2

To loop through all the elements of an array of arrays, you need to nest as many loops inside each other as to how there are nested arrays:

foreach (int [] sub in jaggedArray)

{

foreach (int e in sub)

{

Console.Write (e + "");

}

Console.WriteLine ();

}

The following example demonstrates how to use an array of arrays or jagged array to create an irregular two-dimensional Can represent data structure. The starting point is a theater parquet, similar to the parquet from the previous section, only that it is there are only 18 seats in the third and fourth rows (see Figure 3).

C# multidimensional array
Figure 3


Example: how to write a program, which reserved seat using jagged array concept:

The program represents this parquet as an array with 10 sub-arrays. The 11th seat in the third Row is marked as reserved.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo
{
    class Program
    {

        static void Main()
        {
            bool[][] seats = new bool[10][];
            for (int row = 1; row <= seats.Length; ++row)
            {
                if (row < 3 || row > 4)
                    seats[row - 1] = new bool[20];
                else
                    seats[row - 1] = new bool[18];
            }
            seats[2][10] = true;
            for (int row = 1; row <= seats.Length; ++row)
            {
                if (row == 3 || row == 4)
                    Console.Write(" ");
                for (int seat = 1; seat <= seats[row - 1].Length; ++seat)
                {
                    if (seats[row - 1][seat - 1] == false)
                        Console.Write("a ");
                    else
                        Console.Write("r ");
                }
                Console.WriteLine();
                Console.ReadKey();
            }



        }

    }

}

output:

C# multidimensional array



C# Multidimensional Array Programming Examples:

Example: how to use simple for and foreach loop in c# multidimensional array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo
{
    class Program
    {

        static void Main()
        {
            string[,] arr = new string[2, 3];

            for (int row = 0; row < 2; row++)
                for (int col = 0; col < 3; col++)
                    arr[row, col] = string.Format("{0}/{1}", row + 1, col + 1);


            foreach (string s in arr)
                Console.WriteLine(s);
            Console.ReadKey();

        }

    }
}

Output:

C# multidimensional array


Example: how to find maximum and minimum value in C# multidimensional array:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace demo
{
    class Program
    {

        static void Main()
        {
            const int x = 3, y = 5;
            int min, max;
            int[,] arr = new int[x, y] { { 11, 50, 79, 20, 19 }, 
            { 1, 56, 78, 97, 66 },
            { 79, 54, 22, 33, 6 } };

            
            min = arr[0, 0];
            max = arr[0, 0];

            
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    
                    if (arr[i, j] > max)
                    {
                        max = arr[i, j];
                    }

                    
                    if (arr[i, j] < min)
                    {
                        min = arr[i, j];
                    }

                }

            }

           
            Console.Write("Array Elements\n");
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < y; j++)
                {
                    Console.Write(arr[i, j] + " ,");
                }
                Console.WriteLine();
            }
            Console.WriteLine();

            
            Console.WriteLine("Maximum Value :" + max);
            Console.WriteLine("Minimum  Value:" + min); ;
            Console.ReadKey();

        }

    }
}

Output:

C# multidimensional array

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button