N-Dimensional Arrays
n-dimensional, or multidimensional, arrays are easy to declare and use. They work just
like single-dimensional arrays, except that a comma is placed within the square brackets between
the array dimensions.
It’s easy to see why you might want to use a two-dimension array to represent the “board” of a
game like checkers or chess. N-dimensional arrays become useful when more information is needed to
adequately model a situation. For example, a three dimensional array might be used to store
stock prices and volume over time.
Here are the declarations for a two-dimensional integer array and a three-dimensional string array:
int [,] numbers;
string [,,] words;
Let’s have a look at an example. First, declare and instantiate a two-dimensional integer array
the2d, with five “rows” and three “columns”:
const int rows = 5;
const int cols = 3;
int [,] the2d = new int [rows, cols];
Next, populate the array by assigning as a value to each element its row times its column:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
 the2d[i,j] = i * j;
}
}
Next, iterate through both dimensions of the array. For each element, create a string consisting of
its coordinates in the array followed by its value, and add it to a ListBox:
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
 string theItem = "the2d [" + i.ToString() + "," + j.ToString() +
  "] is "
  + the2d[i,j].ToString() + ".";
 lstMulti.Items.Add(theItem);
}
}
If you run the code in the listing, you’ll see that the contents of the array is displayed in
the ListBox.
Listing: Creating and Displaying a Two-Dimensional Array
private void btnMulti_Click(object sender, System.EventArgs e) {
const int rows = 5;
const int cols = 3;
// declare 5X3 array
int [,] the2d = new int [rows, cols];
// populate the array
for (int i = 0; i < rows; i++) {
 for (int j = 0; j < cols; j++) {
  the2d[i,j] = i*j;
 }
}
// display it
for (int i = 0; i < rows; i++) {
 for (int j = 0; j < cols; j++) {
  string theItem = "the2d [" + i.ToString() + "," + j.ToString()
   + "] is " + the2d[i,j].ToString() + ".";
  lstMulti.Items.Add(theItem);
 }
}
}
|
|
Search Engine Optimization
 
Syndication Viewer
Our Web host:
IX WebHosting
|