Monday, October 17, 2011

Arrays

An array says your book, "represents a fixed number of elements of the same type." An array, for instance can be a set of integers or a set of doubles or strings. The set can be accessed under a single variable name.

You use square brackets [] to signify an array. The following declares an array of integers with 5 elements

int[] myArray=new int[5];

Each element in an array has an index number. We can use these indexes to assign or access values in an array. Indexes always begin with 0

myArray[0]=5;
myArray[1]=12;
myArray[2]=7;
myArray[3]=74;
myArray[4]=9;

Console.WriteLine("The fourth element of the array is {0}",myArray[3]);

Here is another way to declare an array. This declaration declares a string array and assigns the values at the moment when the array is created

string[ ] weekdays =new string[ ]
       {"Monday","Tuesday","Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

The values are still indexed 0 to 6


Array work naturally with loops. You can easily use a loop to assign values:


for (int i=0; i<size;i++)
{
     Console.WriteLine("Enter an Integer");
     myArray[i]=int.Parse(Console.ReadLine());

}

Arrays can be passed as a parameter to methods and they can be returned by a method.

private void CreateArray()
{
    double[ ] payments = new double[5];
    FillArray(payments, 5);
}

private void FillArray(double[ ] pmts, int size)
{
    int x=0;
   while (x < size)
  {
     Console.WriteLine("Enter Payment Amount");
     pmts[x]=double.Parse(Console.ReadLine());
     x++;
  }
}

No comments:

Post a Comment