Multi Dimensional Arrays

Started by thiruvasagamani, Jul 11, 2008, 02:20 PM

Previous topic - Next topic

thiruvasagamani

Multi Dimension Arrays

A multidimensional array is an array with more than one dimension. A multi dimension array is declared as following:

string[,] strArray;

After declaring an array, you can specify the size of array dimensions if you want a fixed size array or dynamic arrays. For example, the following code two examples create two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items respectively.

int[,] numbers = new int[3, 2] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[2, 2] { {"Rosy","Amy"}, {"Peter","Albert"} };

If you don't want to specify the size of arrays, just don't define a number when you call new operator. For example,

int[,] numbers = new int[,] { {1, 2}, {3, 4}, {5, 6} };
string[,] names = new string[,] { {"Rosy","Amy"}, {"Peter","Albert"} };

You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example:

int[,] numbers = { {1, 2}, {3, 4}, {5, 6} };
string[,] siblings = { {"Rosy", "Amy"}, {"Peter", "Albert"} };

Jagged Arrays


Jagged arrays are often called array of arrays. An element of a jagged array itself is an array. For example, you can define an array of names of students of a class where a name itself can be an array of three strings - first name, middle name and last name. Another example of jagged arrays is an array of integers containing another array of integers. For example,

int[][] numArray = new int[][] { new int[] {1,3,5}, new int[] {2,4,6,8,10} };

Again, you can specify the size when you call the new operator.

Mixed Arrays

Mixed arrays are a combination of multi-dimension arrays and jagged arrays. Multi-dimension arrays are also called as rectangular arrays.

Accessing Arrays using foreach Loop

The foreach control statement (loop) of C# is a new to C++ or other developers. This control statement is used to iterate through the elements of a collection such as an array. For example, the following code uses foreach loop to read all items of numArray.

int[] numArray = {1, 3, 5, 7, 9, 11, 13};
foreach (int num in numArray)
{
System.Console.WriteLine(num.ToString());
}
Thiruvasakamani Karnan