3.5 Loops
A loop allows a program to execute the same instructions repeatedly. Loops are important in Arduino because many applications require continuous monitoring of sensors and devices.
3.5.1 for Loop
A for loop is commonly used when the number of repetitions is known.
for (int i = 0; i < 5; i++) {
Serial.println(i);
}
This program prints numbers from 0 to 4.
The three parts are:
for (initialization; condition; increment)
3.5.2 while Loop
A while loop continues executing as long as its condition remains true.
int counter = 0;
while (counter < 5) {
Serial.println(counter);
counter++;
}
3.5.3 do…while Loop
A do…while loop executes its instructions at least once, then checks the condition.
int counter = 0;
do {
Serial.println(counter);
counter++;
} while (counter < 5);
Importance of Loops in Arduino
Loops can be used to:
- Read sensors repeatedly.
- Blink LEDs.
- Count events.
- Control motors.
- Monitor switches.
- Update displays.
- Process incoming data.


