Skip to main content

Loop Statements Overview

FOR…DO…END_FOR;

Syntax

FOR Counter := Start_Value TO Limit_Value [BY Step_Value] DO
Statements
END_FOR;

Rules

  • BY is optional; if not specified, it defaults to 1.

  • If BY equals 0, a runtime error occurs.

  • Start_Value, Limit_Value, and Step_Value are evaluated once when the loop begins.

  • Positive steps run ascending; negative steps run descending.

  • The loop counter is read-only within the body.

  • Only integer expressions are allowed for counter and step.

Example

// Ascending loop (default BY 1)
Sum_Result := 0;
FOR Counter := 1 TO 5 DO
Sum_Result := Sum_Result + Counter;
END_FOR;
// Result: Sum_Result = 15

// Descending loop
Reverse_Sum := 0;
FOR Counter := 5 TO 1 BY -1 DO
Reverse_Sum := Reverse_Sum + Counter;
END_FOR;
// Result: Reverse_Sum = 15

WHILE…DO…END_WHILE;

Syntax

WHILE Condition DO
Statements
END_WHILE;

Rules

  • The condition is checked before each iteration.

  • The body executes only while the condition is TRUE.

  • If the condition never changes, the loop never ends.

Example

Value_Now := 0;
WHILE Value_Now < 5 DO
Value_Now := Value_Now + 1;
END_WHILE;
// Result: Value_Now = 5

REPEAT…UNTIL…END_REPEAT;

Syntax

REPEAT
Statements
UNTIL Condition
END_REPEAT;

Rules

  • The body runs once before checking the condition.

  • The loop ends when the condition becomes TRUE.

Example

Cycle_Count := 0;
REPEAT
Cycle_Count := Cycle_Count + 1;
UNTIL Cycle_Count >= 3
END_REPEAT;
// Result: Cycle_Count = 3

Boolean Conditions Must Be BOOL

Studio's Structured Text compiler requires loop and branch conditions to evaluate to BOOL. When working with numeric flags, compare them to an explicit value (or convert them) before using them in a condition.

Is_Active := 1; // Numeric flag
WHILE Is_Active <> 0 DO
Is_Active := 0; // Clear the flag and exit next iteration
END_WHILE;

Early Termination with EXIT;

Exits the innermost loop immediately.

FOR Task_Index := 1 TO 5 DO
IF Task_Index = 3 THEN
EXIT;
END_IF;
END_FOR;
// Result: Task_Index = 3 because EXIT stops before the BY step runs
Loop_Index := 0;
WHILE Loop_Index < 10 DO
IF Loop_Index = 3 THEN
EXIT; // Leave the loop once the target is reached
END_IF;
Loop_Index := Loop_Index + 1;
END_WHILE;
// Result: Loop_Index = 3

Summary Table

ConstructCondition CheckedOne Iteration GuaranteedSupports BYEarly ExitTypical Use
FOR…DO…END_FOR;Fixed rangeNoYes (default = 1)YesCounted iteration or array processing
WHILE…DO…END_WHILE;Before bodyNoNoYesRepetition while condition is true
REPEAT…UNTIL…END_REPEAT;After bodyYesNoYesDo-once-then-check or retry logic