Week 2 · Decisions & Debugging
Session 9: Loops and 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.
Session plan
- 0:0010 minRecap
Quiz: Serial commands
- 0:1020 minDemo
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.
- 0:3035 minBuild
Four-LED chase
Students build the worked sketch, then reorder the pins in the array and predict the new pattern before uploading.
- 1:0545 min
- 1:5010 minWrap-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.