Week 2 · Decisions & Debugging

Session 9: Loops and arrays

Teach & build120 minLesson 07: Loops & Arrays

Learning outcomes

  • Write for loops with a correct init, condition and update
  • Store pins and readings in arrays and index from zero
  • Use sizeof so a loop always matches its array
  • Avoid off-by-one errors and infinite loops

Kit and components

  • Uno, breadboard, four LEDs, four 330 Ω resistors, jumper wires

Pre-reading about 25 min

Students read these on their phones before class. They are listed on the student Before class page.

  1. Lesson 07: for loop anatomy
  2. Lesson 07: Arrays store related values
  3. Lesson 07: The bounds trap
  4. Theory Reference: for loops

Session plan

  1. 0:0010 min
    Recap

    Quiz: Serial commands

  2. 0:1020 min
    Demo

    From copy-paste to a loop

    Start with four copy-pasted digitalWrite lines and refactor them into an array and a for loop. Then change the condition to i <= ledCount and discuss what goes wrong.

  3. 0:3035 min
    Build

    Four-LED chase

    Students build the worked sketch, then reorder the pins in the array and predict the new pattern before uploading.

  4. 1:0545 min
  5. 1:5010 min
    Wrap-up

    What is the last valid index?

Checkpoint: ready to move on?

Each student's chase runs from a pin array sized with sizeof, and they can say why i <= ledCount is a bug.

Extension for fast finishers

Reverse chase counting down with int i (lesson challenge).

Catch-up path

Trace a for loop on paper in a table: i, the condition, what runs.

Homework and practice

Code Along 4.5-4.7.

Facilitator notes

  • Leave the four-LED circuit on the breadboard: S10-S12 use it again.