Thursday, 18 October 2012

Two-Dimensional Arrays

To declare a two-dimensional integer array table of size 10, 20, you would write
int[,] table = new int[10, 20];
Pay careful attention to the declaration. Notice that the two dimensions are separated from
each other by a comma. In the first part of the declaration, the syntax
[,]
indicates that a two-dimensional array reference variable is being created. When memory
is actually allocated for the array using new, this syntax is used:
int[10, 20]
This creates a 10×20 array, and again, the comma separates the dimensions.
To access an element in a two-dimensional array, you must specify both indices,
separating the two with a comma. For example, to assign location 3, 5 of array table
the value 10, you would use
table[3, 5] = 10;
Demonstrate a two-dimensional array:
using System;
class TwoD {
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();
     }
  }
}

In this example, table[0, 0] will have the value 1, table[0, 1] the value 2, table[0, 2] the
value 3, and so on. The value of table[2, 3] will be 12.

Wednesday, 17 October 2012

One-Dimensional Array

To declare a one-dimensional array, you will use this general form:
type[ ] array-name = new type[size];
Here is an example:
The following creates an int array of ten elements and links it to an
array reference variable named sample:
int[] sample = new int[10];
This declaration works just like an object declaration. The sample variable holds a reference
to the memory allocated by new. This memory is large enough to hold ten elements of type
int.
As with objects, it is possible to break the preceding declaration in two.
For example:
int[] sample;
sample = new int[10];

In this case, when sample is first created, it refers to no physical object. It is only after the
second statement executes that sample is linked with an array.

Demonstrate a one-dimensional array.
using System;
class ArrayDemo

 {
public static void Main() 

{
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
Console.WriteLine("sample[" + i + "]: " +sample[i]);
   }
}

The output from the program is shown here:
sample[0]: 0
sample[1]: 1

sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9