Control Structure

Lesson 21 - Using for Loop

Learn how for loops repeat code in a controlled way using initialization, condition checks, and increment/decrement steps.

Progress indicator

Lesson 21 of 28

Learning Objectives

  • Understand what a for loop is and when to use it.
  • Write correct for loop syntax with all three parts.
  • Explain initialization, condition, and increment/decrement behavior.
  • Read loop flow clearly from start to end.
  • Understand how nested for loops behave.
  • Avoid common beginner mistakes with loop bounds and counters.

Concept Explanation

What is for Loop

A for loop repeats a block of code a known number of times.

It is useful when you want controlled repetition, such as blinking an LED exactly 5 times or processing array items one by one.

for Loop Syntax

for (initialization; condition; update) {
  // code to repeat
}

How for Loop Works

  1. Run initialization once at loop start.
  2. Check condition before each repetition.
  3. If condition is true, run loop body.
  4. Run update expression (increment/decrement).
  5. Repeat until condition becomes false.

Think of it as a small machine: start counter, test rule, do work, move counter, test again.

Loop Initialization

Example: int i = 0. This creates and sets the loop counter.

Loop Condition

Example: i < 5. Loop runs only while this is true.

Increment / Decrement

Example: i++ increases by 1 each cycle. You can also use i--.

for Loop Flow

Read it as: start counter, check rule, run code, update counter, check again. This gives predictable repetition.

Cyclei ValueCondition i < 5
10true (run)
21true (run)
32true (run)
43true (run)
54true (run)
Stop5false (exit)

Nested for Loops

A nested loop is a loop inside another loop. It is useful for grid-style tasks, matrix data, or repeated patterns.

Beginners should keep nesting shallow because deep nesting gets harder to debug.

for (int row = 0; row < 2; row++) {
  for (int col = 0; col < 3; col++) {
    Serial.print("row=");
    Serial.print(row);
    Serial.print(", col=");
    Serial.println(col);
  }
}

When to Use for Loop

  • Blink LED fixed number of times
  • Iterate through arrays and buffers
  • Run calibration/test steps in order

Example Code

This example blinks the LED 5 times using a for loop and prints the cycle number.

const int ledPin = 2;

void setup() {
  pinMode(ledPin, OUTPUT);
  Serial.begin(115200);
}

void loop() {
  for (int i = 0; i < 5; i++) {
    digitalWrite(ledPin, HIGH);
    Serial.print("Blink cycle: ");
    Serial.println(i);
    delay(300);

    digitalWrite(ledPin, LOW);
    delay(300);
  }

  Serial.println("for loop finished");
  delay(1000);
}

Example Code Explanation

  1. Set LED pin as output and start Serial in setup().
  2. for (int i = 0; i < 5; i++) starts at 0 and repeats while i is less than 5.
  3. Inside each loop cycle, LED turns ON, waits, then turns OFF and waits again.
  4. Serial prints the current loop index so you can track each repetition.
  5. After 5 cycles, loop exits, prints finished message, then pauses before repeating.

Real-life connection

Use this pattern when you need fixed retries, fixed blink alerts, or fixed sampling steps in a calibration process.

Common Mistakes with for Loop

  • Using wrong condition and creating accidental infinite loops.
  • Forgetting increment/decrement expression so loop never reaches stop condition.
  • Off-by-one errors, like running 6 times instead of 5.
  • Reusing the same counter variable name in nested loops incorrectly.

Best Practices for for Loop

  • Use clear counter names and readable bounds.
  • Keep loop body small and focused on one task per iteration.
  • Comment non-obvious limits or step sizes.
  • Test boundary cases (0, max-1, max) while learning.
  • When possible, use constants for loop limits to avoid magic numbers.

Practice Task

  1. Change loop count from 5 to 3 and observe Serial output.
  2. Change delay(300) to delay(100) and compare blink speed.
  3. Modify loop to count down from 5 to 1 using i--.
  4. Write one small nested loop that prints row/column pairs to Serial.

Try it now

Open simulator workspace and test fixed-count loop behavior with LED blinking.

Run in Simulator