Home

Multidimensional Arrays

   

Fundamentals of Multidimensional Arrays

 

Introduction

The arrays we used so far were made of a uniform series, where all members consisted of a simple list, like a column of names on a piece of paper. Also, all items fit in one list. This type of array is referred to as one-dimensional.

In some cases, you may want to divide the list in delimited sections. For example, if you create a list of names, you may want part of the list to include family members and another part of the list to include friends. Instead of creating a second list, you can add a second dimension to the list. In other words, you would create a list of a list, or one list inside of another list, although the list is still made of items with common characteristics.

A multidimensional array is a series of arrays so that each array contains its own sub-array(s).

ApplicationApplication: Introducing Multidimensional Arrays

  1. Launch your programming environment
  2. To create a new application, on the main menu, click File -> New Project...
  3. In the middle list, click Console Application
  4. Change the Name to DepartmentStore3
  5. Click OK
  6. In the Solution Explorer, right-click Program.cs and click Rename
  7. Type DepartmentStore.cs and press Enter
  8. Change the DepartmentStore.cs file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DepartmentStore3
    {
        public class DepartmentStore
        {
            public static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                double Price = 0.00D;
    
                Console.Title = "Fun Department Store";
    
                Console.WriteLine("==============================");
                Console.WriteLine("Fun Department Store");
                Console.WriteLine("==============================");
                Console.WriteLine("Receipt");
                Console.WriteLine("------------------------------");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}", Price);
                Console.WriteLine("==============================");
    
                Console.ReadKey();
                return 0;
            }
        }
    }
  9. To execute the application to see the result, press F5. This would produce:
    ==============================
    Fun Department Store
    ==============================
    Receipt
    ------------------------------
    Item Number: 0
    Description: Unknown
    Unit Price:  $0.00
    ==============================
  10. Press Enter to close the DOS window and return to your programming environment

Creating a Two-Dimensional Array

The most basic multidimensional array is made of two dimensions. This is referred to as two-dimensional.  To create a two-dimensional array, declare the array variable as we have done so far but add a comma in the square brackets. The formula you would use is:

DataType[,] VariableName;

The pair of brackets is empty but must contain a comma. There are various ways you can initialize a two-dimensional array. If you are declaring the array variable but are not ready to initialize it, use the following formula:

DataType[,] VariableName = new DataType[Number1,Number2];

Or you can use the var keyword:

var VariableName = new DataType[Number1,Number2];

Either way, in the right pair of square brackets, enter two integers separated by a comma. Here is an example:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        var members = new string[2, 4];

        return 0;
    }
}

In our declaration, the members variable contains two lists. Each of the two lists contains 4 elements. This means that the first list contains 4 elements and the second list contains 4 elements. Therefore, the whole list is made of 8  elements (2 * 4 = 8). Because the variable is declared as a string, each of the 8 items must be a string.

You can also create a two-dimensional array that takes more than two lists, such as 3, 4, 5 or more. Here is an example:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        var Prices = new double[5, 8];

        return 0;
    }
}

This time, the variable has 5 lists and each list contains 8 elements. This means that the whole variable contains 5 * 8 = 40 elements.

If you want to declare the array variable using the first formula where you don't know the sizes of the lists, you must use the data type of the array and you can omit the right square brackets. Here is an example:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        string[,] members;

        return 0;
    }
}

In this case also, remember that you need the square brackets. If you use the var keyword, you don't need the left square brackets but, in the right square brackets, you must specify the sizes.

You can initialize an array variable when declaring it. To do this, on the right side of the declaration, before the closing semi-colon, type an opening and a closing curly brackets. Inside of the brackets, include a pair of an opening and a closing curly brackets for each internal list of the array. Then, inside of a pair of curly brackets, provide a list of the values of the internal array, just as you would do for a one-dimensional array. Here is an example:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        var members = new string[2, 4]
        {
            {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
	    {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
        };

        return 0;
    }
}

When initializing a two-dimensional array, remember the dimensions. The number on the left side of the right comma specifies the number of main lists and the number on the right side of the right comma specifies the number of elements in each list. Here is an example:

using System;

public static class Exercise
{
    public static int Main(string[] args)
    {
        var Prices = new double[5, 8]
        {
            { 10.50, 2.35, 49.75, 202.35, 8.70, 58.20, 34.85, 48.50 },
            { 23.45, 878.50, 26.35, 475.90, 2783.45, 9.50, 85.85, 792.75 },
            { 47.95, 72.80, 34.95, 752.30, 49.85, 938.70, 45.05, 9.80 },
            { 759.25, 73.45, 284.35, 70.95, 82.05, 34.85, 102.30, 84.50 },
            { 29.75, 953.45, 79.55, 273.45, 975.90, 224.75, 108.25, 34.05 }
        };

        return 0;
    }
}

If you use this technique to initialize an array, you can omit specifying the dimension of the array. That is, you can remove the numbers in the right square brackets. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var members = new string[,]
        {
            {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
	    {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
        };

        return 0;
    }
}

ApplicationApplication: Creating a Two-Dimensional Array

  • To create and use a two-dimensional array, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DepartmentStore3
    {
        public class DepartmentStore
        {
            public static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                double Price = 0.00D;
    
                // The first list contains women's items
                // The other contains non-women items
                long[,] ItemNumber = new long[2, 5]
                {
                    { 947783, 934687, 973947, 987598, 974937 },
                    { 739579, 367583, 743937, 437657, 467945 } };
    
                string[,] ItemName = new string[2, 5]
                {
                    { "Women Double-faced wool coat",
    		          "Women Floral Silk Tank Blouse",
    		          "Women Push Up Bra",
    		          "Women Chiffon Blouse",
    		          "Women Bow Belt Skirtsuit"
    		        },
                    { "Chaco Leather Slide-On Sandal",
    		          "Children Cable-knit Sweater  ",
                      "Children Bear Coverall Cotton",
    		          "Baby three-piece Set         ",
    		          "Girls Jeans with Heart Belt  "
                    }
                };
    
                double[,] UnitPrice = new double[2, 5]
    	    {
                    { 98.75D, 180.05D, 50.00D, 265.35D, 245.55D },
    	        { 45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
    	    };
    
                Console.Title = "Fun Department Store";
    
                Console.WriteLine("==============================");
                Console.WriteLine("Fun Department Store");
                Console.WriteLine("==============================");
                Console.WriteLine("Receipt");
                Console.WriteLine("------------------------------");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}", Price);
                Console.WriteLine("==============================");
    
                Console.ReadKey();
                return 0;
            }
        }
    }

Accessing the Members of a Two-Dimensional Array

To use the members of a two-dimensional array, you can access each item individually. For example, to initialize a two-dimensional array, you can access each member of the array and assign it a value. The external list is zero-based. In other words, the first list has an index of 0, the second list has an index of 1. Internally, each list is zero-based and behaves exactly like a one-dimensional array. To access a member of the list, type the name of the variable followed by its square brackets. In the brackets, type the index of the list, a comma, and the internal index of the member whose access you need. If you create an array without initializing using the curly brackets, you can use this technique of accessing the members by the square brackets to initialize each member of the array. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var members = new string[2,4];

        members[0, 0] = "Celeste";    // Member of the First List
        members[0, 1] = "Mathurin";   // Member of the First List
        members[0, 2] = "Alex";       // Member of the First List
        members[0, 3] = "Germain";    // Member of the First List
        members[1, 0] = "Jeremy";     // Member of the Second List
        members[1, 1] = "Mathew";     // Member of the Second List
        members[1, 2] = "Anselme";    // Member of the Second List
        members[1, 3] = "Frederique"; // Member of the Second List

        return 0;
    }
}

You can use this same technique to retrieve the value of each member of the array. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var members = new string[2,4];

        members[0, 0] = "Celeste";    // Member of the First List
        members[0, 1] = "Mathurin";   // Member of the First List
        members[0, 2] = "Alex";       // Member of the First List
        members[0, 3] = "Germain";    // Member of the First List
        members[1, 0] = "Jeremy";     // Member of the Second List
        members[1, 1] = "Mathew";     // Member of the Second List
        members[1, 2] = "Anselme";    // Member of the Second List
        members[1, 3] = "Frederique"; // Member of the Second List

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

        return 0;
    }
}

This would produce:

Celeste
Mathurin
Alex
Germain
Jeremy
Mathew
Anselme
Frederique
Press any key to continue . . .

As we described it earlier, a two-dimensional array is a list of two arrays, or two arrays of arrays. In other words, the second arrays are nested in the first arrays. In the same way, if you want to access them using a loop, you can nest one for loop inside of a first for loop. The external loop accesses a member of the main array and the second loop accesses the internal list of the current array. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var members = new string[2,4];

        members[0, 0] = "Celeste";    // Member of the First List
        members[0, 1] = "Mathurin";   // Member of the First List
        members[0, 2] = "Alex";       // Member of the First List
        members[0, 3] = "Germain";    // Member of the First List
        members[1, 0] = "Jeremy";     // Member of the Second List
        members[1, 1] = "Mathew";     // Member of the Second List
        members[1, 2] = "Anselme";    // Member of the Second List
        members[1, 3] = "Frederique"; // Member of the Second List

        for (int External = 0; External < 2; External++)
            for (int Internal = 0; Internal < 4; Internal++)
                Console.WriteLine(members[External, Internal]);

        return 0;
    }
}

To apply a foreach operator, access only each member of the internal list. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var members = new string[2, 4];

        members[0, 0] = "Celeste";    // Member of the First List
        members[0, 1] = "Mathurin";   // Member of the First List
        members[0, 2] = "Alex";       // Member of the First List
        members[0, 3] = "Germain";    // Member of the First List
        members[1, 0] = "Jeremy";     // Member of the Second List
        members[1, 1] = "Mathew";     // Member of the Second List
        members[1, 2] = "Anselme";    // Member of the Second List
        members[1, 3] = "Frederique"; // Member of the Second List

        foreach (var Internal in members)
            Console.WriteLine(Internal);

        return 0;
    }
}

ApplicationApplication: Accessing the Members

  1. To retrieve the values of a two-dimensional array, change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DepartmentStore3
    {
        public class DepartmentStore
        {
            public static int Main(string[] args)
            {
                long ItemID = 0;
                string Description = "Unknown";
                double Price = 0.00D;
    
                // The first list contains women's items
                // The other contains non-women items
                long[,] ItemNumber = new long[2, 5]
                {
                    { 947783, 934687, 973947, 987598, 974937 },
                    { 739579, 367583, 743937, 437657, 467945 } };
    
                string[,] ItemName = new string[2, 5]
                {
                    { "Women Double-faced wool coat",
    		          "Women Floral Silk Tank Blouse",
    		          "Women Push Up Bra",
    		          "Women Chiffon Blouse",
    		          "Women Bow Belt Skirtsuit"
    		        },
                    { "Chaco Leather Slide-On Sandal",
    		          "Children Cable-knit Sweater  ",
                      "Children Bear Coverall Cotton",
    		          "Baby three-piece Set         ",
    		          "Girls Jeans with Heart Belt  "
                    }
                };
    
                double[,] UnitPrice = new double[2, 5]
    	    {
                    { 98.75D, 180.05D, 50.00D, 265.35D, 245.55D },
    	        {  45.55D,  25.65D, 28.25D,  48.55D,  19.95D }
    	    };
    
                // Order Processing
                try
                {
                    Console.Write("Enter Item Number: ");
                    ItemID = long.Parse(Console.ReadLine());
                }
                catch (FormatException)
                {
                    Console.WriteLine("Invalid Number - The program will terminate\n");
                }
    
                for (int i = 0; i < 2; i++)
                {
                    for (int j = 0; j < 5; j++)
                    {
                        if (ItemID == ItemNumber[i, j])
                        {
                            Description = ItemName[i, j];
                            Price = UnitPrice[i, j];
                        }
                    }
                }
    
                Console.Title = "Fun Department Store";
    
                Console.Clear();
    
                Console.WriteLine("==============================");
                Console.WriteLine("Fun Department Store");
                Console.WriteLine("==============================");
                Console.WriteLine("Receipt");
                Console.WriteLine("------------------------------");
                Console.WriteLine("Item Number: {0}", ItemID);
                Console.WriteLine("Description: {0}", Description);
                Console.WriteLine("Unit Price:  {0:C}", Price);
                Console.WriteLine("==============================");
    
                Console.ReadKey();
                return 0;
            }
        }
    }
  2. To execute the application and test it, press F5
  3. Type the Item Number as 739579 and press Enter:
     
    ==============================
    Fun Department Store
    ==============================
    Receipt
    ------------------------------
    Item Number: 739579
    Description: Chaco Leather Slide-On Sandal
    Unit Price:  $45.55
    ==============================
     
    Chaco Leather Slide-On Sandal
  4. Press Enter to close the DOS window and return to your programming environment
  5. To execute the application again, press F5
  6. Type a different item number, such as 273644, and press Enter
    ==============================
    Fun Department Store
    ==============================
    Receipt
    ------------------------------
    Item Number: 273644
    Description: Unknown
    Unit Price:  $0.00
    ==============================
  7. Press Enter to close the DOS window and return to your programming environment

Creating and Using a Multidimensional Array

 

Introduction

Beyond two dimensions, you can create an array variable that represents various lists, and each list contains various internal lists, and each internal list contains its own elements. This is referred to as a multidimensional array. One of the rules you must follow is that, as always, all members of the array must be of the same type.

Creating a Multidimensional Array

To create a multidimensional array, add as many commas in the square brackets as you judge them necessary. If you only want to declare the variable without indicating the actual number of lists, you can specify the data type followed by square brackets and the commas. Here is an example that represents a three-dimensional array that is not initialized:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        double[,,] Number;

        return 0;
    }
}

If you know the types of members the array will use, you can use the assignment operator and specify the numbers of lists in the square brackets. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        double[,,] Number = new double[2, 3, 5];

        return 0;
    }
}

In this case, you can use the var keyword on the left side of the name of the variable:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Number = new double[2, 3, 5];

        return 0;
    }
}

In this example, we are creating 2 groups of items. Each of the two groups is made of three lists. Each list contains 5 numbers. As a result, the array contains 2 * 3 * 5 = 30 members.

Initializing a Multidimensional Array

As always, there are various ways you can initialize an array. To initialize a multidimensional array when creating it, you use an opening and a closing curly brackets for each list but they must be nested. The most external pair of curly brackets represents the main array. Inside of the main curly brackets, the first nested curly brackets represent a list of the first dimension. Inside of those brackets, you use another set curly brackets to represent a list that would be nested. You continue this up to the most internal array. Then, in that last set, you initialize the members of the array by specifying their values. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Number = new double[2, 3, 5]
	{
            {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
                {-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
		{  48.02, 120.44,   38.62,  526.82, 1704.62 },
		{  56.85, 105.48,  363.31,  172.62,  128.48 },
		{  906.68, 47.12, -166.07, 4444.26,  408.62 }
	    },
	};

        return 0;
    }
}

Access to Members of a Multidimensional Array

To access a member of a multidimensional array, type the name of the array followed by the opening square bracket, followed by the 0-based first dimension, followed by a comma. Continue with each dimension and end with the closing square bracket. You can use this technique to initialize the array if you had only created it. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Number = new double[2, 3, 5];
        
        Number[0, 0, 0] = 12.44;
        Number[0, 0, 1] = 525.38;
        Number[0, 0, 2] = -6.28;
        Number[0, 0, 3] = 2448.32;
        Number[0, 0, 4] = 632.04;
        Number[0, 1, 0] = -378.05;
        Number[0, 1, 1] = 48.14;
        Number[0, 1, 2] = 634.18;
        Number[0, 1, 3] = 762.48;
        Number[0, 1, 4] = 83.02;
        Number[0, 2, 0] = 64.92;
        Number[0, 2, 1] = -7.44;
        Number[0, 2, 2] = 86.74;
        Number[0, 2, 3] = -534.60;
        Number[0, 2, 4] = 386.73;
        Number[1, 0, 0] = 48.02;
        Number[1, 0, 1] = 120.44;
        Number[1, 0, 2] = 38.62;
        Number[1, 0, 3] = 526.82;
        Number[1, 0, 4] = 1704.62;
        Number[1, 1, 0] = 56.85;
        Number[1, 1, 1] = 105.48;
        Number[1, 1, 2] = 363.31;
        Number[1, 1, 3] = 172.62;
        Number[1, 1, 4] = 128.48;
        Number[1, 2, 0] = 906.68;
        Number[1, 2, 1] = 47.12;
        Number[1, 2, 2] = -166.07;
        Number[1, 2, 3] = 4444.26;
        Number[1, 2, 4] = 408.62;

        return 0;
    }
}

This is the same approach you can use to access each member of the array to check or retrieve its value. Here are examples:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        double[, ,] number = new double[2, 3, 5]
	{
	    {
		{  12.44, 525.38,  -6.28,  2448.32, 632.04 },
                {-378.05,  48.14, 634.18,   762.48,  83.02 },
		{  64.92,  -7.44,  86.74,  -534.60, 386.73 }
	    },
	    {
	        {  48.02, 120.44,  38.62,   526.82,1704.62 },
		{  56.85, 105.48, 363.31,  172.62,  128.48 },
	        {  906.68, 47.12,-166.07,  4444.26, 408.62 }
	    },
	};

        Console.WriteLine("Number[0][0][0] = {0}", number[0, 0, 0]);
        Console.WriteLine("Number[0][0][1] = {0}", number[0, 0, 1]);
        Console.WriteLine("Number[0][0][2] = {0}", number[0, 0, 2]);
        Console.WriteLine("Number[0][0][3] = {0}", number[0, 0, 3]);
        Console.WriteLine("Number[0][0][4] = {0}\n", number[0, 0, 4]);

        Console.WriteLine("Number[0][1][0] = {0}", number[0, 1, 0]);
        Console.WriteLine("Number[0][1][1] = {0}", number[0, 1, 1]);
        Console.WriteLine("Number[0][1][2] = {0}", number[0, 1, 2]);
        Console.WriteLine("Number[0][1][3] = {0}", number[0, 1, 3]);
        Console.WriteLine("Number[0][1][4] = {0}\n", number[0, 1, 4]);

        Console.WriteLine("Number[0][2][0] = {0}", number[0, 2, 0]);
        Console.WriteLine("Number[0][2][1] = {0}", number[0, 2, 1]);
        Console.WriteLine("Number[0][2][2] = {0}", number[0, 2, 2]);
        Console.WriteLine("Number[0][2][3] = {0}", number[0, 2, 3]);
        Console.WriteLine("Number[0][2][4] = {0}\n", number[0, 2, 4]);

        Console.WriteLine("Number[1][0][0] = {0}", number[1, 0, 0]);
        Console.WriteLine("Number[1][0][1] = {0}", number[1, 0, 1]);
        Console.WriteLine("Number[1][0][2] = {0}", number[1, 0, 2]);
        Console.WriteLine("Number[1][0][3] = {0}", number[1, 0, 3]);
        Console.WriteLine("Number[1][0][4] = {0}\n", number[1, 0, 4]);

        Console.WriteLine("Number[1][1][0] = {0}", number[1, 1, 0]);
        Console.WriteLine("Number[1][1][1] = {0}", number[1, 1, 1]);
        Console.WriteLine("Number[1][1][2] = {0}", number[1, 1, 2]);
        Console.WriteLine("Number[1][1][3] = {0}", number[1, 1, 3]);
        Console.WriteLine("Number[1][1][4] = {0}\n", number[1, 1, 4]);

        Console.WriteLine("Number[1][2][0] = {0}", number[1, 2, 0]);
        Console.WriteLine("Number[1][2][1] = {0}", number[1, 2, 1]);
        Console.WriteLine("Number[1][2][2] = {0}", number[1, 2, 2]);
        Console.WriteLine("Number[1][2][3] = {0}", number[1, 2, 3]);
        Console.WriteLine("Number[1][2][4] = {0}\n", number[1, 2, 4]);
        
        return 0;
    }
}

This would produce:

Number[0][0][0] = 12.44
Number[0][0][1] = 525.38
Number[0][0][2] = -6.28
Number[0][0][3] = 2448.32
Number[0][0][4] = 632.04

Number[0][1][0] = -378.05
Number[0][1][1] = 48.14
Number[0][1][2] = 634.18
Number[0][1][3] = 762.48
Number[0][1][4] = 83.02

Number[0][2][0] = 64.92
Number[0][2][1] = -7.44
Number[0][2][2] = 86.74
Number[0][2][3] = -534.6
Number[0][2][4] = 386.73

Number[1][0][0] = 48.02
Number[1][0][1] = 120.44
Number[1][0][2] = 38.62
Number[1][0][3] = 526.82
Number[1][0][4] = 1704.62

Number[1][1][0] = 56.85
Number[1][1][1] = 105.48
Number[1][1][2] = 363.31
Number[1][1][3] = 172.62
Number[1][1][4] = 128.48

Number[1][2][0] = 906.68
Number[1][2][1] = 47.12
Number[1][2][2] = -166.07
Number[1][2][3] = 4444.26
Number[1][2][4] = 408.62

Press any key to continue . . .

Since the lists are nested, if you want to use loops to access the members of the array, you can nest the for loops to incrementally access the values. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Number = new double[2, 3, 5];
        
        Number[0, 0, 0] = 12.44;
        Number[0, 0, 1] = 525.38;
        Number[0, 0, 2] = -6.28;
        Number[0, 0, 3] = 2448.32;
        Number[0, 0, 4] = 632.04;
        Number[0, 1, 0] = -378.05;
        Number[0, 1, 1] = 48.14;
        Number[0, 1, 2] = 634.18;
        Number[0, 1, 3] = 762.48;
        Number[0, 1, 4] = 83.02;
        Number[0, 2, 0] = 64.92;
        Number[0, 2, 1] = -7.44;
        Number[0, 2, 2] = 86.74;
        Number[0, 2, 3] = -534.60;
        Number[0, 2, 4] = 386.73;
        Number[1, 0, 0] = 48.02;
        Number[1, 0, 1] = 120.44;
        Number[1, 0, 2] = 38.62;
        Number[1, 0, 3] = 526.82;
        Number[1, 0, 4] = 1704.62;
        Number[1, 1, 0] = 56.85;
        Number[1, 1, 1] = 105.48;
        Number[1, 1, 2] = 363.31;
        Number[1, 1, 3] = 172.62;
        Number[1, 1, 4] = 128.48;
        Number[1, 2, 0] = 906.68;
        Number[1, 2, 1] = 47.12;
        Number[1, 2, 2] = -166.07;
        Number[1, 2, 3] = 4444.26;
        Number[1, 2, 4] = 408.62;

        for(int Outside = 0; Outside < 2; Outside++)
            for(int Inside = 0; Inside < 3; Inside++)
                for(int Value = 0; Value < 5; Value++)
        	    Console.WriteLine("Number = {0}",
			Number[Outside, Inside, Value]);

        return 0;
    }
}

This would produce:

Number = 12.44
Number = 525.38
Number = -6.28
Number = 2448.32
Number = 632.04
Number = -378.05
Number = 48.14
Number = 634.18
Number = 762.48
Number = 83.02
Number = 64.92
Number = -7.44
Number = 86.74
Number = -534.6
Number = 386.73
Number = 48.02
Number = 120.44
Number = 38.62
Number = 526.82
Number = 1704.62
Number = 56.85
Number = 105.48
Number = 363.31
Number = 172.62
Number = 128.48
Number = 906.68
Number = 47.12
Number = -166.07
Number = 4444.26
Number = 408.62
Press any key to continue . . .

To make the result easier to read, we could use code as follows:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Number = new double[2, 3, 5];
        
        . . . No Change

        for(int Outside = 0; Outside < 2; Outside++)
            for(int Inside = 0; Inside < 3; Inside++)
                for (int Value = 0; Value < 5; Value++)
                {
                    Console.WriteLine("Number[{0}][{1}][{2}] = {3}",
                        Outside, Inside, Value, Number[Outside, Inside, Value]);

                    if (Value % 5 == 0)
                        Console.WriteLine();
                }
        
        return 0;
    }
}

To use a foreach operator, access only each member to get to it. Here is an example:

using System;

public static class Exercise
{
    static int Main(string[] args)
    {
        var Numbers = new double[2, 3, 5];
        
        . . . No Change

        foreach (var Value in Numbers)
            Console.WriteLine("Number: {0}", Value);

        return 0;
    }
}

Multidimensional Arrays and Classes

 

Introduction

Like an array of a primitive type, a multidimensional array can be made a field of a class. You can primarily declare it without initializing it. Here is an example:

public class TriangleInCoordinateSystem
{
    private int[,] Points;
}

This indicates a two-dimensional array field: the array will contain two lists but we don't know (yet) how many members each array will contain. Therefore, if you want, when creating the array, you can specify its dimension by assigning it a second pair of square brackets using the new operator and the data type. Here is an example:

public class TriangleInCoordinateSystem
{
    private int[,] Points = new int[3, 2];
}

You can also use a method of the class or a constructor to indicate the size of the array. Here is an example:

public class TriangleInCoordinateSystem
{
    private int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];
    }
}

To initialize the array, you can access each member using the square brackets as we saw in the previous sections. Here is an example:

public class TriangleInCoordinateSystem
{
    private int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];

        Points[0, 0] = -2; // A(x, )
        Points[0, 1] = -3; // A( , y)
        Points[1, 0] =  5; // B(x, )
        Points[1, 1] =  1; // B( , y)
        Points[2, 0] =  4; // C(x, )
        Points[2, 1] = -2; // C( , y)
    }
}

After initializing the array, you can use it as you see fit. For example, you can display its values to the user. Here is an example:

using System;

public class TriangleInCoordinateSystem
{
    private int[,] Points;

    public TriangleInCoordinateSystem()
    {
        Points = new int[3, 2];

        Points[0, 0] = -2; // A(x, )
        Points[0, 1] = -3; // A( , y)
        Points[1, 0] =  5; // B(x, )
        Points[1, 1] =  1; // B( , y)
        Points[2, 0] =  4; // C(x, )
        Points[2, 1] = -2; // C( , y)
    }

    public void ShowPoints()
    {
        Console.WriteLine("Coordinates of the Triangle");
        Console.WriteLine("A({0}, {1})", Points[0, 0], Points[0, 1]);
        Console.WriteLine("B({0}, {1})", Points[1, 0], Points[1, 1]);
        Console.WriteLine("C({0}, {1})", Points[2, 0], Points[2, 1]);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        var Triangle = new TriangleInCoordinateSystem();

        Triangle.ShowPoints();

        return 0;
    }
}

This would produce:

Coordinates of the Triangle
A(-2, -3)
B(5, 1)
C(4, -2)
Press any key to continue . . .

A Multidimensional Array as Argument

A multidimensional array can be passed as argument. When creating the method, in its parentheses, enter the data type followed by the square brackets. In the square brackets, enter one comma for a two-dimensional array, two or more commas, as necessary, for a three-dimensional arrays as necessary. Here is an example:

public class TriangleInCoordinateSystem
{
    public void ShowPoints(int[,] Coords)
    {
    }
}

When defining the method, in its body, you can use the array as you see fit, such as displaying its values. Here is an example:

public class TriangleInCoordinateSystem
{
    public void ShowPoints(int[,] Coords)
    {
        Console.WriteLine("Coordinates of the Triangle");
        Console.WriteLine("A({0}, {1})", Coords[0, 0], Coords[0, 1]);
        Console.WriteLine("B({0}, {1})", Coords[1, 0], Coords[1, 1]);
        Console.WriteLine("C({0}, {1})", Coords[2, 0], Coords[2, 1]);
    }
}

To call this type of method, pass only the name of the array.

As indicated with one-dimensional arrays, when passing a multi-dimensional array as argument, the array is treated as a reference. This makes it possible for the method to modify the array and return it changed. If you want to indicate that the array is passed by reference, you can precede its name in the parentheses by the the ref keyword. Here is an example:

using System;

public class TriangleInCoordinateSystem
{
    private int[,] Points;

    public void CreateTriangle(ref int[,] Points)
    {

        Points[0, 0] = -2; // A(x, )
        Points[0, 1] = -3; // A( , y)
        Points[1, 0] =  5; // B(x, )
        Points[1, 1] =  1; // B( , y)
        Points[2, 0] =  4; // C(x, )
        Points[2, 1] = -2; // C( , y)
    }

    public void ShowPoints(int[,] Coords)
    {
        Console.WriteLine("Coordinates of the Triangle");
        Console.WriteLine("A({0}, {1})", Coords[0, 0], Coords[0, 1]);
        Console.WriteLine("B({0}, {1})", Coords[1, 0], Coords[1, 1]);
        Console.WriteLine("C({0}, {1})", Coords[2, 0], Coords[2, 1]);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        var Coordinates = new int[3, 2];

        var Triangle = new TriangleInCoordinateSystem();

        Triangle.CreateTriangle(ref Coordinates);
        Triangle.ShowPoints(Coordinates);

        return 0;
    }
}

Returning a Multi-Dimensional Array

You can return a multi-dimensional array from a method. When creating the method, before its name, specify the data type followed by square brackets. In the square brackets, enter the necessary number of commas. Here is an example:

using System;

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
    }
}

In the body of the method, you can do what you want but, before exiting it, you must return an array of the same type that was created. When calling the method, you can assign it to an array of the same type it returns. Here is an example:

using System;

public class TriangleInCoordinateSystem
{
    public int[,] CreateTriangle()
    {
        var Points = new int[3,2];
    
        Points[0, 0] = 6; // A(x, )
        Points[0, 1] = 1; // A( , y)
        Points[1, 0] = 2; // B(x, )
        Points[1, 1] = 3; // B( , y)
        Points[2, 0] = 1; // C(x, )
        Points[2, 1] = 4; // C( , y)

        return Points;
    }

    public void ShowPoints(int[,] Coords)
    {
        Console.WriteLine("Coordinates of the Triangle");
        Console.WriteLine("A({0}, {1})", Coords[0, 0], Coords[0, 1]);
        Console.WriteLine("B({0}, {1})", Coords[1, 0], Coords[1, 1]);
        Console.WriteLine("C({0}, {1})", Coords[2, 0], Coords[2, 1]);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        var Coordinates = new int[3, 2];

        var Triangle = new TriangleInCoordinateSystem();

        Coordinates = Triangle.CreateTriangle();
        Triangle.ShowPoints(Coordinates);

        return 0;
    }
}

This would produce:

Coordinates of the Triangle
A(6, 1)
B(2, 3)
C(1, 4)
Press any key to continue . . .

A Multidimensional Array of Objects

 

A Variable of a Multidimensional Array of Objects

As done for primitive data types, you can create a multi-dimensional array where each member is of a class type. Of course you can use an existing class or you must first create a class. Here is an example:

public class Point
{
    private int XCoord;
    private int YCoord;

    public int x
    {
        get { return XCoord; }
        set { XCoord = value; }
    }

    public int y
    {
        get { return YCoord; }
        set { YCoord = value; }
    }
}

To create a multidimensional array of objects without initializing it, you can use the following formula:

ClassName[,] VariableName;

If you know the number of instances of the class that the array will use, you can use the following formula:

ClassName[,] VariableName = new ClassName[Number1,Number2];

Or you can use the var or the dynamic keyword in the following formula:

var VariableName = new DataType[Number1,Number2];
dynamic VariableName = new DataType[Number1,Number2];

The ClassName factor is the name of the class that will make up each member of the array. The other sections follow the same rules we reviewed for the primitive types. For example, you can create an array without allocating memory for it as follows:

public static class Exercise
{
    static int Main(string[] args)
    {
        Point[,] Line;

        return 0;
    }
}

If you know the number of members that the array will contain, you can use the right pair of square brackets, in which case you can specify the name of the class or use the var keyword and omit the left square brackets. Here is an example:

public static class Exercise
{
    static int Main(string[] args)
    {
        var Line = new Point[2, 2];

        return 0;
    }
}

This declaration creates a two-dimensional array of two Point objects: The array contains two lists and each list contains two Points.

To initialize a multidimensional array of objects, you can access each array member using its index, allocate memory for it using the new operator. After allocating memory for the member, you can then access its fields or properties to initialize it. Here is an example:

using System;

public class Point
{
    private int XCoord;
    private int YCoord;

    public int x
    {
        get { return XCoord; }
        set { XCoord = value; }
    }

    public int y
    {
        get { return YCoord; }
        set { YCoord = value; }
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        var Line = new Point[2, 2];

        Line[0, 0] = new Point(); // First Point A
        Line[0, 0].x = -3;        // A(x,  )
        Line[0, 0].y =  8;        // A( , y)
        Line[0, 1] = new Point(); // Second Point B
        Line[0, 1].x =  4;        // B(x,  )
        Line[0, 1].y = -5;        // B( , y)

        return 0;
    }
}

You can also initialize the array when creating it. Before doing this, you would need a constructor of the class and the constructor must take the argument(s) that would be used to initialize each member of the array. To actually initialize the array, you would need a pair of external curly brackets for the main array. Inside of the external curly brackets, create a pair of curly brackets for each sub-dimension of the array. Inside the last curly brackets, use the new operator to access an instance of the class and call its constructor to specify the values of the instance of the class. Here is an example:

public class Point
{
    private int XCoord;
    private int YCoord;

    public Point()
    {
    }

    public Point(int X, int Y)
    {
        XCoord = X;
        YCoord = Y;
    }

    public int x
    {
        get { return XCoord; }
        set { XCoord = value; }
    }

    public int y
    {
        get { return YCoord; }
        set { YCoord = value; }
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        var Line = new Point[,]
        {
            {
                new Point(-3, 8),
		new Point(4, -5)
            }
        };

        return 0;
    }
}

Accessing the Members of a Multidimensional Array of Objects

To access the members of a multidimensional array of objects, apply the square brackets to a particular member of the array and access the desired field or property of the class. Here is an example:

public static class Exercise
{
    public static int Main(string[] args)
    {
        var Line = new Point[,]
        {
            {
                new Point(-3, 8),  new Point(4, -5)
            }
        };

        Console.WriteLine("Line =-=");
        Console.WriteLine("From A({0}, {1}) to B({2}, {3})",
                          Line[0, 0].x, Line[0, 0].y,
                          Line[0, 1].x, Line[0, 1].y);
        return 0;
    }
}

This would produce:

Line =-=
From A(-3, 8) to B(4, -5)
Press any key to continue . . .

You can also use a loop to access the members of the array. To do this, create a first for loop that stops at the first dimension of the array - 1. Then, inside of a first for loop, nest a for loop for each subsequent dimension. Here is an example:

public static class Exercise
{
    public static int Main(string[] args)
    {
        var Line = new Point[,]
        {
            {
                new Point(-3, 8),  new Point(4, -5)
            }
        };
 
        Console.WriteLine("The points of the line are:");
        for(int i = 0; i < 1; i++)
            for(int j = 0; j < 2; j++)
                Console.Write("({0}, {1})",
                              Line[i, j].x, Line[i, j].y);
        return 0;
    }
}

This would produce:

The points of the line are:
(-3, 8)
(4, -5)
Press any key to continue . . .

To apply a foreach operator, access only each member of the internal list. Here is an example:

public static class Exercise
{
    static int Main(string[] args)
    {
        var Line = new Point[,]
        {
            {
                new Point(-3, 8),  new Point(4, -5)
            }
        };

        Console.WriteLine("The points of the line are:");
        foreach (Point pt in Line)
            Console.WriteLine("({0}, {1})", pt.x, pt.y);
        
        return 0;
    }
}

Multidimensional Arrays of Objects and Classes

 

Introduction

As done for primitive types, a multidimensional array of objects can be made a field of a class. You can declare the array without specifying its size. Here is an example:

public class Triangle
{
    public Point[,] Vertices;
}

If you know the dimensions that the array will have, you can specify them using the new operator at the same time you are creating the field. Here is an example:

public class Triangle
{
    public Point[,] Vertices = new Point[3,2];
}

This creation signals a multidimensional array of Point objects. It will consist of three lists and each list will contain two Point objects

To initialize the array, access each member by its index to allocate memory for it. Once you get the member, you access each one of its fields or properties and initialize it with the desired value. Here is an example:

public class Triangle
{
    public Point[,] Vertices = new Point[3, 2];

    public Triangle()
    {
        Vertices[0, 0] = new Point(); // Point A(x, y)
        Vertices[0, 0].x = -2;        // A(x,  )
        Vertices[0, 0].y = -4;        // A( , y)
        Vertices[1, 0] = new Point(); // Point B(x, y)
        Vertices[1, 0].x =  3;        // B(x,  )
        Vertices[1, 0].y =  5;        // B( , y)
        Vertices[2, 0] = new Point(); // Point C(x, y)
        Vertices[2, 0].x =  6;        // C(x,  )
        Vertices[2, 0].y = -2;        // C( , y)
    }
}

If the class is equipped with the right constructor, you can use it to initialize each member of the array.

Once the array is ready, you can access each members using its index and manipulate it. For example you can display its value(s) to the user. Here is an example:

using System;

public class Point
{
    private int XCoord;
    private int YCoord;

    public Point()
    {
    }

    public Point(int X, int Y)
    {
        XCoord = X;
        YCoord = Y;
    }

    public int x
    {
        get { return XCoord; }
        set { XCoord = value; }
    }

    public int y
    {
        get { return YCoord; }
        set { YCoord = value; }
    }
}

public class Triangle
{
    public Point[,] Vertices = new Point[3, 2];

    public Triangle()
    {
        Vertices[0, 0] = new Point(); // Point A(x, y)
        Vertices[0, 0].x = -2;        // A(x,  )
        Vertices[0, 0].y = -4;        // A( , y)
        Vertices[1, 0] = new Point(); // Point B(x, y)
        Vertices[1, 0].x =  3;        // B(x,  )
        Vertices[1, 0].y =  5;        // B( , y)
        Vertices[2, 0] = new Point(); // Point C(x, y)
        Vertices[2, 0].x =  6;        // C(x,  )
        Vertices[2, 0].y = -2;        // C( , y)
    }

    public void Identify()
    {
        Console.Write("Triangle Vertices: ");
        Console.WriteLine("A({0}, {1}),  B({2}, {3}), and C({4}, {5})",
                          Vertices[0, 0].x, Vertices[0, 0].y,
                          Vertices[1, 0].x, Vertices[1, 0].y,
                          Vertices[2, 0].x, Vertices[2, 0].y);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        Triangle Tri = new Triangle();
        Tri.Identify();

        return 0;
    }
}

This would produce:

Triangle Vertices: A(-2, -4),  B(3, 5), and C(6, -2)
Press any key to continue . . .

Passing a Multidimensional Array of Objects

You can pass a multidimensional array of objects as arguments. To do this, in the parentheses of the method, enter the class name followed by the square brackets. In the square brackets, type the appropriate number of commas. Here is an example:

public class Triangle
{
    public void Create(Point[,] Points)
    {
    }
}

In the body of the method, use the array as you we have done so far. You can access its members to get to its values. Here are examples:

public class Triangle
{
    public void Create(Point[,] Points)
    {
        Points[0, 0] = new Point(); // Point A(x, y)
        Points[0, 0].x = -2;        // A(x,  )
        Points[0, 0].y = -4;        // A( , y)
        Points[1, 0] = new Point(); // Point B(x, y)
        Points[1, 0].x =  3;        // B(x,  )
        Points[1, 0].y =  5;        // B( , y)
        Points[2, 0] = new Point(); // Point C(x, y)
        Points[2, 0].x =  6;        // C(x,  )
        Points[2, 0].y = -2;        // C( , y)
    }

    public void Identify(Point[,] Coordinate)
    {
        Console.Write("Triangle Vertices: ");
        Console.WriteLine("A({0}, {1}),  B({2}, {3}), and C({4}, {5})",
                          Coordinate[0, 0].x, Coordinate[0, 0].y,
                          Coordinate[1, 0].x, Coordinate[1, 0].y,
                          Coordinate[2, 0].x, Coordinate[2, 0].y);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        Triangle Tri = new Triangle();
        Point[,] Vertices = new Point[3, 2];

        Tri.Create(Vertices);
        Tri.Identify(Vertices);

        return 0;
    }
}

Remember that an array passed as argument is in fact passed by reference. You can indicate this by preceding it with the ref keyword.

Returning a Multidimensional Array of Objects

A method can return a multidimensional array of objects. If you are creating the method, before its name, type the name of the class followed by square brackets. Inside the square brackets, type the desired number of commas to indicate the dimension of the returned value. Here is an example:

public class Triangle
{
    public Point[,] Create()
    {
    }
}

After implementing the method, before exiting it, make sure it returns the type of array that it was indicated to produce. Here is an example:

using System;

public class Point
{
    private int XCoord;
    private int YCoord;

    public Point()
    {
    }

    public Point(int X, int Y)
    {
        XCoord = X;
        YCoord = Y;
    }

    public int x
    {
        get { return XCoord; }
        set { XCoord = value; }
    }

    public int y
    {
        get { return YCoord; }
        set { YCoord = value; }
    }
}

public class Triangle
{
    public Point[,] Create()
    {
        var Points = new Point[3, 2];

        Points[0, 0] = new Point(); // Point A(x, y)
        Points[0, 0].x = -2;        // A(x,  )
        Points[0, 0].y = -4;        // A( , y)
        Points[1, 0] = new Point(); // Point B(x, y)
        Points[1, 0].x =  3;        // B(x,  )
        Points[1, 0].y =  5;        // B( , y)
        Points[2, 0] = new Point(); // Point C(x, y)
        Points[2, 0].x =  6;        // C(x,  )
        Points[2, 0].y = -2;        // C( , y)

        return Points;
    }

    public void Identify(Point[,] Coordinate)
    {
        Console.Write("Triangle Vertices: ");
        Console.WriteLine("A({0}, {1}),  B({2}, {3}), and C({4}, {5})",
                          Coordinate[0, 0].x, Coordinate[0, 0].y,
                          Coordinate[1, 0].x, Coordinate[1, 0].y,
                          Coordinate[2, 0].x, Coordinate[2, 0].y);
    }
}

public static class Exercise
{
    static int Main(string[] args)
    {
        Triangle Tri = new Triangle();
        Point[,] Vertices = Tri.Create();
        Tri.Identify(Vertices);

        return 0;
    }
}
 
 

Previous Copyright © 2010-2016, FunctionX Next