What is a 2D Array?
A two-dimensional array is much like a normal 1D array. However it allows you to represent data as a grid or rows and columns.
So a 2D
|
How do I create a 2D array?
To create a 2D array with set values use the following code:
int[,] array2D = new int[,] {
{ 1, 2, 3 }, { 4, 5,6 }, { 7,8,9}, { 10,11,12} }; |
The code here will create an array with 4 rows and 3 columns.
Note:
|
How do I iterate ( loop) through the array?
Here is some code to iterate through the loop with a count controlled ( for) loop and display each value:
for( int row = 0; row < 4; row++)
{ Console.Write(array2D[row,0] + " "); Console.Write(array2D[row, 1] + " "); Console.WriteLine(array2D[row, 2]); } |
The code here will loop through each row.
The value at column position 0 for that row is displayed. The value at column position 1 for that row is displayed. The value at column position 2 for that row is displayed. ( Using Write to display words next to each other and then WriteLine to display and then move on to the next line). |
Iteration using a nested count controlled loop.
Since the column values increase by one inside the for loop we can use another loop inside:
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 3; col++)
{
Console.Write(array2D[row, col] + " ");
}
Console.WriteLine(" ");
}
{
for (int col = 0; col < 3; col++)
{
Console.Write(array2D[row, col] + " ");
}
Console.WriteLine(" ");
}
How do I create an empty array?
The following code with create an empty array with 10 columns and 12 rows:
int[,] arrSimple = new int[10, 12];
How do I fill up the array?
The following code will populate ( fill) the array with numbers starting at 1. The code uses a local variable n.
int n = 1;
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 12; col++)
{
arrSimple[row, col] = n++;
}
}
for (int row = 0; row < 10; row++)
{
for (int col = 0; col < 12; col++)
{
arrSimple[row, col] = n++;
}
}
How would fill the array with random numbers?
int[,] arr = new int[10, 12];
// set up for random.. Random rnd = new Random(); // iterate through the array and fill with random numbers.. for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { arr[x, y] = rnd.Next(0, 200); } } |
|