Thursday, May 13, 2010

Arrays


Arrays in C#


Array Declaration :
An Array is a collection of values of a similar data type. Technically, C# arrays are a reference type. Each array in C# is an object and is inherited from the System.Array class. Arrays are declared as:

[] = new [];

Let's define an array of type int to hold 10 integers.

int [] integers = new int[10];

The size of an array is fixed and must be defined before using it. However, you can use variables to define the size of the array:

int size = 10;
int [] integers = new int[size];

You can optionally do declaration and initialization in separate steps:

int [] integers;
integers = new int[10]

It is also possible to define arrays using the values it will hold by enclosing values in curly brackets and separating individual values with a comma:

int [] integers = {1, 2, 3, 4, 5}

This will create an array of size 5, whose successive values will be 1, 2, 3, 4 and 5.

Accessing the values stored in an array

To access the values in an Array, we use the indexing operator [int index]. We do this by passing an int to indicate which particular index value we wish to access. It's important to note that index values in C# start from 0. So if an array contains 5 elements, the first element would be at index 0, the second at index 1 and the last (fifth) at index 4. The following lines demonstrate how to access the 3rd element of an array:

int [] intArray = {5, 10, 15, 20};
int j = intArray[2];

PROGRAM :


// demonstrates the use of arrays in C#
static void Main()
{
    // declaring and initializing an array of type integer
    int [] integers = {3, 7, 2, 14, 65};
    // iterating through the array and printing each element
    for(int i=0; i<5; i++)
    {
        Console.WriteLine(integers[i]);
    }
}

Here we used the for loop to iterate through the array and the Console.WriteLine() method to print each individual element of the array. Note how the indexing operator [] is used.

The above program is quite simple and efficient, but we had to hard-code the size of the array in the for loop. As we mentioned earlier, arrays in C# are reference type and are a sub-class of the System.Array Class. This class has lot of useful properties and methods that can be applied to any instance of an array that we define. Properties are very much like the combination of getter and setter methods in common Object Oriented languages.

Properties are context sensitive, which means that the compiler can un-ambiguously identify whether it should call the getter or setter in any given context. We will discuss properties in detail in the coming lessons. System.Array has a very useful read-only property named Length that can be used to find the length, or size, of an array programatically.

 Using the Length property, the for loop in the above program can be written as:

for(int i=0; i
{
Console.WriteLine(integers[i]);
}

This version of looping is much more flexible and can be applied to an array of any size and of any data-type. Now we can understand the usual description of Main(). Main is usually declared as:

static void Main(string [] args)

The command line arguments that we pass when executing our program are available in our programs through an array of type string identified by the args string array. 



Arrays More Explained:

An array is a data structure that contains a number of variables. These are accessed through computed indices. C# supports one-dimensional arrays, multidimensional arrays (rectangular arrays) and arrays of arrays (jagged arrays). As C, C++ and Java C# arrays are zero indexed. This means the array indexes start as zero. 

When declaring arrays, the square bracket [] must come after the type, not the identifiers, for example int[] table. 

The size of the array is not part of its type as it is in the C language. Thus

int[] numbers = new int[20];


Array Initialization :

 
int[] numbers = {0, 1, 2, 3, 5};


This is identical to the complete initialisation statement:
int[] numbers = new int[] {0, 1, 2, 3, 5}; 


In C# arrays are actually objects. System.Array is the abstract base type of all
array types. The class Array contains methods for sorting and searching. 


// myArray.cs
using System;
class myArray 

{

    public static void Main() 

    {
            int[] numbers = { 4, 12345, 890, 23456789 }; 
            int prod = numbers[2]*numbers[0]; 
            Console.Write("prod = " + prod); 
            Console.Write("\n"); 
            int numb = Array.BinarySearch(numbers,4); 
            Console.Write("numb = " + numb); 
            Console.Write("\n"); 
            double[] d = new double[3];
            d[0] = 1.1; d[1] = 3.4; d[2] = 8.9; 
            int dpos = Array.BinarySearch(d,8.9); 
            Console.Write("dpos = " + dpos);  
   }
           Console.Write("\n"); 

            string[] slist = { "otto", "uli", "carl", "marius", "jacob" };
            int pos1 = Array.BinarySearch(slist,"carl"); 

            Console.Write("pos1 = {0}",pos1); 
             Console.WriteLine();
             Array.Sort(slist); 

              // sorting the array int pos2 = Array.BinarySearch(slist,"carl");
             Console.Write("pos2 = {0}",pos2); Console.WriteLine();
             for(int j=0;j

            { 
                Console.WriteLine("{0} {1}",j,slist[j]); 
            }
}


To create multidimensional arrays the array initializer must have as many levels of nesting as there are dimensions in the array. Thus:


int[,] numbers = {{0, 2}, {4, 6}, {8, 10}, {12, 17}, {16, 18}};


The outermost nesting level corresponds to the leftmost dimension. The innermost nesting level corresponds to the rightmost dimension. The length of each dimension of the array is determined by the number of elements at the corresponding nesting level in the array initializer. Thus the example above creates a two-dimensional array with a length of five for the leftmost dimension and a length of two for the rightmost dimension. For example


int[,] numbers = new int[5,2];


and initialises the array with:


numbers[0,0] = 0; numbers[0,1] = 2;
numbers[1,0] = 4; numbers[1,1] = 6; 
numbers[2,0] = 8; numbers[2,1] = 10; 
numbers[3,0] = 12; numbers[3,1] = 14; 
numbers[4,0] = 16; numbers[4,1] = 18;


JAGGED ARRAYS :


Jagged arrays are arrays of arrays. The element arrays do not all have to be the same.


using System;
public class TwoDim 

{
         public static void Main() 

        { 
                int[][] matrix = new int[2][]; // rows 
                matrix[0] = new int[2]; // 
               columns matrix[1] = new int[2];  // columns 
               matrix[0][0] = 2; matrix[0][0] = 4; 
               matrix[1][0] = 7; matrix[1][1] = 3; 

                int i = 1; 
                Console.WriteLine("matrix[" + i + "][" + i + "] = " + matrix[i][i]);

                double[,] myarray; 

                myarray = new double[2,3]; 
                myarray[0,0] = 3.1; myarray[0,1] = 4.7; myarray[0,2] = 3.3; 
                myarray[1,0] = 2.7; myarray[1,1] = 1.1; myarray[1,2] = 7.3;
                double r = myarray[0,1]*myarray[1,2]; 
                Console.WriteLine("r = " + r); 
        } // end Main
}

No comments:

Post a Comment