Introduction
A for loop is the right tool when you know how many times to go round: six notes, ten readings, five rows.
A while loop is for when you do not.
while (something is true) {
keep doing this
}
Keep going until the button is released. Keep going until the sensor settles. Keep going until the answer is found. There is no count, only a condition — and something inside the loop has to eventually make that condition false, or the sketch hangs there for ever.
That is the danger, and it is worth being blunt about it: an Arduino has no way out of an infinite loop. No error, no message, no way to interrupt it. The board sits there apparently working, doing nothing, until you unplug it.
break and continue are the two escape hatches. break leaves the loop immediately. continue skips the rest of this pass and goes round again. Both work in for loops too.
What you will be able to do
By the end of this lesson you can:
- Write a
whileloop with a condition that will eventually end. - Say when
whilefits better thanfor, and the reverse. - Use
breakto leave a loop early. - Use
continueto skip one pass. - Recognise an infinite loop, and say what causes one.
- Say what
do ... whiledoes differently.
What you need
| Part | Type | Qty |
|---|---|---|
| Arduino UNO R3 | Microcontroller | 1 |
| USB A to B cable | Cable | 1 |
Basic
No wiring. Read everything in the Serial Monitor at 9600 baud.
while
int count = 0;
while (count < 5) {
Serial.println(count);
count++; // without this line, it never ends
}
Prints 0 to 4 — the same as the equivalent for. The difference is that the counter is declared outside and stepped by hand, so nothing forces you to remember it.
That count++ is the whole safety of the loop. Delete it and the sketch stops responding for ever.
for or while?
Use for when | Use while when |
|---|---|
| you know how many passes | you do not |
| walking an array | waiting for something to change |
| counting to a number | repeating until a result is good enough |
A for loop keeps its start, its condition and its step in one place where you can see all three. That is why it is safer, and why you should reach for it first.
An infinite loop
int count = 0;
while (count < 5) {
Serial.println(count); // no count++
}
This prints 0 for ever. The board is not crashed — it is doing exactly what you said, endlessly. Nothing else in the sketch will ever run again.
There is no way to interrupt it. Upload a different sketch to recover.
One infinite loop is deliberate and legitimate:
while (true) {
// never ends — used to halt a sketch on purpose
}
break
Challenges
Challenge 1
The same count, three ways.
Print 0 to 4 using:
- a
forloop - a
whileloop - a
do ... whileloop
All three produce identical output. Then change the starting value to 10 in all three and run again.
Two of them print nothing. One prints a single line. Explain why in one sentence.
Log in to ask for the answer.
Challenge 2
Break and continue.
Write a loop over the numbers 1 to 20 that:
- skips every multiple of 3, using
continue - stops completely at 17, using
break
Print what survives. Work out the expected output on paper first — there should be eleven numbers.
Then swap the two conditions round in the loop body and see whether the output changes. Explain why or why not.
Log in to ask for the answer.
Challenge 3
Search an array.
Take:
int readings[10] = {23, 45, 12, 67, 34, 89, 21, 56, 78, 43};
Find the first value above 50 and print it along with its index. Stop looking as soon as you find it.
Then count how many passes the loop actually made, and print that too. Compare it with 10.
Now search for a value above 200, which is not there. What does your sketch print, and does it handle that case sensibly?
Log in to ask for the answer.
Extra challenge
Guess the number, properly.
The sketch picks a secret with random(1, 101) and then guesses it itself, using a while loop and halving the range each time — the strategy from ARD-PG-10.
Keep a low of 1 and a high of 100. Each pass, guess the middle, print it, and move low or high depending on whether the guess was too small or too large. Stop when it matches.
Count and print the number of guesses.
Run it ten times with different secrets. What is the worst number of guesses you see?
Think about it: counting from 1 needed up to 100 guesses. This needs 7. Both loops look about the same size on the page. Where did the saving actually come from — and what did the loop have to know that the counting version did not?
Log in to ask for the answer.