Arrays
- It has element of any one type.
- Elements are accessed with an index.
- Index start at zero.
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.
Initializing an Array :
so our friend name will be definitely in string format.
The Syntax goes as :
here,
string [] friend = new string[20];
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 :
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";
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;
}
{
return array[0]*2;
}
Output
-10
Square brackets are used for all arrays.
No comments:
Post a Comment