Multidimensional Arrays of Primitive Types |
|
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 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).
Practical Learning: Introducing Multidimensional Arrays
Control | (Name) | Text | TextAlign |
Label | Employee #: | ||
TextBox | txtEmployeeNumber | ||
Label | Hourly Salary: | ||
TextBox | txtHourlySalary | Right | |
Label | Employee Name: | ||
TextBox | txtEmployeeName |
using System;
using System.Windows.Forms;
namespace PayrollPreparation14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtEmployeeNumber_Leave(object sender, EventArgs e)
{
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 };
if (string.IsNullOrEmpty(txtEmployeeNumber.Text))
{
MessageBox.Show("You must enter an employee's number", "Payroll Preparation");
return;
}
int emplNbr = int.Parse(txtEmployeeNumber.Text);
for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
{
if (emplNbr == employeesNumbers[nbr])
{
txtEmployeeName.Text = employeesLastNames[nbr] + ", " + employeesFirstNames[nbr];
txtHourlySalary.Text = hourlySalaries[nbr].ToString();
}
}
}
}
}
Control | (Name) | Text | Other Properties |
Label | Employee #: | ||
TextBox | txtEmployeeNumber | ||
Label | Hourly Salary: | ||
TextBox | txtHourlySalary | Right | |
Label | Employee Name: | ||
TextBox | txtEmployeeName | ||
GroupBox | Work Preparation | ||
Label | _________________ | ||
Label | Monday | ||
Label | Tuesday | ||
Label | Wednesday | ||
Label | Thursday | ||
Label | Friday | ||
Label | Time Worked | ||
TextBox | txtTimeWorkedMonday | Right | |
TextBox | txtTimeWorkedTuesday | Right | |
TextBox | txtTimeWorkedWednesday | Right | |
TextBox | txtTimeWorkedThursday | Right | |
TextBox | txtTimeWorkedFriday | Right | |
Label | _________________ |
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:
using System;
using System.Windows.Forms;
namespace Exercise
{
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void btnDateTime_Click(object sender, EventArgs e)
{
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:
using System; using System.Windows.Forms; namespace Exercise { public partial class Form1 : Form { public Form1() => InitializeComponent(); private void btnDateTime_Click(object sender, EventArgs e) { 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 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; using System.Windows.Forms; namespace Exercise { public partial class Form1 : Form { public Form1() => InitializeComponent(); private void btnDateTime_Click(object sender, EventArgs e) { 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:
using System; using System.Windows.Forms; namespace Exercise { public partial class Form1 : Form { public Form1() => InitializeComponent(); private void btnDateTime_Click(object sender, EventArgs e) { 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:
using System;
using System.Windows.Forms;
namespace Exercise03
{
public partial class Form1 : Form
{
public Form1() => InitializeComponent();
private void btnDateTime_Click(object sender, EventArgs e)
{
double[,] members = new string[,]
{
{"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:
using System; public class Exercise { public static void Main(string[] args) { 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 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; using static System.Console; public class Program { public static int Main(string[] args) { 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++) WriteLine("Person: {0}", members[External, Internal]); WriteLine("================================="); return 9_999; } }
Click Color and click RGB
Person: Celeste Person: Mathurin Person: Alex Person: Germain Person: Jeremy Person: Mathew Person: Anselme Person: Frederique ================================= Press any key to continue . . .
Practical Learning: Accessing the Members of a Two-Dimensional Array
using System; using System.Windows.Forms; namespace PayrollPreparation14 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void txtEmployeeNumber_Leave(object sender, EventArgs e) { int[] employeesNumbers = new int[] { 293708, 594179, 820392, 492804, 847594 }; double[] hourlySalaries = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 }; string[,] employeesNames = new string[2, 6] { { "Jonathan", "Christine", "Peter", "Lilly", "Gabriel", "Evelyne" }, { "Greenberg", "Keys", "Verland", "Malone", "Reasons", "Roberts" } }; /* 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 } }; if (string.IsNullOrEmpty(txtEmployeeNumber.Text)) { MessageBox.Show("You must enter an employee's number", "Payroll Preparation"); return; } int emplNbr = int.Parse(txtEmployeeNumber.Text); for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++) { if (emplNbr == employeesNumbers[nbr]) { txtEmployeeName.Text = string.Format("{0}, {1}", employeesNames[0, nbr], employeesNames[1, nbr]); txtHourlySalary.Text = hourlySalaries[nbr].ToString(); txtMondayTimeWorked.Text = timesWorked[nbr, 0].ToString("F"); txtTuesdayTimeWorked.Text = timesWorked[nbr, 1].ToString("F"); txtWednesdayTimeWorked.Text = timesWorked[nbr, 2].ToString("F"); txtThursdayTimeWorked.Text = timesWorked[nbr, 3].ToString("F"); txtFridayTimeWorked.Text = timesWorked[nbr, 4].ToString("F"); return; } } } } }
namespace PayrollPreparation14 { public 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; } } }
namespace PayrollPreparation14 { public 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); } } } }
Control | (Name) | Text | TextAlign |
Label | Employee #: | ||
TextBox | txtEmployeeNumber | ||
Label | Hourly Salary: | ||
TextBox | txtHourlySalary | Right | |
Label | Employee Name: | ||
TextBox | txtEmployeeName | ||
GroupBox | Work Preparation | ||
Label | _________________ | ||
Label | Monday | ||
Label | Tuesday | ||
Label | Wednesday | ||
Label | Thursday | ||
Label | Friday | ||
Label | Time Worked | ||
TextBox | txtTimeWorkedMonday | Right | |
TextBox | txtTimeWorkedTuesday | Right | |
TextBox | txtTimeWorkedWednesday | Right | |
TextBox | txtTimeWorkedThursday | Right | |
TextBox | txtTimeWorkedFriday | Right | |
Label | ___________________ | ||
Label | Time | ||
Label | Pay | ||
Label | Regular: | ||
TextBox | txtRegularTime | Right | |
TextBox | txtRegularPay | Right | |
Label | Overtime: | ||
TextBox | txtOvertime | Right | |
TextBox | txtOvertimePay | Right | |
Label | ____________________ | ||
Label | Net Pay | ||
TextBox | txtNetPay | Right |
using System;
using System.Windows.Forms;
namespace PayrollPreparation14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtEmployeeNumber_Leave(object sender, EventArgs e)
{
int[] employeesNumbers = new int[] { 293708, 594179, 820392, 492804, 847594 };
double[] hourlySalaries = new double[] { 22.86, 29.47, 30.72, 18.39, 17.38 };
string[,] employeesNames = new string[2, 6]
{
{ "Jonathan", "Christine", "Peter", "Lilly", "Gabriel", "Evelyne" },
{ "Greenberg", "Keys", "Verland", "Malone", "Reasons", "Roberts" }
};
/* 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 }
};
if (string.IsNullOrEmpty(txtEmployeeNumber.Text))
{
MessageBox.Show("You must enter an employee's number", "Payroll Preparation");
return;
}
int emplNbr = int.Parse(txtEmployeeNumber.Text);
for (int nbr = 0; nbr <= employeesNumbers.Length - 1; nbr++)
{
if (emplNbr == employeesNumbers[nbr])
{
txtEmployeeName.Text = string.Format("{0}, {1}", employeesNames[0, nbr], employeesNames[1, nbr]);
txtHourlySalary.Text = hourlySalaries[nbr].ToString();
txtMondayTimeWorked.Text = timesWorked[nbr, 0].ToString("F");
txtTuesdayTimeWorked.Text = timesWorked[nbr, 1].ToString("F");
txtWednesdayTimeWorked.Text = timesWorked[nbr, 2].ToString("F");
txtThursdayTimeWorked.Text = timesWorked[nbr, 3].ToString("F");
txtFridayTimeWorked.Text = timesWorked[nbr, 4].ToString("F");
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);
txtRegularTime.Text = preparation.RegularTime.ToString("F");
txtOvertime.Text = preparation.Overtime.ToString("F");
txtRegularPay.Text = preparation.RegularPay.ToString("F");
txtOvertimePay.Text = preparation.OvertimePay.ToString("F");
txtNetPay.Text = preparation.NetPay.ToString("F");
return;
}
}
}
}
}
For Each Item in an Array
To apply a foreach operator, access only each member of the internal list. Here is an example:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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) WriteLine("Person: {0}", name); WriteLine("================================="); return 9_999; } }
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:
public class Exercise
{
private void Create
{
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:
public class Exercise
{
private void Create
{
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:
public class Exercise { private void Create { 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 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 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:
public class Program
{
public static void Main(string[] args)
{
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:
public class Program { public static void Main(string[] args) { 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 System; using static System.Console; public class Program { public static int Main(string[] args) { 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("================================="); return 9_999; } }
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:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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++) WriteLine("Number: {0}", numbers[outside, inside, value]); WriteLine("================================="); return 9_999; } }
To indicate the position of eah item, we could use code as follows:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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++) WriteLine("Numbers[" + outside + "][" + inside + "][" + value + "] = " + numbers[outside, inside, value]); WriteLine("================================="); return 9_999; } }
To use a foreach operator, access only each member to get to it. Here is an example:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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) WriteLine("Numbers: " + value); WriteLine("================================="); return 9_999; } }
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:
public class Program
{
public static void Main(string[] args)
{
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:
public class Program
{
public static int Main(string[] args)
{
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:
public class Program
{
public static int Main(string[] args)
{
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:
using System; using static System.Console; public class Program { public static int Main(string[] args) { string[][] members = new string[2][]; members[0] = new string[] { "Celeste", "Mathurin", "Alex", "Germain" }; members[1] = new string[] { "Jeremy", "Mathew", "Anselme", "Frederique" }; WriteLine("Member 1: {0}", members[0][0]); WriteLine("Member 2: {0}", members[0][1]); WriteLine("Member 3: {0}", members[0][2]); WriteLine("Member 4: {0}", members[0][3]); WriteLine("Member 5: {0}", members[0][0]); WriteLine("Member 6: {0}", members[1][1]); WriteLine("Member 7: {0}", members[1][2]); WriteLine("Member 8: {0}", members[1][3]); WriteLine("================================="); return 9_999; } }
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:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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++) WriteLine("Member: {0}", members[externe][interne]); WriteLine("================================="); return 2; } }
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 System; using static System.Console; public class Program { public static int Main(string[] args) { 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]) WriteLine("Member: {0}", name); WriteLine("================================="); return 2; } }
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:
using System; using static System.Console; public class Program { public static int Main(string[] args) { 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]) WriteLine("Member: {0}", name); WriteLine("-------------------"); foreach (string name in members[1]) WriteLine("Member: {0}", name); WriteLine("================================="); return 2; } }
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;
|
||
Previous | Copyright © 2001-2020, FunctionX | Next |
|