While Loops

<< Click to Display Table of Contents >>

Navigation:  Project > Scripts > ST language > Operators and Expressions in STL > Iteration with Repeating Loops >

While Loops

Previous pageReturn to chapter overviewNext page

The while loop is a little different from the FOR loop, because it is used to repeat the loop as long as some conditions are TRUE. A WHILE loop will repeat as long as a boolean expression evaluates to TRUE.Here’s the syntax of WHILE loops:

while (boolean expression){  

<statement>;

}

Between the parentheses are the boolean expression. If that boolean expression evaluates to TRUE, all the statements between braces {}will be executed. When } is reached, the boolean expression will be evaluated again. This will happen over and over again until the expression doesn’t evaluate to TRUE. But to make the loop stop at one point, you have to change a value in the boolean expression. Only in that way can the boolean expression go from TRUE to FALSE. Here’s an example of a WHILE loop in Structured Text:

counter = 0;

while (counter < 10){

 counter = counter + 1;

 machine_status = counter * 10;

}

If you look at the third line you will see how the loop will eventually stop repeating.  The boolean expression uses the counter variable and checks if its value is less than 10. But since the value of counter is set to 0 right before the WHILE loop, the boolean expression will be TRUE unless counter is changed. That is what’s happening in line 3. This is the first statement in the WHILE loop, and with the other statements, are executed each time the loop repeats. In the third line the value of the counter variable is increased by 1. You can say that the incremental value is 1. In the example above, the loop will repeat 10 times. When the value of count reaches 10, the boolean expression will be evaluated to FALSE (because 10 is not less than 10) and the loop will stop.

You can also use the BREAK keyword in the WHILE loop to stop repeating the loop before the boolean expression is FALSE. The syntax is an IF statement with the BREAK keyword in. Place it anywhere between braces {}.

if  (boolean expression) {

 break;

}