Unit A - Foundations

06. Loops, Arrays & Functions

Remove repetition and organise reusable code.

Estimated time 4 hours

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.

Loops, Arrays & Functions instructional connection diagram
Open the diagram for a larger view. Trace every connection before building.

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

  1. D2, D3, D4, D5 -> separate 330 ohm resistors -> LED anodes
  2. All LED cathodes -> GND
Power rule: switch off before moving wires. Arduino I/O pins are control signals; high-current loads require a driver and suitable external supply.
const 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

  1. sizeof expression calculates the array length instead of duplicating the number 4.
  2. setAll receives one Boolean parameter and controls every LED.

Test and record evidence

Expected result: Four LEDs chase in order, then all flash together.

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.
Extension challenge: Write a function chase(bool forward) that can run the pattern in either direction.

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.