Sub topic 8
Repeating Work with `for`, `while`, and `do-while`
This chapter assumes you know how to open, verify, and upload an Arduino sketch. You should also know the roles of setup() and loop(), how to declare variables, and how to control an output pin with pinMode() and digitalWrite().
Loops repeat a group of statements. They are useful when an action must happen several times, when you need to process every item in an array, or when a program must keep checking a condition.
Choosing a loop
Arduino uses three common loop forms:
| Loop | Best use | Condition checked |
|---|---|---|
| `for` | A known number of repetitions | Before each iteration |
| `while` | Repeat while a condition remains true | Before each iteration |
| `do-while` | Run at least once, then repeat conditionally | After each iteration |
A loop iteration is one pass through the loop body.
The `for` loop
A for loop combines initialization, a condition, and an update:
for (initialization; condition; update) {
// repeated statements
}The initialization runs once. The condition is checked before every iteration. The update runs after the body.
This sketch turns on four LEDs one at a time. The array stores the pin numbers, and the loop visits each array element by using its index.
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);
}
}Array indexes start at zero. For an array with four elements, valid indexes are 0, 1, 2, and 3. The condition i < ledCount prevents access beyond the end of the array.
The `while` loop
A while loop is useful when you do not know how many repetitions are needed:
while (condition) {
// repeated statements
}The condition must eventually become false. Otherwise, the loop never ends and the remaining code cannot run. For example, this loop waits until a sensor reading reaches a threshold:
int reading = analogRead(A0);
while (reading < 700) {
reading = analogRead(A0);
delay(10);
}The variable used in the condition must be updated inside the loop. If reading were never updated, the loop could become infinite.
The `do-while` loop
A do-while loop checks its condition after running the body:
do {
// statements that must run at least once
} while (condition);The semicolon after the condition is required. This form is useful for an action such as taking an initial measurement before deciding whether another measurement is needed.
int reading;
do {
reading = analogRead(A0);
delay(10);
} while (reading < 700);The body runs at least once, even if the first reading is already 700 or higher.
Common loop errors
- Use
<when an array index must stay below its element count.i <= ledCountaccesses one invalid element. - Change the loop variable or condition value so a
whileloop can finish. - Do not add a semicolon after a
fororwhilecondition unless an empty loop is intentional. - Remember that
delay()blocks the entire sketch during its wait. Later chapters replace it withmillis()timing.
Exercise
Rewrite the LED loop so the LEDs turn on in reverse order, from pin 6 to pin 3.
Show answer
Start the index at ledCount - 1, continue while i >= 0, and decrement it. Use a signed type such as int for the index so it can reach -1 and stop safely.