Unit A · From blocks to text
What we are making: an LED that blinks a set number of times, then stops — which the forever block could never do on its own.
You know two loops from last year: repeat, which counts, and forever, which does not stop. C++ has both, and one of them is already doing its job invisibly.
The for line looks like a lot at first. It is three small things separated by
semicolons, and it is always the same shape.
int i = 0 — start a counter at zero. Done once, before anything.i < 5 — keep going while this is true. Checked before every round.i++ — add one to i. Done at the end of every round.i < 5 with i starting at 0 gives 0, 1, 2, 3, 4 — five rounds. Programmers count from zero almost everywhere, and you will meet it again with arrays.i so you can watch the counter. Open the serial monitor.i < 5 to i < 10. What happens?delay(3000) inside the for loop's brackets. Upload. Why is it so different?while repeats as long as something is true. It has no counter of its own.
while whose condition never becomes false runs forever and nothing after it ever happens. If your board seems to freeze, look at your while loops first.i in the delay.while to hold the program until the button is pressed, then blink five times.In this session