Why Loops?
Loops let you repeat code without writing it out multiple times. They're essential for counting, scanning, animations, and waiting.
The for Loop
Best when you know how many times to repeat:
for (int i = 0; i < 10; i++) {
Serial.println(i); // Prints 0-9
}
Structure: for (start; condition; step)
The while Loop
Best when you want to repeat until something changes:
while (digitalRead(buttonPin) == HIGH) {
// Keep waiting until button is pressed
}
Serial.println("Button pressed!");
The do-while Loop
Runs at least once, then checks the condition:
char key;
do {
// This runs at least once
key = keypad.getKey();
} while (key == NO_KEY); // key is declared outside, so the condition can see it
Loop Patterns
Counting up
for (int i = 0; i <= 10; i++) { }
Counting down
for (int i = 10; i >= 0; i--) { }
Stepping by 2
for (int i = 0; i < 100; i += 2) { }
Looping through an array
int leds[] = {3, 5, 6, 9};
for (int i = 0; i < 4; i++) {
digitalWrite(leds[i], HIGH);
}
Breaking Out
break;exits the loop immediatelycontinue;skips to the next iteration