Array dimension
In this chapter you will learn:
- Declare, create, and initialize the rectangular array
- Create and use two dimensional array
- Sum the values on a diagonal of a 3x3x3 matrix
- How to get array rank for two-dimensional array
Array with more than one dimension
The general form of a multidimensional array declaration:
type[, ...,] name = new type[size1, size2, ..., sizeN];
The following code declares a Two-Dimensional Array.
class MainClass/*ja va 2 s . c o m*/
{
static void Main()
{
int[,] cells = new int[3,3];
}
}
The general form of array initialization for a two-dimensional array is shown here:
type[,] array_name = {//from j a v a 2s. co m
{ val, val, val, ..., val },
{ val, val, val, ..., val },
.
.
.
{ val, val, val, ..., val }
};
The following code shows how to declare and initialize an three-dimensional array.
using System;/* ja va 2 s. com*/
class MainClass
{
static void Main()
{
int[,] arr = new int[2, 3] { { 0, 1, 2 }, { 10, 11, 12 } };
for (int i = 0; i < 2; i++){
for (int j = 0; j < 3; j++){
Console.WriteLine(arr[i, j]);
}
}
}
}
The code above generates the following result.
Two dimensional array
using System; // j a v a 2 s. c o m
class MainClass {
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();
}
}
}
The code above generates the following result.
3x3x3 matrix
using System; /*j a va 2 s . co m*/
class MainClass {
public static void Main() {
int[,,] m = new int[3, 3, 3];
int sum = 0;
int n = 1;
for(int x=0; x < 3; x++)
for(int y=0; y < 3; y++)
for(int z=0; z < 3; z++)
m[x, y, z] = n++;
sum = m[0,0,0] + m[1,1,1] + m[2, 2, 2];
Console.WriteLine("Sum of first diagonal: " + sum);
}
}
The code above generates the following result.
Array rank
using System;/* j av a 2s . c o m*/
class MainClass
{
public static void Main()
{
int[,,] intArray = new int [10, 5, 3];
intArray[1, 3, 2] = 3;
intArray[4, 1, 2] = 9;
Console.WriteLine("intArray.Rank (number of dimensions) = " +
intArray.Rank);
Console.WriteLine("intArray.Length (number of elements) = " +
intArray.Length);
for (int x = 0; x < intArray.GetLength(0); x++){
for (int y = 0; y < intArray.GetLength(1); y++){
for (int z = 0; z < intArray.GetLength(2); z++){
if (intArray[x, y, z] != 0){
Console.WriteLine("intArray[" + x + ", " + y + ", " + z +"] = " +
intArray[x, y, z]);
}
}
}
}
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Initializing a Jagged Array
- Length with jagged arrays
- Use foreach statement to loop through jagged array
Home » C# Tutorial » Array