06. Loops, Arrays & Functions
Remove repetition and organise reusable code.
Learning outcomes
- Use for and while loops safely
- Store related values in arrays
- Create functions with parameters and return values
- Avoid array bounds and infinite-loop faults
Parts and preparation
Arduino Uno, four LEDs, four 330 ohm resistors and breadboard.
Before power: inspect wiring, confirm supply voltage and ensure all connected circuits share GND.
for loops
A for loop has initialisation, condition and update. It suits known repetitions. Ensure the condition eventually becomes false.
while loops
A while loop repeats while its condition is true. It can block the rest of a program if the condition never changes.
Arrays
An array stores same-type values under one name. Indexing starts at zero. For four items, valid indices are 0-3.
Functions
A function names a task. Parameters provide inputs; a return type describes the result. void means no value is returned. Functions improve testing and reuse.
Wiring and safe build sequence
- D2, D3, D4, D5 -> separate 330 ohm resistors -> LED anodes
- All LED cathodes -> GND
Worked sketch
Download .ino sketchconst byte leds[] = {2, 3, 4, 5};
const byte ledCount = sizeof(leds) / sizeof(leds[0]);
void setAll(bool state) {
for (byte i = 0; i < ledCount; i++) {
digitalWrite(leds[i], state);
}
}
void setup() {
for (byte i = 0; i < ledCount; i++) {
pinMode(leds[i], OUTPUT);
}
}
void loop() {
for (byte i = 0; i < ledCount; i++) {
digitalWrite(leds[i], HIGH);
delay(150);
digitalWrite(leds[i], LOW);
}
setAll(HIGH);
delay(300);
setAll(LOW);
}How the code works
- sizeof expression calculates the array length instead of duplicating the number 4.
- setAll receives one Boolean parameter and controls every LED.
Test and record evidence
Practical evidence checklist
Common faults and checks
- An i <= ledCount condition is wrong because it accesses one item past the array.
- Check each LED/resistor branch separately.
Check your understanding
Q1. What is the first array index?
Show answer
0.
Q2. Why create a function?
Show answer
To name, reuse and independently test a task.