Arrays in Csharp

download Arrays in Csharp

of 41

Transcript of Arrays in Csharp

  • 8/6/2019 Arrays in Csharp

    1/41

    Arrays in C#

    Prepared By:

    Esha Batish

    Lecture No-25Date-26-04-2011

  • 8/6/2019 Arrays in Csharp

    2/41

    Introduction to Arrays

    An array is a collection of variables of thesame type that are referred to by a common

    name.

    The principal advantage of an array is that it

    organizes data in such a way that it can be

    easily manipulated.

    Arrays can be One dimensional, Two

    Dimensional or Multi-Dimensional.

    Commonly used are One dimensional, Two

    Dimensional. Contd..

  • 8/6/2019 Arrays in Csharp

    3/41

    Although arrays in C# can be used just likearrays in many other programming languages,they have one special attribute: They areimplemented as objects. By implementingarrays as objects, several important advantages

    are gained, such as they are automaticallygarbage-collected.

    In C#, arrays can be declared as fixed length ordynamic.

    The array name behave as constant pointer which hold the reference of first element ofarray. Contd..

  • 8/6/2019 Arrays in Csharp

    4/41

    Arrays are represented using Dimensions i.e.[]

    Such as : DataType[] ArrayName;DataType describe the type of elements array is

    going to store in it.

    In Memory, Array is used to store in sequentialmanner. (Fig.1 Arrays in Memory)

    Array Name

    Index ElementBase Address

  • 8/6/2019 Arrays in Csharp

    5/41

    Array Declaration & Intialization

    An array is declared by defining the type of elements inside the array followed by emptybrackets and a variable name in c#. Such as:

    For e.g. int[] myArray;

    This myArray is going to store integral valueand name of the array will hold the baseaddress of the array elements.

    Memory must be allocated to hold all theelements of the array. An array is a referencetype, so memory on the heap must beallocated. Contd..

  • 8/6/2019 Arrays in Csharp

    6/41

    The process of allocation of memory to

    declared array is called Array Initialization.

    Initialization is done with new keyword such

    as

    myArray=new int[4];

    The Declaration and initialization can be done

    in single line also:

    int[] myArray=new int[4];

    This statement will force compiler to instruct

    Operating System to allocation memory for 4

    elements; each having 4bytes to store. Contd..

  • 8/6/2019 Arrays in Csharp

    7/41

    Memory Representation

    Name of the array is value type but it isallocated memory using new keyword so

    memory allocated is on Heap.(Fig2.Memory

    for myArray). Its a Single-Dimension Array.

  • 8/6/2019 Arrays in Csharp

    8/41

    You can also assign values to every array

    element using an array initializer. Array

    initializers can be used only while declaring an

    array variable, not after the array is declared:

    int[] myArray = new int[] {4, 7, 11, 2};

    In this case there is no need to specify the size

    as size is evaluated with number of elements

    passed in {}.

    Using curly brackets you can write the arraydeclaration and initialization. Contd..

  • 8/6/2019 Arrays in Csharp

    9/41

    int[] myArray = {4, 7, 11, 2};

    Accessing Array Elements: Elements of anarray is accessed using index element in

    dimensions.

    int[] myArray = new int[] {4, 7, 11, 2}; int v1 = myArray[0]; // read first element

    int v2 = myArray[1]; // read second element

    myArray[3] = 44; // change fourth element

    Contd..

  • 8/6/2019 Arrays in Csharp

    10/41

    If you use a wrong indexer value where no

    element exists, an exception of type

    IndexOutOfRangeException is thrown.

    If you don t know the number of elements in

    the array, you can use the Length property that

    is used in this for statement:

    for (int i = 0; i < myArray.Length; i++)

    {

    Console.WriteLine(myArray[i]);

    } Contd..

  • 8/6/2019 Arrays in Csharp

    11/41

    Instead of using a for statement to iterate

    through all elements of the array, you can alsouse the foreach statement:

    foreach (int val in myArray)

    { Console.WriteLine(val);

    }

  • 8/6/2019 Arrays in Csharp

    12/41

    Using Reference TypesIn stead of declaring arrays of predefinedtypes, you can also declare arrays of custom

    types. Lets Person is a user defined class, we

    can create array of this class such as:

    Person[] Per = new Person[2];

    This array will hold memory for the data of

    objects of Person class.

    If elements of an array is of reference type

    then memory should be allocated, otherwise

    NullReferenceException is thrown. Contd..

  • 8/6/2019 Arrays in Csharp

    13/41

    You can allocate every element of the array byusing an indexer starting from 0:

    Per[0] = new Per ();

    Per[1] = new Per(); e.g.

    class Program

    {

    static void Main(string[] args)

    {

    person[] myPerson = new person[2];myPerson[0] = new person(3);

    myPerson[1] = new person(4); Contd..

  • 8/6/2019 Arrays in Csharp

    14/41

    myPerson[0].dis();

    myPerson[1].dis();

    Console.ReadKey();

    }

    }

    class person{

    int x;

    public person(int x){

    this.x = x;

    } Contd..

  • 8/6/2019 Arrays in Csharp

    15/41

    public void dis()

    {Console.WriteLine(x);

    }

    }

    Output:

    3

    4

  • 8/6/2019 Arrays in Csharp

    16/41

    Memory Representation

  • 8/6/2019 Arrays in Csharp

    17/41

    Multi-Dimensional Array

    Ordinary arrays (also known as one -dimensional arrays) are indexed by a single

    integer. A multidimensional array is indexed

    by two or more integers. Array with 2dimension usually represent rows and

    columns.

    A is a 2d array.

  • 8/6/2019 Arrays in Csharp

    18/41

    Declaring this two - dimensional array with C#

    is done by putting a comma inside the

    brackets. The array is initialized by specifying

    the size of every dimension (also known as

    rank). Then the array elements can be accessed

    by using two integers with the indexer: int[,] a= new int[3, 3];

    Here 2D array contains 3 rows and 3 columns.

    Values can be initialize as: Contd..

  • 8/6/2019 Arrays in Csharp

    19/41

    a[0,0]=2;

    a[2,3]=9; Another way to initialize 2D array is:

    int[,] a = {

    {1, 2, 3},

    {4, 5, 6},

    {7, 8, 9}

    };

    When using an array initializer, you mustinitialize every element of the array. It is notpossible to leave the initialization of some valuesfor later.

  • 8/6/2019 Arrays in Csharp

    20/41

    Three-Dimensional Array

    By using two commas inside the brackets, youcan declare a three - dimensional array:

    int[,,] threedim = {

    { { 1, 2 }, { 3, 4 } },

    { { 5, 6 }, { 7, 8 } },

    { { 9, 10 }, { 11, 12 } }

    };

    Console.WriteLine(threedim[0, 1, 1]);

    Contd..

  • 8/6/2019 Arrays in Csharp

    21/41

    Jagged Arrays

    A jagged array is more flexible in sizing thearray. With a jagged array every row can have

    a different size.

    Each row of jagged array can have differentnumber of elements. Lets compare with 2D

    arrays.

  • 8/6/2019 Arrays in Csharp

    22/41

    A jagged array is declared by placing one pair ofopening and closing brackets after another. With

    the initialization of the jagged array, only the sizethat defines the number of rows in the first pair ofbrackets is set. The second brackets that define thenumber of elements inside the row are kept empty

    because every row has a different number of elements. Next, the element number of the rowscan be set for every row:

    int[][] jagged = new int[3][];

    jagged[0] = new int[2] { 1, 2 };

    jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };

    jagged[2] = new int[3] { 9, 10, 11 };

  • 8/6/2019 Arrays in Csharp

    23/41

    Iterating through all elements of a jagged arraycan be done with nested for loops. In the outer for

    loop every row is iterated, and the inner for loopiterates through every element inside a row.

    for (int row = 0; row < jagged.Length; row++)

    { for (int element = 0; element