Saturday, 2 July 2016

C sharp Array

Normally, array is a collection of similar type of elements that have contiguous memory location.
 Array is an object that contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a C# array.
Array is a reference type variable.
The new keyword is used to create an instance of an array.
You can assign values to each element of the array by using the index number.
Index number is also called the array subscript of the element.
An example of assigning values to an array:

int[] Score = new int[10];

Score[8]=10;

Array in C# is index based, first element of the array is stored at 0 index.

Advantage of  C# Array
  • Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
  • Random access: We can get any data located at any index position.
Disadvantage of C#  Array
  • Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.



For example Sometimes, you need to declare multiple variable of same data type. It is complex and time consuming process. Suppose you have to declare 100 integer type of variable then what would you do? Will you declare variable as follow:

 int num1,num2,num3,num4,num5,num6,num7,num8.... num100;

It is not a suitable way to declare multiple variable of same data type. To overcome this situation, array came alive. An array is a collection of same data type. If you have to declare 100 variable of same data type in C#, then you can declare and initialize an array as follow.


int[] num = new int[100];


Types of Array
There are two types of array.
Ø  Single Dimensional Array
Ø  Multidimensional array

Single Dimensional Array: Single dimensional array stores data in a row.



The one dimensional array or single dimensional array in C# is the simplest type of array that contains only one row for storing data. It has single set of square bracket (“[]”). To declare single dimensional array in C#, you can write the following code.
       
using System;

namespace single_Dimensional_Array
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declaring single dimensional array
            string[] station = new string[5];
            station[0] = "Goregaon";
            station[1] = "Kandivali";
            station[2] = "Malad";
            station[3] = "Andheri";
            station[4] = "Vileparle";

            Console.WriteLine("All the element of Books array is:\n\n");
            int i = 0;
            for (i = 0; i < 5; i++)
            {
                Console.Write("index {0}  -  {1}\n",i ,station[i]);
            }
            Console.ReadLine();
        }
    }
}


Multidimensional array: Multidimensional array stores data in more than one row (dimension).


The multi-dimensional array in C# is such type of array that contains more than one row to store data on it. The multi-dimensional array is also known as rectangular array in c sharp because it has same length of each row. It can be two dimensional array or three dimensional array or more. It contains more than one coma (,) within single rectangular brackets (“[,]”). To storing and accessing the elements from multidimensional array, you need to use nested loop in program. The following example will help you to figure out the concept of multidimensional array.
Example
using System;

namespace multi_dimensional_array
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, j;
            //Declaring multi dimensional array
            string[,] name = new string[3, 3];
            for (i = 0; i < 3; i++)
            {
                for (j = 0; j < 3; j++)
                {
                 Console.Write("\nEnter Book Name for {0}. Row and {1}. column:\t", i + 1, j + 1);
                 name[i, j] = Console.ReadLine();
                }
            }

            Console.WriteLine("\n\n=========================");
            Console.WriteLine("All the element of Books array  is:\n\n");

            //Formatting Output
            Console.Write("\t1\t2\t3\n\n");
            //outer loop for accessing rows
            for (i = 0; i < 3; i++)
            {
                Console.Write("{0}.\t", i + 1);

                //inner or nested loop for accessing column of each row
                for (j = 0; j < 3; j++)
                {
                 Console.Write("{0}\t", name[i, j]);
                }
                Console.Write("\n");
            }
            Console.WriteLine("\n\n=========================");
            Console.ReadLine();
        }
    }
}


Properties of the Array

Properties
Explanation
Length
Returns the length of array. Returns integer value.
Rank
Returns total number of items in all the dimension. Returns integer value.
IsFixedSize
Check whether array is fixed size or not. Returns Boolean value
IsReadOnly
Check whether array is ReadOnly or not. Returns Boolean value
Example
using System;
class Program
{

    static void Main(string[] args)
    {
        //Initializing and storing value in arr1
        int[] data = new int[5] { 43, 25, 33, 14, 5 };
     
        int len, rank;
        bool fixedsize, read_only;
        Console.WriteLine("\nElements of array is:\n");
        foreach (int i in data)
        {
            Console.Write("{0}\n", i);
        }
     

        //Check array length
        len = data.Length;
        Console.WriteLine("\nLength:\t{0}", len);

        //Check array rank
        rank = data.Rank;
        Console.WriteLine("Rank:\t{0}", rank);

        //Check whether array is fixed size or not
        fixedsize = data.IsFixedSize;
        Console.WriteLine("Fixed Size:\t{0}", fixedsize);

        //Check whether array is read only or not
        read_only = data.IsReadOnly;
        Console.WriteLine("Read Only:\t{0}", read_only);
        Console.ReadLine();
    }
}

 functions of Array
Function
Explanation
Sort
Sort an array
Clear
Clear an array by removing all the items
GetLength
Returns the number of elements
GetValue
Returns the value of specified items
IndexOf
Returns the index position of value
Copy
Copy array elements to another elements
Example
using System;
class Program
{

    static void Main(string[] args)
    {
        //Initializing and storing value in arr1
        int[] data = new int[5] { 43, 25, 33, 14, 5 };
        int[] data1 = new int[5] { 43, 25, 33, 14, 5 };

        Array.Sort(data);
        Console.WriteLine("\nElements of array is:\n");
        foreach (int i in data)
        {
            Console.Write("\t{0}", i);
        }
        Console.WriteLine("\n");

        //Returning Lenght from specified position
        Console.WriteLine("Get Length:\t{0}", data.GetLength(0));

        //Returns value of specied position
        Console.WriteLine("Get Value:\t{0}", data.GetValue(2));

        //Returns Index position of specified value
        Console.WriteLine("Get Index:\t{0}", Array.IndexOf(data, 33));

        //Copying arr1's items to arr2
        Array.Copy(data, data1, 5);
        Console.WriteLine("\nElements of new array after Copying :\n");
        foreach (int i in data1)
        {
            Console.Write("\t{0}", i);
        }
        Console.WriteLine("\n");

        //Removing items from array.
        Array.Clear(data, 0, 5);
        Console.WriteLine("\nElements of array Removing :\n");
        foreach (int i in data)
        {
            Console.Write("\t{0}", i);
        }
        Console.WriteLine("\n");

        Console.ReadLine();
    }
}









No comments:

Post a Comment