Multidimensional Arrays


Although the one-dimensional array is the most commonly used array in programming, multidimensional arrays are certainly not rare. A multidimensional array is an array that has two or more dimensions, and an individual element is accessed through the combination of two or more indices.

Two-Dimensional Arrays

The simplest form of the multidimensional array is the two-dimensional array. In a two-dimensional array, the location of any specific element is specified by two indices. If you think of a two-dimensional array as a table of information, one index indicates the row, the other indicates the column.

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;

Here is a complete example. It loads a two-dimensional array with the numbers 1 through 12 and then displays the contents of the array.

 // 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. Conceptually, the array will look like that shown in Figure 7-1.

image from book
Figure 7-1: A conceptual view of the table array created by the TwoD program



C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net