What is an Array?
An array is a collection of values stored under a single name. Each value has an index (position number starting from 0).
Declaring Arrays
// Method 1: Specify size and values
int leds[4] = {3, 5, 6, 9};
// Method 2: Let compiler count
int leds[] = {3, 5, 6, 9};
// Method 3: Specify size, fill later
int readings[10]; // 10 zeros
Accessing Elements
int first = leds[0]; // 3 (first element)
int second = leds[1]; // 5
int last = leds[3]; // 9
leds[2] = 10; // Change third element
Important: Arrays are zero-indexed. An array of 4 elements has indices 0, 1, 2, 3.
Array + Loop = Power
int leds[] = {3, 5, 6, 9};
int numLeds = 4;
// Turn all LEDs on
for (int i = 0; i < numLeds; i++) {
pinMode(leds[i], OUTPUT);
digitalWrite(leds[i], HIGH);
}
Common Uses
- LED pin arrays: Control multiple LEDs
- Melody arrays: Store note sequences
- Lookup tables: Digit patterns for 7-segment displays
- Sensor buffers: Average multiple readings
Common Mistakes
- Buffer overflow: Accessing index beyond array size crashes the Arduino
- Off-by-one: Remember arrays start at 0, not 1
- Forgetting size: Always track array length separately