Creating and Using Arrays - Example

This section provides a tutorial example on how to create and use an array.

The following program is a good illustration of the different array syntaxes:

```// Arrays.cs
// Copyright (c) 2015, HerongYang.com, All Rights Reserved.

class Arrays {
static void Main() {
int[] primes;
primes = new int[10];
primes[0] = 2;
primes[2] = 5;
System.Console.WriteLine("The 3rd prime number is: {0}",
primes[2]);
double[] temperatures = new double[3];
temperatures[0] = 70.0;
temperatures[1] = 75.0;
temperatures[2] = 73.5;
System.Console.WriteLine("Forecast for tomorrow's high"
+ " temperature: {0}", temperatures[2]);
}
}
```

Output:

```The 3rd prime number is: 5
Forecast for tomorrow's high temperature: 73.5
```

Please note that:

• The first element has an index of 0, not 1.
• You don't have to assign values to all array elements. primes[1] has no value
• in the above program.
• You will get an outside-the-bounds error, if you try to use primes[10], because
• you are trying to access the 11th position of the array, which doesn't exist.
• We are allowed to join the assignment with the declaration statement, like "double[] temperatures = new double[3];".

Last update: 2015.

Table of Contents