Thursday, February 5, 2009

"Array"

An array is a series of elements of the same type placed in contiguous memory locations that can be individually referenced by adding an index to a unique identifier. That means that, for example, we can store 5 values of type int in an array without having to declare 5 different variables, each one with a different identifier. Instead of that, using an array we can store 5 different values of the same type, int for example, with a unique identifier.


For example, an array to contain 5 integer values of type int called billy could be represented like this:
0 1 2 3 4
billy ____
int

where each blank panel represents an element of the array, that in this case are integer values of type int. These elements are numbered from 0 to 4 since in arrays the first index is always 0, independently of its length.

First index (0)

0 1 2 3 4 5 6 7 8 9 -----indices

billy ____ __ Element (at indexes 8)

---------------Array length is 10-------------------


Array dimensions:

In the most of cases the Array has one dimension like the description above, but in some case the Array has more than one dimension (In MQL4 the maximum dimension is four dimensions).Multi-dimensional arrays are very like multi-column tables, where the first column is the first dimension of the Array and the second column is the second dimension of the Array etc.

Creating an Array:

The arrays must to be declared (like the variables) before using it in the code. Declaring an array means creating it by giving it a name (identifier), type and size. In MQL4 we are creating the Arrays like this:int myarray[50];

In the code above we declared one-dimensional array.int keyword indicates that the array is an array of integers.myarray is the name of the array (identifier).[] telling the compiler that we are declaring an array not an integer variable.50 is the size of the array.


We have now a one-dimensional array of 50 integersdouble myarray[5][40];

The line above is the way to declare two-dimensional of seven arrays each of them consisting of 40 doubles.Initializing the Array:Initializing an array (or a variable) means setting its value at the same declaration line.Look at this code which initializes one- dimensional array of 6 integers:

int myarray [6] = {1,4,9,16,25,36};


Example arrays
1-D: [ 3. 1. 4. 1.]
2-D:
[[1 2 3]
[4 5 6]]

3-D:
[[[ 1 2]
[ 3 4]
[ 5 6]]
[[ 7 8]
[ 9 10]
[11 12]]]

No comments: