Usually operators in the code of an expert advisor are executed successively – one by one. But often it is required to change the order of their execution depending on some conditions. In the previous article I considered one of the ways to change this order – the conditional operator if-else. The usage of this operator is justified if it is required to execute two different execution sequences depending on some condition.
In this article I’m going to speak about the while loop operator. The name itself says that this operator is used in cases when it is required to repeat the same sequence of operators for n times.
The while loop operator format:
while (expression)
operator;
Each time before the «operator» is executed the value of the «expression» is evaluated. If the «expression» is true, then the «operator» will be executed. This repeats until the condition becomes false. Once it becomes false the loop terminates and control will be given to the operator that follows the while loop.
The while loop may never be executed if the «expression» was false initially (at the first evaluation).
If not one but several operators are required to be executed in the body of the loop, a compound operator is used, i.e. it is necessary to enclose several operators in braces {}. After the closing brace} there mustn’t be a semicolon.
Unfortunately I don’t use the while lopp in our first expert advisor, that’s why I’ll have to invent an example of its usage.
int i = 0;
while ( i < 9 )
{
Print( i );
i++;
}
Print ("Done");
At the first evaluation the «expression» (i<9) will be true (as 0<9) and the compound operator, which consists of the Print function (output of information in the experts' log) that will output number 0 in the log, and of the operator i++, which increment the variable i by one, will be executed.
Then the statement i<9 will be calculated one more time. This time it will be true again. As a result the current value of the variable I (i.e. 1) will be output in the log file, and after that the value of the variable will be increased by one and will become equal to 2. The loop will be repeated until the value of the variable i becomes equal to 9. Then the expression i<9 will become false, the loop will terminate and the control will be passed to the following operator:
Print ("Done");
Next article: "
For loop"