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

  • Allows multiple items of data to be stored together under one identifier like a 1D array.
  • Which reduces need for multiple variables.
  • Furthermore a 2D array can store a table structure.

text

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:

  • a comma is used inside the square brackets to show that this is a 2D array.
  • a row is enclosed with curly braces
  • a comma is used after each row of data.

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:

  1. The value at column position 0 for that row is displayed.
  2. The value at column position 1 for that row is displayed.
  3. 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(" ");
}

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?

Thefollowing 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++;
    }
}

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);
    }
}
  1. Set up the array as before.
  2. Create an instance of Random (you don't need to know what this means until A Level)
  3. This loop is shown with x and y like coordinates which is another common way to iterate through a 2D array.
  4. Inside the loop use rnd.Next(0,200) to get a random number between 0 and 200.

BBC BITESIZE

Pumpkin