0% found this document useful (0 votes)
4 views2 pages

2 DArrays

Uploaded by

manormansteam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

2 DArrays

Uploaded by

manormansteam
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

You can have arrays with multiple dimensions, but this will cover 2d arrays.

Multidimensional arrays are essentially just arrays of arrays.

In order to create a 2D array, inside the square brackets, add a comma and put each
array within its own segment of curly brackets:

string[,] eggs = new eggs[,] { {"fried", "boiled", "raw"} {"scrambled",


"burnt", "poached"} };

Eggs is now an array with 2 arrays as its elements, each of which hold three
elements. You can think of the two arrays as seperate rows and the elements in each
as columns:

column 0 | column 1 | column 2


Row 0: | "fried" | "boiled" | "raw"
Row 1: | "scrambled" | "burnt" | "poached"

In order to access a 2D array, you needto specify two indexes, one of which (the
first) being for the array and the other being for the elements in the array. You
can also think of the first index as the row and the second as a column (make sure
not to mix this up with (x, y) in maths as you go down rows then across columns):

string[,] eggs = new eggs[,] { {"fried", "boiled", "raw"} {"scrambled",


"burnt", "poached"} };
Console.Writeline(eggs[0, 2]);
// this outputs boiled

You can also change elements in a 2D array using this format:

string[,] eggs = new eggs[,] { {"fried", "boiled", "raw"} {"scrambled",


"burnt", "poached"} };
eggs[0, 2] = "omelette";
Console.WriteLine(eggs[0, 2]);
// this outputs omelette

A foreach loop will loop through each elements in each array in order:

string[,] eggs = new eggs[,] { {"fried", "boiled" "raw"} {"scrambled",


"burnt", "poached"} };
foreach (string i in eggs)
{
Console.WriteLine(i);
}

You can also use a regular for loop but you need the GetLength() method instead of
simply the .Length method:

string[,] eggs = new eggs[,] { {"fried", "boiled", "raw"} {"scrambled",


"burnt", "poached"} };
for (int i = 0; i < eggs.GetLength(0); i++) // Get.Length(0) asks how many
rows (arrays) there are
{
for (int j = 0; j < eggs.GetLength(0); i++) // Get.Length(1) asks how
many columns (elements) there are in each array
{
Console.WriteLine(eggs[i, j]);
}
}
Keep in mind that this for loop doesn't work if the amount of elements in each
array is different, as it relies on the basis that each array contains the same
number of elements (multiplies the arrays by the elements in each array), just use
the foreach loop if you can't use this one

You might also like