Sub topic 9
Arrays and looping over them
What this chapter assumes
You have already met variables and data types, and you know how for, while, and do-while loops repeat work. You can upload a sketch and open the Serial Monitor. This chapter combines those pieces. An array holds several values of one type under a single name, and a loop visits each of them.
Why arrays exist
Suppose you wire four LEDs to pins 3, 4, 5, and 6. Without arrays you would write one variable per pin:
const int led1 = 3;
const int led2 = 4;
const int led3 = 5;
const int led4 = 6;Every action then has to be repeated four times: one pinMode() call per LED, one digitalWrite() call per LED. Adding a fifth LED means editing many lines. An array stores the four pin numbers in one place, and a loop applies the same action to each one.
Declaring and initializing arrays
An array is a numbered sequence of elements. All elements have the same type, and the number of elements is fixed when the array is declared. The syntax is type name[size].
int readings[5]; // five ints, contents not set
const byte ledPins[] = {3, 4, 5, 6}; // size inferred from the list: 4
float weights[3] = {0.5, 1.0, 1.5}; // size given and values listed
int zeros[8] = {0}; // all eight elements set to 0Some details are worth knowing:
- If you give an initializer list and leave the brackets empty, the compiler counts the values for you.
- If you give a size and a shorter list, the remaining elements are set to zero.
- A global array with no initializer is zeroed. A local array with no initializer holds whatever bytes were in memory. Do not read it before you write to it.
- The size must be known at compile time. You cannot use a variable that changes at run time as the size.
Indexing
Each element has an index, which is its position counted from zero. For an array of four elements, the valid indexes are 0, 1, 2, and 3.
| Expression | Meaning for `ledPins` = {3, 4, 5, 6} |
|---|---|
| `ledPins[0]` | 3, the first element |
| `ledPins[3]` | 6, the last element |
| `ledPins[4]` | Out of range, undefined behavior |
You read an element with ledPins[2] and change it with an assignment such as readings[0] = 512;.
Out-of-bounds access
The most common array bug is an index past the end. The Arduino compiler does not check indexes, and the board does not stop you at run time. Writing ledPins[4] = 9; stores a byte in whatever memory sits after the array. That memory may belong to another variable. The result can be a corrupted value, odd behavior far from the faulty line, or a reset.
The classic form of the mistake is a loop condition of i <= count where it should be i < count. The loop then runs one time too many.
Finding the number of elements
Hard-coding the length in several places invites errors. Compute it from the array itself:
const byte ledPins[] = {3, 4, 5, 6};
const byte ledCount = sizeof(ledPins) / sizeof(ledPins[0]);sizeof(ledPins) is the total number of bytes in the array. sizeof(ledPins[0]) is the number of bytes in one element. Dividing the first by the second gives the element count. This works for any element type, including int (2 bytes on an Uno) and float (4 bytes).
Looping over an array with for
A for loop is the natural partner of an array. The loop counter doubles as the index. This sketch configures four pins once and then chases a light along them:
const byte ledPins[] = {3, 4, 5, 6};
const byte ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
void setup() {
for (byte i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (byte i = 0; i < ledCount; i++) {
digitalWrite(ledPins[i], HIGH);
delay(200);
digitalWrite(ledPins[i], LOW);
}
}Follow the logic in loop(). On the first pass i is 0, so pin 3 turns on, waits 200 ms, and turns off. Then i becomes 1 and pin 4 gets the same treatment. When i reaches 4, the condition i < ledCount is false and the loop ends. loop() then starts again from the top.
To add a fifth LED on pin 7, you change one line: {3, 4, 5, 6, 7}. The count and both loops adjust themselves.
The counter type matters. A byte holds 0 to 255, which is fine for small arrays. If an array could have more than 255 elements, use int or unsigned int. Be careful when counting down with an unsigned type: for (byte i = ledCount - 1; i >= 0; i--) never ends, because an unsigned value can never be below zero. It wraps from 0 to 255. Use a signed int for a reverse loop.
const byte ledPins[] = {3, 4, 5, 6};
const int ledCount = sizeof(ledPins) / sizeof(ledPins[0]);
void setup() {
for (int i = 0; i < ledCount; i++) {
pinMode(ledPins[i], OUTPUT);
}
}
void loop() {
for (int i = ledCount - 1; i >= 0; i--) {
digitalWrite(ledPins[i], HIGH);
delay(200);
digitalWrite(ledPins[i], LOW);
}
}This version runs the chase backward, from pin 6 to pin 3.
Common array patterns
Summing and averaging
Accumulate into a variable that is wide enough for the total. Ten readings of up to 1023 add up to 10230, which still fits in an int on an Uno (maximum 32767). A longer series would overflow it, so a long is the safer choice.
int samples[] = {512, 530, 498, 505, 520};
const byte sampleCount = sizeof(samples) / sizeof(samples[0]);
void setup() {
Serial.begin(9600);
long total = 0;
for (byte i = 0; i < sampleCount; i++) {
total += samples[i];
}
Serial.print("Average: ");
Serial.println(total / sampleCount);
}
void loop() {
}The result is 513, because integer division drops the fractional part.
Finding the largest value
Start with the first element, then compare the rest against it:
int samples[] = {512, 530, 498, 505, 520};
const byte sampleCount = sizeof(samples) / sizeof(samples[0]);
void setup() {
Serial.begin(9600);
int largest = samples[0];
for (byte i = 1; i < sampleCount; i++) {
if (samples[i] > largest) {
largest = samples[i];
}
}
Serial.print("Largest: ");
Serial.println(largest);
}
void loop() {
}Starting the loop at index 1 avoids comparing the first element to itself. Starting largest at 0 would be a bug if every reading could be negative.
Keeping the last N readings
A common use is a small buffer of recent sensor values. The index wraps back to 0 with the modulo operator, so the buffer overwrites its oldest entry:
const byte bufferSize = 5;
int recent[bufferSize];
byte nextSlot = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
recent[nextSlot] = analogRead(A0);
nextSlot = (nextSlot + 1) % bufferSize;
long total = 0;
for (byte i = 0; i < bufferSize; i++) {
total += recent[i];
}
Serial.println(total / bufferSize);
delay(200);
}Because recent is global, it starts zeroed. The first few averages are therefore too low until the buffer fills.
Arrays of other types
Arrays are not limited to pin numbers. A char array holds text, and an array of const char* can hold several messages. Here the array holds a pattern of delays in milliseconds:
const unsigned int pattern[] = {100, 100, 100, 400, 400, 400};
const byte patternLength = sizeof(pattern) / sizeof(pattern[0]);
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
for (byte i = 0; i < patternLength; i++) {
digitalWrite(LED_BUILTIN, HIGH);
delay(pattern[i]);
digitalWrite(LED_BUILTIN, LOW);
delay(150);
}
delay(1000);
}Changing the behavior means editing data, not logic. That separation keeps the code short and easy to read.
Memory cost
An array uses RAM for as long as it exists. On an Uno, SRAM is 2 KB in total. An int array of 500 elements needs 1000 bytes, which is nearly half of it. Choose the smallest type that fits: byte for pin numbers and values up to 255, int for analog readings, and float only when you need fractions.
Marking a lookup table const tells the compiler the values never change. It also prevents accidental writes. On AVR boards such as the Uno, a const array still occupies RAM unless you place it in flash with PROGMEM. That technique is outside this chapter.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Loop condition `i <= count` | Reads or writes one element past the end | Use `i < count` |
| Assuming indexes start at 1 | The first element is skipped and the last is out of range | Start at 0 |
| `sizeof` on an array parameter | Wrong length, often 2 | Pass the length as a parameter |
| Unsigned counter in a countdown loop | The loop never ends | Use a signed `int` |
| Reading a local array before writing | Random values | Initialize it, for example `= {0}` |
| Values too large for the element type | Wrapped or negative numbers | Choose a wider type |
Exercise
An array is declared as int levels[6] = {10, 20, 30};. What does levels[4] contain, and what happens if the sketch reads levels[6]?
Show answer
levels[4] is 0, because elements without an initializer are set to zero when a size and a shorter list are given. levels[6] is outside the valid indexes 0 to 5. The compiler does not check it, so the sketch reads whatever memory follows the array. The value is unpredictable and the behavior is undefined.
Exercise
Rewrite this loop so it visits every element of ledPins exactly once without going out of range: for (byte i = 0; i <= ledCount; i++) { digitalWrite(ledPins[i], HIGH); }
Show answer
Change the condition to i < ledCount: for (byte i = 0; i < ledCount; i++) { digitalWrite(ledPins[i], HIGH); }. With <=, the last pass uses index ledCount, which is one past the final element.
Exercise
You want a loop that turns LEDs off from the last one to the first. Why does for (byte i = ledCount - 1; i >= 0; i--) never finish, and what is the fix?
Show answer
A byte is unsigned, so i >= 0 is always true. After i reaches 0, i-- wraps it to 255. Declare the counter as a signed int so it can become -1 and end the loop.