Bird
Raised Fist0
PLC Programmingscripting~15 mins

FOR and WHILE loops in PLC Programming - Deep Dive

Choose your learning style10 modes available
Overview - FOR and WHILE loops
What is it?
FOR and WHILE loops are instructions in PLC programming that repeat a set of actions multiple times. A FOR loop repeats a fixed number of times, while a WHILE loop repeats as long as a condition is true. They help automate repetitive tasks without writing the same code again and again.
Why it matters
Without loops, programmers would have to write the same instructions many times, making programs long, hard to read, and error-prone. Loops save time, reduce mistakes, and make automation efficient and flexible. In industrial machines, this means faster, safer, and more reliable control.
Where it fits
Before learning loops, you should understand basic PLC instructions and how to write simple sequential code. After mastering loops, you can learn about nested loops, conditional branching, and advanced control structures like state machines.
Mental Model
Core Idea
Loops repeat instructions automatically, either a set number of times (FOR) or while a condition stays true (WHILE), to handle repetitive tasks efficiently.
Think of it like...
Using a FOR loop is like setting a timer to water plants exactly 5 times, while a WHILE loop is like watering plants as long as the soil is dry.
┌─────────────┐       ┌─────────────┐
│   Start     │       │   Start     │
└─────┬───────┘       └─────┬───────┘
      │                     │
      ▼                     ▼
┌─────────────┐       ┌─────────────┐
│ Initialize  │       │ Check       │
│ counter     │       │ condition   │
└─────┬───────┘       └─────┬───────┘
      │                     │
      ▼                     ▼
┌─────────────┐       ┌─────────────┐
│ Check if    │       │ Condition   │
│ counter < N │       │ true?       │
└─────┬───────┘       └─────┬───────┘
      │ Yes                 │ Yes
      ▼                     ▼
┌─────────────┐       ┌─────────────┐
│ Execute     │       │ Execute     │
│ loop body   │       │ loop body   │
└─────┬───────┘       └─────┬───────┘
      │                     │
      ▼                     ▼
┌─────────────┐       ┌─────────────┐
│ Increment   │       │ Re-check    │
│ counter     │       │ condition   │
└─────┬───────┘       └─────┬───────┘
      │                     │
      ▼                     │
┌─────────────┐             │
│ Repeat or   │◄────────────┘
│ exit loop   │
└─────────────┘
Build-Up - 6 Steps
1
FoundationUnderstanding Basic Loop Purpose
🤔
Concept: Loops automate repeating tasks to avoid writing the same code multiple times.
Imagine you want a PLC to turn a motor on and off 10 times. Without loops, you'd write the on/off commands 10 times. Loops let you write this once and repeat it automatically.
Result
You can repeat actions efficiently without code duplication.
Understanding that loops save effort and reduce errors is the first step to writing cleaner, more maintainable PLC programs.
2
FoundationFOR Loop Structure Basics
🤔
Concept: A FOR loop repeats a block of code a fixed number of times, controlled by a counter.
In PLC languages, a FOR loop usually has a start value, an end value, and an increment step. The loop runs from start to end, increasing the counter each time. For example, FOR i = 1 TO 5 means repeat 5 times.
Result
The loop runs exactly the number of times specified.
Knowing that FOR loops count through a range helps you plan how many times your task repeats.
3
IntermediateWHILE Loop Condition Control
🤔Before reading on: do you think a WHILE loop always runs at least once or only if the condition is true? Commit to your answer.
Concept: A WHILE loop repeats as long as a condition remains true, checking before each repetition.
WHILE loops check a condition before running the loop body. If the condition is false at the start, the loop body never runs. For example, WHILE sensor_active DO keep motor running.
Result
The loop runs zero or more times depending on the condition.
Understanding that WHILE loops may not run at all if the condition is false prevents logic errors in your control flow.
4
IntermediateCombining Loop Counters and Conditions
🤔Before reading on: can a FOR loop be stopped early by a condition inside it? Commit to yes or no.
Concept: Loops can include conditions inside to break early or skip steps, adding flexibility.
Inside a FOR or WHILE loop, you can add IF statements to check extra conditions. For example, in a FOR loop counting 1 to 10, you can stop early if a fault occurs using a BREAK instruction.
Result
Loops become more adaptable to real-time situations.
Knowing loops can be controlled internally helps you handle unexpected events without rewriting the whole loop.
5
AdvancedNested Loops for Complex Repetition
🤔Before reading on: do you think nested loops multiply the total repetitions or just add them? Commit to your answer.
Concept: Loops can be placed inside other loops to repeat multi-step processes multiple times.
A nested loop runs the inner loop completely for each iteration of the outer loop. For example, an outer FOR loop runs 3 times, and an inner FOR loop runs 2 times, resulting in 6 total repetitions.
Result
You can automate complex, repeated sequences efficiently.
Understanding nested loops unlocks powerful automation patterns for multi-dimensional tasks.
6
ExpertLoop Performance and Safety in PLCs
🤔Before reading on: do you think infinite loops are safe in PLCs if they have conditions inside? Commit to yes or no.
Concept: Loops must be carefully designed to avoid infinite cycles and ensure real-time safety in PLC control.
In PLCs, loops that never end or take too long can freeze the system or cause unsafe states. Experts use watchdog timers, loop counters, and condition checks to prevent this. Also, some PLC languages limit loop execution time per scan cycle.
Result
PLC programs remain responsive and safe during operation.
Knowing the risks and controls around loops in PLCs is critical to building reliable industrial automation.
Under the Hood
PLCs execute loops by repeatedly running the loop body instructions while updating counters or checking conditions each scan cycle. The PLC scan cycle reads inputs, executes logic including loops, and updates outputs. Loop counters are stored in memory registers, and condition checks are evaluated every cycle to decide continuation or exit.
Why designed this way?
Loops in PLCs are designed to fit the scan cycle model, ensuring deterministic and repeatable control. Fixed iteration FOR loops provide predictable timing, while WHILE loops offer flexibility for condition-based repetition. Safety and real-time constraints shaped these designs to prevent uncontrolled looping.
┌───────────────┐ Scan Cycle Start
│ Read Inputs   │
└──────┬────────┘
       │
       ▼
┌───────────────┐ Loop Start
│ Evaluate Loop │
│ Condition or  │
│ Counter       │
└──────┬────────┘
       │ Yes
       ▼
┌───────────────┐ Execute Loop Body
│ Instructions  │
└──────┬────────┘
       │
       ▼
┌───────────────┐ Update Counter
│ Increment or  │
│ Re-check Cond │
└──────┬────────┘
       │
       ▼
┌───────────────┐ Loop End or Repeat
│ Exit Loop?    │
└──────┬────────┘
       │ No
       └─────────────┐
                     ▼
               (Repeat Loop)

After Loop:
┌───────────────┐
│ Update Outputs│
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a WHILE loop always run at least once? Commit to yes or no.
Common Belief:A WHILE loop always runs the loop body at least once before checking the condition.
Tap to reveal reality
Reality:A WHILE loop checks the condition before running the loop body, so it may run zero times if the condition is false initially.
Why it matters:Assuming the loop runs at least once can cause logic errors and unexpected behavior in PLC control sequences.
Quick: Can a FOR loop be stopped early by a condition inside it? Commit to yes or no.
Common Belief:FOR loops always run the full number of iterations and cannot be stopped early.
Tap to reveal reality
Reality:FOR loops can be interrupted early using control instructions like BREAK or EXIT when conditions inside the loop are met.
Why it matters:Believing FOR loops cannot stop early limits program flexibility and can lead to inefficient or unsafe control logic.
Quick: Are infinite loops safe in PLC programs if they have conditions inside? Commit to yes or no.
Common Belief:Infinite loops with conditions inside are safe because the condition will eventually stop the loop.
Tap to reveal reality
Reality:Infinite loops can cause the PLC to freeze or miss critical tasks if the condition never becomes false or is not checked properly.
Why it matters:Mismanaging loops can cause machine downtime or unsafe operation in industrial environments.
Quick: Do nested loops add or multiply total repetitions? Commit to add or multiply.
Common Belief:Nested loops add the number of repetitions together.
Tap to reveal reality
Reality:Nested loops multiply the total number of repetitions because the inner loop runs fully for each outer loop iteration.
Why it matters:Misunderstanding nested loops can cause unexpected long runtimes or resource use in PLC programs.
Expert Zone
1
Some PLC languages optimize FOR loops by unrolling them during compilation for faster execution.
2
WHILE loops in PLCs must be carefully designed to avoid scan cycle overruns that can cause watchdog timer faults.
3
Loop counters and conditions are stored in specific memory areas that can be monitored or modified during runtime for advanced control.
When NOT to use
Avoid using WHILE loops for tasks requiring fixed iteration counts; use FOR loops instead for predictability. For very complex or asynchronous tasks, consider state machines or event-driven programming instead of loops.
Production Patterns
In production PLC code, FOR loops often control fixed cycles like conveyor steps, while WHILE loops monitor sensor states continuously. Nested loops are used in batch processing or multi-axis motion control. Safety interlocks are always checked inside loops to allow immediate exit.
Connections
State Machines
Builds-on
Loops provide repeated actions, while state machines manage complex sequences with states and transitions; understanding loops helps grasp state machine cycles.
Event-driven Programming
Opposite pattern
Loops actively repeat tasks, whereas event-driven programming reacts to events; knowing loops clarifies when to use polling versus event handling.
Human Habit Formation
Similar pattern
Just as loops repeat instructions automatically, human habits form by repeating actions until automatic; this shows how repetition builds reliable behavior in both machines and people.
Common Pitfalls
#1Creating an infinite loop that never ends.
Wrong approach:WHILE TRUE DO Motor_On() END_WHILE
Correct approach:WHILE Sensor_Active DO Motor_On() END_WHILE
Root cause:Not including a condition that eventually becomes false causes the loop to run forever.
#2Assuming FOR loop counter starts at zero by default.
Wrong approach:FOR i TO 5 DO // loop body END_FOR
Correct approach:FOR i = 1 TO 5 DO // loop body END_FOR
Root cause:Forgetting to initialize the loop counter explicitly leads to unexpected loop behavior.
#3Not updating the loop counter inside a WHILE loop.
Wrong approach:WHILE i < 5 DO Motor_On() END_WHILE
Correct approach:WHILE i < 5 DO Motor_On() i = i + 1 END_WHILE
Root cause:Without changing the condition variable, the loop condition never becomes false, causing an infinite loop.
Key Takeaways
FOR loops repeat a set number of times using a counter, making them perfect for fixed repetitions.
WHILE loops repeat as long as a condition is true, offering flexibility but requiring careful condition management.
Loops prevent repetitive code, making PLC programs shorter, clearer, and easier to maintain.
Misunderstanding loop behavior can cause infinite loops or logic errors, risking machine safety and reliability.
Expert PLC programmers combine loops with conditions and safety checks to build robust, efficient automation.

Practice

(1/5)
1. Which statement best describes a FOR loop in PLC programming?
easy
A. It repeats a set of instructions a fixed number of times.
B. It repeats instructions only while a condition is true.
C. It runs instructions once and then stops.
D. It waits for an input before running.

Solution

  1. Step 1: Understand the purpose of a FOR loop

    A FOR loop repeats instructions a specific number of times, controlled by a counter.
  2. Step 2: Compare with other loop types

    WHILE loops repeat based on a condition, not a fixed count. The other options describe different behaviors.
  3. Final Answer:

    It repeats a set of instructions a fixed number of times. -> Option A
  4. Quick Check:

    FOR loop = fixed repetitions [OK]
Hint: FOR loops run fixed times; WHILE loops depend on conditions [OK]
Common Mistakes:
  • Confusing FOR loops with WHILE loops
  • Thinking FOR loops run only once
  • Believing FOR loops wait for input
2. Which of the following is the correct syntax for a FOR loop in PLC structured text?
easy
A. for i in range(1,6): ...
B. FOR (i = 1; i <= 5; i++) { ... }
C. FOR i := 1 TO 5 DO ... END_FOR;
D. WHILE i < 5 DO ... END_WHILE;

Solution

  1. Step 1: Identify PLC structured text syntax

    PLC uses FOR i := 1 TO 5 DO ... END_FOR; for loops.
  2. Step 2: Recognize other languages' syntax

    The syntax FOR (i = 1; i <= 5; i++) { ... } is C/JavaScript. The syntax for i in range(1,6): ... is Python. WHILE i < 5 DO ... END_WHILE; is a WHILE loop.
  3. Final Answer:

    FOR i := 1 TO 5 DO ... END_FOR; -> Option C
  4. Quick Check:

    PLC FOR loop uses := and TO [OK]
Hint: PLC FOR loops use ':=' and 'TO' keywords [OK]
Common Mistakes:
  • Using C or Python syntax in PLC code
  • Confusing FOR and WHILE syntax
  • Omitting END_FOR statement
3. What will be the output of this PLC structured text code?
VAR i: INT := 1; sum: INT := 0; END_VAR
FOR i := 1 TO 3 DO
  sum := sum + i;
END_FOR;
// Output sum
medium
A. Syntax error
B. 6
C. 0
D. 3

Solution

  1. Step 1: Trace the FOR loop iterations

    The loop runs with i = 1, 2, 3. sum starts at 0.
  2. Step 2: Calculate sum after each iteration

    sum = 0+1=1, then 1+2=3, then 3+3=6.
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    1+2+3 = 6 [OK]
Hint: Add loop variable each iteration to sum [OK]
Common Mistakes:
  • Adding only last value of i
  • Starting sum at 1 instead of 0
  • Confusing loop range boundaries
4. Identify the error in this PLC code snippet:
VAR i: INT := 0; count: INT := 0; END_VAR
WHILE i < 5 DO
  count := count + 1;
END_WHILE;
medium
A. Missing increment of i inside the WHILE loop
B. Incorrect variable declaration syntax
C. WHILE loop should be FOR loop
D. count variable should be BOOL, not INT

Solution

  1. Step 1: Analyze the WHILE loop condition and body

    The loop condition is i < 5, but i never changes inside the loop.
  2. Step 2: Identify infinite loop risk

    Without incrementing i, the condition stays true forever, causing an infinite loop.
  3. Final Answer:

    Missing increment of i inside the WHILE loop -> Option A
  4. Quick Check:

    Loop variable must change to avoid infinite loop [OK]
Hint: Always update loop variable inside WHILE loops [OK]
Common Mistakes:
  • Forgetting to increment loop variable
  • Confusing FOR and WHILE loops
  • Incorrect variable types
5. You want to use a loop to turn on 4 output coils named Q1 to Q4 in sequence using PLC structured text. Which code snippet correctly uses a FOR loop to do this?
hard
A. FOR i := 1 TO 4 DO Q[i-1] := TRUE; END_FOR;
B. FOR i := 1 TO 4 DO Q + i := TRUE; END_FOR;
C. FOR i := 1 TO 4 DO Qi := TRUE; END_FOR;
D. FOR i := 1 TO 4 DO Q[i] := TRUE; END_FOR;

Solution

  1. Step 1: Understand coil addressing in arrays

    Using Q[i] accesses coil Q1 to Q4 correctly if Q is an array of outputs.
  2. Step 2: Check other options for syntax errors

    FOR i := 1 TO 4 DO Q + i := TRUE; END_FOR; uses invalid syntax Q + i. FOR i := 1 TO 4 DO Qi := TRUE; END_FOR; treats Q1, Q2 as fixed names, not variable. FOR i := 1 TO 4 DO Q[i-1] := TRUE; END_FOR; uses i-1 which may cause off-by-one error if indexing starts at 1.
  3. Final Answer:

    FOR i := 1 TO 4 DO Q[i] := TRUE; END_FOR; -> Option D
  4. Quick Check:

    Use array indexing for sequential coil control [OK]
Hint: Use array indexing Q[i] for sequential outputs [OK]
Common Mistakes:
  • Using invalid syntax for coil names
  • Off-by-one errors in indexing
  • Treating coil names as strings
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard