FOR Statement

Help Contents

Introduction

The IEC 61131-3 Structured Text FOR statement executes a list of statements a defined number of times. The FOR statement has this syntax:

FOR variable := start-value TO end-value [ BY step-value ] DO
    statement;
    statement;
    ..
    statement;
END_FOR;

Where:

Execution Logic

The FOR Loop uses this logic to execute statements:

  1. The start-value is written to the variable.
  2. The variable is compared with the end-value.
  3. If the loop has finished, steps 4, 5 and 6 are skipped. Execution continues with the next statement after the END_FOR keyword.
  4. Each statement inside the loop is executed in order.
  5. The step-value is added to the variable.
  6. Execution continues with Step 2.

The condition used to end the loop depends on whether the step value is positive or negative:

To stop the FOR loop early (before the loop variable reaches its target value) use the EXIT Statement.

Example

The following example executes the loop 6 times:

Sum:= 0;
FOR Index := 0 TO 5 DO
    Sum := Sum + Item[ Index ];
END_FOR;

Note: When completed the Index loop variable will be 6.

Further Information

Structured Text

For other Structured Text (ST) statement types.

Variable Reference

To learn about variable references that can be used for the variable.

Expressions

To learn about expressions that can be used for start-value, end-value, and step-value.

Glossary

For the meaning of terms used in Fernhill SCADA.