A Two-Dimensional Array

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.

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 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).

Practical LearningPractical Learning: Introducing Multidimensional Arrays

  1. Start Microsoft Visual Studio and create a C# Console App (that supports the .NET 8.0 (Long-Term Support)) named PayrollPreparation8
  2. From the Solution Explorer, rename Program.cs as PayrollPreparation
  3. Change the document as follows:
    using static System.Console;
    
    int[]    employeesNumbers = new int[] { 293708, 594179, 820392, 492804, 847594 };
    string[] employeesFirstNames = new string[] { "Christine", "Peter", "Jonathan", "Lilly", "Gabriel" };
    string[] employeesLastNames = new string[] { "Greenberg", "Keys", "Verland", "Malone", "Reasons" };
    double[] hourlySalaries = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 };
    
    int emplNbr = 0;
    
    WriteLine("Payroll Preparation");
    WriteLine("===================");
    
    try
    {
        Write("Employee #: ");
        emplNbr = int.Parse(ReadLine()!);
    }
    catch(FormatException)
    {
        WriteLine("You must enter an employee's number.");
    }
    
    Clear();
    
    for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
    {
        if (emplNbr == employeesNumbers[nbr])
        {
            WriteLine("Payroll Preparation");
            WriteLine("===================================");
            WriteLine($"Employee #:    {employeesNumbers[nbr]}");
            WriteLine("EmployeeName:  " + employeesLastNames[nbr] + ", " + employeesFirstNames[nbr]);
            WriteLine($"Hourly Salary: {hourlySalaries[nbr]}");
        }
    }
    
    WriteLine("===================================");
  4. To execute the application, on the main menu, click Debug -> Start Without Debugging
  5. When requested, type the Employee # as 293708
    Payroll Preparation
    ===================
    Employee #: 293708
  6. Press Enter:
    Payroll Preparation
    ===================================
    Employee #:    293708
    EmployeeName:  Greenberg, Christine
    Hourly Salary: 22.86
    ===================================
    
    Press any key to close this window . . .
  7. Close the 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 primary formula to follow is:

data-type[,] variable-name;

The pair of square brackets is empty but must contain a comma. Here is an example:

string[,] names;

Initializing a Two-Dimensional Array

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:

data-type[,] variable-name = new data-type[number1,number2];

Once again, the left square brackets contain only a comma. In the right square brackets, enter two integers separated by a comma. Here is an example:

string[,] members = new string[2, 4];

You can use the var keyword to declare the variable. The formula to follow is:

var variable-name = new data-type[number1,number2];

You can also use the dynamic keyword. If you use the var or the dynamic keyword, you don't need the left square brackets but, in the right square brackets, you must specify the sizes of the array. Here is an example:

var names = new string[2, 4];
dynamic people = new string[2, 2];

In our declaration, the names 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 2 * 4 = 8 elements. 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 are examples:

double[,] prices = new double[5, 8];
var storeItems = new string[3, 7];
dynamic distances = new float[7, 4];

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 the brackets, include a pair of an opening and a closing curly brackets for each internal list of the array. Then, inside 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:

string[,] names = new string[2, 4]
        {
            {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
            {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
        };

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

double[,] 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 }
};

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:

string[,] members = new string[,]
{
    {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
    {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
};

Since the left side of the assignment operator indicates the type of the array, you can omit the data type on the right side of the assignment operator. This can be done as follows:

string[,] members = new[,]
{
    {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
    {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
};

In fact, since the left side of the assignment operator indicates that you are creating an array, you can omit the new operator and square brackets on the right side of the assignment operator. This can be done as follows:

string[,] members =
{
    {"Celeste", "Mathurin", "Alex", "Germain"},   // First List
    {"Jeremy", "Mathew", "Anselme", "Frederique"} // Second List
};

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, and so on. 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 it 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:

string[,] members = new string[2,4];

members[0, 0] = "Celeste";    // Member of the first list, first item
members[0, 1] = "Mathurin";   // Member of the first list, second item
members[0, 2] = "Alex";       // Member of the first list, third item
members[0, 3] = "Germain";    // Member of the first list, fourth item
members[1, 0] = "Jeremy";     // Member of the second list, first item
members[1, 1] = "Mathew";     // Member of the second list, second item
members[1, 2] = "Anselme";    // Member of the second list, third item
members[1, 3] = "Frederique"; // Member of the second list, fourth item

You can use this same technique to retrieve the value of each member of the array.

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 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:

string[,] 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("Person: {0}", members[External, Internal]);

Console.WriteLine("=================================");

This would produce:

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

Practical LearningPractical Learning: Accessing the Members of a Two-Dimensional Array

  1. Change the code as follows:
    using static System.Console;
    
    int[]    employeesNumbers    = new int[] { 293708, 594179, 820392, 492804, 847594 };
    string[] employeesFirstNames = new string[] { "Christine", "Peter", "Jonathan", "Lilly", "Gabriel" };
    string[] employeesLastNames  = new string[] { "Greenberg", "Keys", "Verland", "Malone", "Reasons" };
    double[] hourlySalaries      = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 };
    
    /* This is an array that represents time sheet values for 5 employees. 
     * Each employee works 5 days a week. */
    double[,] timesWorked = new double[5, 5]
    {
        {  8.00,  8.00, 8.00, 8.00, 8.00 },
        {  6.00,  7.50, 6.00, 8.50, 6.00 },
        { 10.00,  8.50, 9.00, 8.00, 9.50 },
        {  8.50,  6.00, 7.50, 6.00, 7.00 },
        {  9.00, 10.50, 8.00, 7.50, 9.00 }
    };
    
    int emplNbr = 0;
    
    WriteLine("Payroll Preparation");
    WriteLine("===================");
    
    try
    {
        Write("Employee #: ");
        emplNbr = int.Parse(ReadLine()!);
    }
    catch(FormatException)
    {
        WriteLine("You must enter an employee's number.");
    }
    
    Clear();
    
    for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
    {
        if (emplNbr == employeesNumbers[nbr])
        {
            WriteLine("Payroll Preparation");
            WriteLine("================================");
            WriteLine($"Employee #:    {employeesNumbers[nbr]}");
            WriteLine("EmployeeName:  " + employeesLastNames[nbr] + ", " + employeesFirstNames[nbr]);
            WriteLine($"Hourly Salary: {hourlySalaries[nbr]}");
            WriteLine("================================");
            WriteLine("Time Worked");
            WriteLine("--------------------------------");
            WriteLine($"Monday:        {timesWorked[nbr, 0]:F}");
            WriteLine($"Tuesday:       {timesWorked[nbr, 1]:F}");
            WriteLine($"Wednesday:     {timesWorked[nbr, 2]:F}");
            WriteLine($"Thursday:      {timesWorked[nbr, 3]:F}");
            WriteLine($"Friday:        {timesWorked[nbr, 4]:F}");
            WriteLine("================================");
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Without Debugging
  3. Type the Employee # as 594179
    Payroll Preparation
    ================================
    Employee #:    594179
    EmployeeName:  Keys, Peter
    Hourly Salary: 29.47
    ================================
    Time Worked
    --------------------------------
    Monday:        6.00
    Tuesday:       7.50
    Wednesday:     6.00
    Thursday:      8.50
    Friday:        6.00
    ================================
    
    Press any key to close this window . . .
  4. Close the window and return to Micrsoft Visual Studio
  5. On the main menu, click Project -> Add Class...
  6. Change the file Name to Calculations
  7. Click Add
  8. Change the class as follows:
    namespace PayrollPreparation2
    {
        internal static class Calculations
        {
            public static double Add(double a, double b)
            {
                return a + b;
            }
    
            public static double Add(double a, double b, double c, double d, double e)
            {
                return a + b + c + d + e;
            }
    
            public static double Subtract(double a, double b)
            {
                return a - b;
            }
    
            public static double Multiply(double a, double b)
            {
                return a * b;
            }
        }
    }
  9. In the Solution Explorer, right-click PayrollPreparation2 -> Add -> Class...
  10. Change the Name to PayrollEvaluation
  11. Click Add
  12. Create a class as follows:
    namespace PayrollPreparation2
    {
        internal sealed class Payroll
        {
            private double timeSpecified;
    
            public Payroll(double salary, double time)
            {
                HourSalary = salary;
                timeSpecified = time;
            }
    
            public double HourSalary { get; set; }
    
            public double OvertimeSalary
            {
                get { return Calculations.Multiply(HourSalary, 1.50); }
            }
    
            public double RegularTime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return timeSpecified;
                    else
                        return 40.00;
                }
            }
    
            public double Overtime
            {
                get
                {
                    if (timeSpecified <= 40.00)
                        return 0.00;
                    else
                        return Calculations.Subtract(timeSpecified, 40.00);
                }
            }
    
            public double RegularPay
            {
                get { return Calculations.Multiply(HourSalary, RegularTime); }
            }
    
            public double OvertimePay
            {
                get { return Calculations.Multiply(OvertimeSalary, Overtime); }
            }
    
            public double NetPay
            {
                get { return Calculations.Add(RegularPay, OvertimePay); }
            }
        }
    }
  13. Click the PayrollPreparation.cs tab to access it
  14. Change the document as follows:
    using static System.Console;
    
    int[]    employeesNumbers    = new int[] { 293708, 594179, 820392, 492804, 847594 };
    string[] employeesFirstNames = new string[] { "Christine", "Peter", "Jonathan", "Lilly", "Gabriel" };
    string[] employeesLastNames  = new string[] { "Greenberg", "Keys", "Verland", "Malone", "Reasons" };
    double[] hourlySalaries      = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 };
    
    /* This is an array that represents time sheet values for 5 employees. 
     * Each employee works 5 days a week. */
    double[,] timesWorked = new double[5, 5]
    {
        {  8.00,  8.00, 8.00, 8.00, 8.00 },
        {  6.00,  7.50, 6.00, 8.50, 6.00 },
        { 10.00,  8.50, 9.00, 8.00, 9.50 },
        {  8.50,  6.00, 7.50, 6.00, 7.00 },
        {  9.00, 10.50, 8.00, 7.50, 9.00 }
    };
    
    int emplNbr = 0;
    
    WriteLine("Payroll Preparation");
    WriteLine("===================");
    
    try
    {
        Write("Employee #: ");
        emplNbr = int.Parse(ReadLine()!);
    }
    catch(FormatException)
    {
        WriteLine("You must enter an employee's number.");
    }
    
    Clear();
    
    for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
    {
        if (emplNbr == employeesNumbers[nbr])
        {
            WriteLine("Payroll Preparation");
            WriteLine("====================================");
            WriteLine($"Employee #:         {employeesNumbers[nbr]}");
            WriteLine("EmployeeName:       " + employeesLastNames[nbr] + ", " + employeesFirstNames[nbr]);
            WriteLine($"Hourly Salary:      {hourlySalaries[nbr]}");
            WriteLine("====================================");
            WriteLine("Time Worked");
            WriteLine("------------------------------------");
            WriteLine($"Monday:        {timesWorked[nbr, 0],10:F}");
            WriteLine($"Tuesday:       {timesWorked[nbr, 1],10:F}");
            WriteLine($"Wednesday:     {timesWorked[nbr, 2],10:F}");
            WriteLine($"Thursday:      {timesWorked[nbr, 3],10:F}");
            WriteLine($"Friday:        {timesWorked[nbr, 4],10:F}");
            WriteLine("====================================");
    
            double totalTime = Calculations.Add(timesWorked[nbr, 0],
                                                timesWorked[nbr, 1],
                                                timesWorked[nbr, 2],
                                                timesWorked[nbr, 3],
                                                timesWorked[nbr, 4]);
    
            Payroll preparation = new Payroll(hourlySalaries[nbr], totalTime);
    
            WriteLine("Pay Summary");
            WriteLine("------------------------------------");
            WriteLine($"Regular Time:  {preparation.RegularTime,10:F}");
            WriteLine($"Overtime:      {preparation.Overtime,10:F}");
            WriteLine($"Regular Pay:   {preparation.RegularPay,10:F}");
            WriteLine($"Overtime Pay:  {preparation.OvertimePay,10:F}");
            WriteLine($"Net Pay:       {preparation.NetPay,10:F}");
            WriteLine("====================================");
        }
    }
  15. To execute the application, on the main menu, click Debug -> Start Without Debugging
  16. In the Employee # text box, type 820392
  17. Press Enter:
    Payroll Preparation
    ====================================
    Employee #:         820392
    EmployeeName:       Verland, Jonathan
    Hourly Salary:      30.72
    ====================================
    Time Worked
    ------------------------------------
    Monday:             10.00
    Tuesday:             8.50
    Wednesday:           9.00
    Thursday:            8.00
    Friday:              9.50
    ====================================
    Pay Summary
    ------------------------------------
    Regular Time:       40.00
    Overtime:            5.00
    Regular Pay:      1228.80
    Overtime Pay:      230.40
    Net Pay:          1459.20
    ====================================
    
    Press any key to close this window . . .
  18. Close the window and return to Micrsoft Visual Studio

For Each Item in an Array

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

string[,] 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 (string name in members)
    Console.WriteLine("Person: {0}", name);

Console.WriteLine("=================================");

A Multidimensional Array

Introduction

Beyond two dimensions, you can create an array variable that represents various lists, each list containing various internal lists, and each internal list containing 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 the desired number of commas in the square bracketsry. 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 in them. Here is an example that represents a three-dimensional array that is not initialized:

double[,,] Numbers;

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:

double[,,] Number = new double[2, 3, 5];

In this case, you can use the var or the dynamic keyword on the left side of the name of the variable. Here are examples:

var numbers = new double[2, 3, 5];
dynami names = new string[2, 4, 8];

For the first variable, 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, 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 the main curly brackets, the first nested curly brackets represent a list of the first dimension. Inside those brackets, you use another set of curly brackets to represent a list that would be nested. You continue this up to the most internal array. Then, in that last set, initialize the members of the array by specifying their values. Here is an example:

double[,,] numbers = 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 }
    },
};

Accessing the 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:

double[, , ] numbers = new double[2, 3, 5];

numbers[0, 0, 0] = 12.44;
numbers[0, 0, 1] = 525.38;
numbers[0, 0, 2] = -6.28;
numbers[0, 0, 3] = 2448.32;
numbers[0, 0, 4] = 632.04;
numbers[0, 1, 0] = -378.05;
numbers[0, 1, 1] = 48.14;
numbers[0, 1, 2] = 634.18;
numbers[0, 1, 3] = 762.48;
numbers[0, 1, 4] = 83.02;
numbers[0, 2, 0] = 64.92;
numbers[0, 2, 1] = -7.44;
numbers[0, 2, 2] = 86.74;
numbers[0, 2, 3] = -534.60;
numbers[0, 2, 4] = 386.73;
numbers[1, 0, 0] = 48.02;
numbers[1, 0, 1] = 120.44;
numbers[1, 0, 2] = 38.62;
numbers[1, 0, 3] = 526.82;
numbers[1, 0, 4] = 1704.62;
numbers[1, 1, 0] = 56.85;
numbers[1, 1, 1] = 105.48;
numbers[1, 1, 2] = 363.31;
numbers[1, 1, 3] = 172.62;
numbers[1, 1, 4] = 128.48;
numbers[1, 2, 0] = 906.68;
numbers[1, 2, 1] = 47.12;
numbers[1, 2, 2] = -166.07;
numbers[1, 2, 3] = 4444.26;
numbers[1, 2, 4] = 408.62;

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 static System.Console;

double[,,] numbers = 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 }
    },
};
    
WriteLine("Numbers [0] [0] [0]: {0}", numbers[0, 0, 0]);
WriteLine("Numbers [0] [0] [1]: {0}", numbers[0, 0, 1]);
WriteLine("Numbers [0] [0] [2]: {0}", numbers[0, 0, 2]);
WriteLine("Numbers [0] [0] [3]: {0}", numbers[0, 0, 3]);
WriteLine("Numbers [0] [0] [4]: {0}", numbers[0, 0, 4]);
        
WriteLine("Numbers [0] [1] [0]: {0}", numbers[0, 1, 0]);
WriteLine("Numbers [0] [1] [1]: {0}", numbers[0, 1, 1]);
WriteLine("Numbers [0] [1] [2]: {0}", numbers[0, 1, 2]);
WriteLine("Numbers [0] [1] [3]: {0}", numbers[0, 1, 3]);
WriteLine("Numbers [0] [1] [4]: {0}", numbers[0, 1, 4]);
        
WriteLine("Numbers [0] [2] [0]: {0}", numbers[0, 2, 0]);
WriteLine("Numbers [0] [2] [1]: {0}", numbers[0, 2, 1]);
WriteLine("Numbers [0] [2] [2]: {0}", numbers[0, 2, 2]);
WriteLine("Numbers [0] [2] [3]: {0}", numbers[0, 2, 3]);
WriteLine("Numbers [0] [2] [4]: {0}", numbers[0, 2, 4]);
        
WriteLine("Numbers [1] [0] [0]: {0}", numbers[1, 0, 0]);
WriteLine("Numbers [1] [0] [1]: {0}", numbers[1, 0, 1]);
WriteLine("Numbers [1] [0] [2]: {0}", numbers[1, 0, 2]);
WriteLine("Numbers [1] [0] [3]: {0}", numbers[1, 0, 3]);
WriteLine("Numbers [1] [0] [4]: {0}", numbers[1, 0, 4]);
        
WriteLine("Numbers [1] [1] [0]: {0}", numbers[1, 1, 0]);
WriteLine("Numbers [1] [1] [1]: {0}", numbers[1, 1, 1]);
WriteLine("Numbers [1] [1] [2]: {0}", numbers[1, 1, 2]);
WriteLine("Numbers [1] [1] [3]: {0}", numbers[1, 1, 3]);
WriteLine("Numbers [1] [1] [4]: {0}", numbers[1, 1, 4]);
        
WriteLine("Numbers [1] [2] [0]: {0}", numbers[1, 2, 0]);
WriteLine("Numbers [1] [2] [1]: {0}", numbers[1, 2, 1]);
WriteLine("Numbers [1] [2] [2]: {0}", numbers[1, 2, 2]);
WriteLine("Numbers [1] [2] [3]: {0}", numbers[1, 2, 3]);
WriteLine("Numbers [1] [2] [4]: {0}", numbers[1, 2, 4]);

WriteLine("=================================");

This would produce:

Numbers [0] [0] [0]: 12.44
Numbers [0] [0] [1]: 525.38
Numbers [0] [0] [2]: -6.28
Numbers [0] [0] [3]: 2448.32
Numbers [0] [0] [4]: 632.04
Numbers [0] [1] [0]: -378.05
Numbers [0] [1] [1]: 48.14
Numbers [0] [1] [2]: 634.18
Numbers [0] [1] [3]: 762.48
Numbers [0] [1] [4]: 83.02
Numbers [0] [2] [0]: 64.92
Numbers [0] [2] [1]: -7.44
Numbers [0] [2] [2]: 86.74
Numbers [0] [2] [3]: -534.6
Numbers [0] [2] [4]: 386.73
Numbers [1] [0] [0]: 48.02
Numbers [1] [0] [1]: 120.44
Numbers [1] [0] [2]: 38.62
Numbers [1] [0] [3]: 526.82
Numbers [1] [0] [4]: 1704.62
Numbers [1] [1] [0]: 56.85
Numbers [1] [1] [1]: 105.48
Numbers [1] [1] [2]: 363.31
Numbers [1] [1] [3]: 172.62
Numbers [1] [1] [4]: 128.48
Numbers [1] [2] [0]: 906.68
Numbers [1] [2] [1]: 47.12
Numbers [1] [2] [2]: -166.07
Numbers [1] [2] [3]: 4444.26
Numbers [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:

double[,,] numbers = 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 }
    },
};

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}", numbers[outside, inside, value]);

Console.WriteLine("=================================");

To indicate the position of eah item, we could use code as follows:

double[,,] numbers = 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 }
    },
};

for (int outside = 0; outside < 2; outside++)
    for (int inside = 0; inside < 3; inside++)
        for (int value = 0; value < 5; value++)
            Console.WriteLine("Numbers[" + outside + "][" + inside + "][" + value + "] = " + numbers[outside, inside, value]);

Console.WriteLine("=================================");

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

double[,,] numbers = 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 }
    },
};

foreach (double value in numbers)
    Console.WriteLine("Numbers: " + value);

Console.WriteLine("=================================");

Jagged Arrays

Introduction

A jagged array is an array of arrays, or an array of arrays of arrays, etc.

To create a jagged array, use a combination of square brackets for each dimension. The formula used is:

data-type[][] variable-name;

Each of the square brackets is used in any of the ways we have introduced arrays so far. This means that the first square bracket can be used as its own one-dimensional array or as a multi-dimensional array. Here is an example:

string[2][5] members;

This declares a variable that represents two arrays and each array internally contains 5 arrays.

Initialization of a Jagged Array

When declaring a jagged array, you can allocate memory for it using the new operator followed by the data type of the array and the same combination of square brackets used on the left of the assignment operator. The first pair of square brackets on the right side of the assignment operator must contain the external dimension of the array. The second pair of square brackets must be left empty. Here is an example:

string[][] members = new string[2][];

To initialize a jagged array, when declaring the variable, on the right side of the second pair of square brackets, provide an opening and a closing curly brackets, then create each list in its own pair of curly brackets. At the beginning of each list, you must allocate memory for the list with the new operator. Here is an example:

string[][] members = new string[2][]{
	new string[]{"Celeste", "Mathurin", "Alex", "Germain"},
	new string[]{"Jeremy", "Mathew", "Anselme", "Frederique"} };

If you initialize the array this way, you can omit specifying the dimension of the external array. With a jagged array, you can also initialize its internal array individually. To do this, access each internal array by its zero-based index. Here is an example:

string[][] members = new string[2][];
		
members[0] = new string[]{"Celeste", "Mathurin", "Alex", "Germain"};
members[1] = new string[]{"Jeremy", "Mathew", "Anselme", "Frederique"};

Access to Members of a Jagged Array

As done for a multidimensional array, each member of a jagged array can be accessed with a multiple index, depending on how the array was created. Both the external and the internal lists are zero-based. Here is an example:

string[][] members = new string[2][];

members[0] = new string[] { "Celeste", "Mathurin", "Alex", "Germain" };
members[1] = new string[] { "Jeremy", "Mathew", "Anselme", "Frederique" };

Console.WriteLine("Member 1: {0}", members[0][0]);
Console.WriteLine("Member 2: {0}", members[0][1]);
Console.WriteLine("Member 3: {0}", members[0][2]);
Console.WriteLine("Member 4: {0}", members[0][3]);
Console.WriteLine("Member 5: {0}", members[0][0]);
Console.WriteLine("Member 6: {0}", members[1][1]);
Console.WriteLine("Member 7: {0}", members[1][2]);
Console.WriteLine("Member 8: {0}", members[1][3]);

Console.WriteLine("=================================");

This would produce:

Member 1: Celeste
Member 2: Mathurin
Member 3: Alex
Member 4: Germain
Member 5: Celeste
Member 6: Mathew
Member 7: Anselme
Member 8: Frederique
=================================
Press any key to continue . . .

You can also use some loops to access each member of the array. Here is an example:

string[][] members = new string[2][];

members[0] = new string[] { "Celeste", "Mathurin", "Alex", "Germain" };
members[1] = new string[] { "Jeremy", "Mathew", "Anselme", "Frederique" };

for (int externe = 0; externe < 2; externe++)
    for (int interne = 0; interne < 4; interne++)
        Console.WriteLine("Member: {0}", members[externe][interne]);

Console.WriteLine("=================================");

If you want to use a foreach operator, you must access each array by its index. The external array can be accessed using a-zero based index and remember that you are accessing a whole array. Here is an example:

using static System.Console;

string[][] members = new string[2][];

members[0] = new string[] { "Celeste", "Mathurin", "Alex", "Germain" };
members[1] = new string[] { "Jeremy", "Mathew", "Anselme", "Frederique" };

foreach (string name in members[0])
    Console.WriteLine("Member: {0}", name);

Console.WriteLine("=================================");

This would produce:

Member: Celeste
Member: Mathurin
Member: Alex
Member: Germain
=================================
Press any key to continue . . .

To access the second array, apply its index as array-name[1]. Here is an example:

string[][] members = new string[2][];

members[0] = new string[] { "Celeste", "Mathurin", "Alex", "Germain" };
members[1] = new string[] { "Jeremy", "Mathew", "Anselme", "Frederique" };

foreach (string name in members[0])
    Console.WriteLine("Member: {0}", name);

Console.WriteLine("-------------------");

foreach (string name in members[1])
    Console.WriteLine("Member: {0}", name);

Console.WriteLine("=================================");

This would produce:

Member: Celeste
Member: Mathurin
Member: Alex
Member: Germain
-------------------
Member: Jeremy
Member: Mathew
Member: Anselme
Member: Frederique
=================================
Press any key to continue . . .

A Multidimensional Jagged Array

Because each pair of square brackets is its own array, it can be used to create its own array with its own multidimensional array. Here is an example that creates a multidimensional array:

string[2,4][5] members;

In the same way, the second square bracket can be used as a single or a multidimensional array. Here is an example:

string[2,4][5,12,8] members;

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Friday 26 November 2021 Next