Thursday 18 October 2012

Two-Dimensional Arrays

To declare a two-dimensional integer array table of size 10, 20, you would write
int[,] table = new int[10, 20];
Pay careful attention to the declaration. Notice that the two dimensions are separated from
each other by a comma. In the first part of the declaration, the syntax
[,]
indicates that a two-dimensional array reference variable is being created. When memory
is actually allocated for the array using new, this syntax is used:
int[10, 20]
This creates a 10×20 array, and again, the comma separates the dimensions.
To access an element in a two-dimensional array, you must specify both indices,
separating the two with a comma. For example, to assign location 3, 5 of array table
the value 10, you would use
table[3, 5] = 10;
Demonstrate a two-dimensional array:
using System;
class TwoD {
public static void Main() {
int t, i;
int[,] table = new int[3, 4];
for(t=0; t < 3; ++t) {
for(i=0; i < 4; ++i) {
table[t,i] = (t*4)+i+1;
Console.Write(table[t,i] + " ");
}
Console.WriteLine();
     }
  }
}

In this example, table[0, 0] will have the value 1, table[0, 1] the value 2, table[0, 2] the
value 3, and so on. The value of table[2, 3] will be 12.

No comments:

Post a Comment