Braintique.com header
Left Navigation Bar

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.

List Box

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);
}
}
}

Previous Table of Contents Next


Google
 
Web www.braintique.com
www.digitalfieldguide.com www.googleplexblog.com


Home | Barticles | Blogs | Books | Services | FAQ | Contact

© Braintique.com. All rights reserved.

Search Engine Optimization







RSS 2.0 Syndication feed

Syndication Viewer

Our Web host:
IX WebHosting



Food for Your Brain! Get a Barticle! Questions Answered Books for You What We Can Do For You Contact Us Brain Food Questions Answered Books for You What We Can Do For You Frequently Asked Questions About Us Google Research Photoshop Wi-Fi and Wireless Networking The Natural Way to Write