Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
swdev:dotnet:arrays [2011/04/08 11:18]
smayr
swdev:dotnet:arrays [2011/05/24 15:48] (current)
smayr [Resources]
Line 17: Line 17:
 <code csharp> <code csharp>
 // allocate memory // allocate memory
-int array[][] = new int[2][10];+int array[,] = new int[2][10];
  
 // use array // use array
 array[0,2] = 15; array[0,2] = 15;
 </code> </code>
 +
 +=== Getting Dimensions ===
 +
 +When traversing an array using loops, for example, there are a couple of ways to do it:
 +
 +<code csharp>
 +// Single Dimension
 +int SingleDimArr[] = new int[10];
 +for (int i = 0; i < SingleDimArr.Length; i++) // rows
 +{
 +    SingleDimArr[i, 0] = 0;
 +}
 +
 +// Multi-dimensions
 +int DoubleDimArr[,] = new int[2,10];
 +for (int i = 0; i < DoubleDimArr.GetLength(0); i++) // rows
 +{
 +    for (int j = 0; j < DoubleDimArr.GetLength(1); j++)  // columns
 +    {
 +        DoubleDimArr[i, j] = 0;
 +    }
 +}
 +</code>
 +
 +Alternatively, you can traverse without knowing dimensions if you simply need the array values:
 +<code csharp>
 +int[,] arr = new int[,] {{1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}};
 +foreach(int a[] in arr)
 +{
 +  foreach(int i in a)
 +  {
 +    Console.WriteLine(i);
 +  }
 +}
 +</code>
 +
 +== Resources ==
 +  * [[http://www.csharp-station.com/Tutorials/Lesson02.aspx|C# Tutorial: Lesson 2: Arrays]]
 +  * [[http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx|MSND: Arrays Tutorial]]