An array is a data structure consisting of a group of elements that are accessed by indexing. In most programming languages each element has the same data type and the array occupies a contiguous area of storage. Multi-dimensional arrays are accessed using more than one index: one for each dimension.
Array type
In ProTrader programming language arrays are set of the same type elements. Example, set of integer values like {1, 5, 11, 2, 4, 800, -45}. Arrays are useful for set of the same type data as price by day. See at table below:
Day of Trade | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
Avrg Price, $ | 15.8 | 15.88 | 15.87 | 16.03 | 15.95 | 15.92 | 15.84 | 15.81 | 18.72 |
The good ideas is describe Avrg Price as Array, but not individual variable for each price.
Array Creation
The general syntax:
double[5] price;
The construction above create array with five elements. The number of bracket pairs indicates the depth of array nesting. The maximal depth is 4, that means, you can create 4D arrays. The simple example of 2D array is table bellow:
4 | -1 | 5 |
6 | 7 | 2 |
6 | 4 | 0 |
The next array correspond to table above:
int[3][3] matrix;
matrix[0][0] = 4;
matrix[0][1] = -1;
matrix[0][2] = 5;
matrix[1][0] = 6;
matrix[1][1] = 7;
matrix[1][2] = 2;
matrix[2][0] = 6;
matrix[2][1] = 4;
matrix[2][2] = 0;
The default value for arrays from int, double, datetime and color elements is 0.
Note:The array can has elements only a same type.
Access to Elements of Array
The access to elements of array possible with next construction:
arrayName[Index]
The first element has index 0 (zero) (as in MQL4). So, the last element has index arraySize - 1. The bound of range create exception and program dump.
Example:
string[2] arr; // create 1D array with 2 elements
arr[0] = "white"; // set first element of array
arr[1] = ''black"; // set second element of array
// arr[2] = "unknown"; // illegal operation, because the third element of array doesn't exist
if( arr[0] == arr[1] ) // compare values of first and second elements of array
Using Array
The next code fragment calcs sum of elements of array:
const int size = 100; // 100 is the number of elements of array
int sum = 0;
int i = 0;
while( i < size )
{
sum += arr[i]; // or sum = sum + arr[i];
}
Comments