Friday, 23 October 2015

Array

Arrays 

  • It has element of any one type.
  • Elements are accessed with an index.
  • Index start at zero.

Consider you want to add all your friends name somewhere. Adding them like this


string frnd1 = "John";
string frnd2 = "Ram";
string frnd3 = "Rohit";

This format of adding information will be tedius and difficult to access and modified later.
Therefore, to achieve these types of goals where we need similar type of data to be put together the concept of Array came.

Array has the capability to store same type of data where you can access the required data by using index of array.

Initializing an Array : 


Let us create our friend list array ,
so our friend name will be definitely in string format.

The Syntax goes as :

 string [] friend = new string[20];
here,

first we define the datatype of our array : string
then the name of the array : friend
after that new operator to initialize a new array of type string with size of 20.

Note : These type of array are called 1-D arrays.

Assigning values to arrays : 


We can add our friend list to the array by many ways few of them are discussed :

1) At the time of initialization:

string[] friend = new string[] { "John","Ram", "Mohan"};
2) After initialization:

string[] friend = new string[5];friend[0] = "John";friend[1] = "Ram";friend[2] = "Mohan";


Example program that initialize and receives array parameter:



class Program {
static void Main()
{

//Three element array
int[] array = new array[]{-5,-6,7};

//Pass array to Method.
Console.WriteLine(Method(array));

}

//Recieves array parameter
static int Method(int[] array)
{
return array[0]*2;
}


Output 

-10

 Square brackets are used for all arrays.

No comments:

Post a Comment