Wednesday, 17 October 2012

One-Dimensional Array

To declare a one-dimensional array, you will use this general form:
type[ ] array-name = new type[size];
Here is an example:
The following creates an int array of ten elements and links it to an
array reference variable named sample:
int[] sample = new int[10];
This declaration works just like an object declaration. The sample variable holds a reference
to the memory allocated by new. This memory is large enough to hold ten elements of type
As with objects, it is possible to break the preceding declaration in two.
For example:
int[] sample;
sample = new int[10];

In this case, when sample is first created, it refers to no physical object. It is only after the
second statement executes that sample is linked with an array.

Demonstrate a one-dimensional array.
using System;
class ArrayDemo

public static void Main() 

int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1)
sample[i] = i;
for(i = 0; i < 10; i = i+1)
Console.WriteLine("sample[" + i + "]: " +sample[i]);

The output from the program is shown here:
sample[0]: 0
sample[1]: 1

sample[2]: 2
sample[3]: 3
sample[4]: 4
sample[5]: 5
sample[6]: 6
sample[7]: 7
sample[8]: 8
sample[9]: 9

No comments:

Post a Comment