A loop that runs until something stops it
96 people wait at the gate. Each round, half of them go in. A round is one time the gate lets people in.
Loading lab…
- Start: waiting = 96, rounds = 0.
- Check ≥ 10? True. waiting = 48, rounds = 1.
- Check again. waiting = 24, rounds = 2.
- Check again. waiting = 12, rounds = 3.
- Check again. waiting = 6, rounds = 4.
- Check ≥ 10? False. Loop ends.
The loop repeats until fewer than 10 people are waiting. That takes 4 rounds. Each time the block runs is one round. The box waiting holds the people still waiting. The box rounds counts the rounds.
The rule
while checks its condition, runs the block, and checks again. Something inside the block must change what the condition asks about. Otherwise nothing ever ends it.
`` while (waiting >= 10) { waiting = waiting / 2; rounds = rounds + 1; } ``
A while loop checks before it runs the block. Suppose fewer than ten people wait at the start. Then the block runs zero times.
Remove the halving line, waiting = waiting / 2;. Then waiting never changes, so the condition stays true. The machine stops the loop itself:
This loop ran 500 times without stopping. Check the condition on line 3.
A step is one small action, such as one sum. The finished loop takes 58 steps and 4 rounds. A loop that removes one person a round takes 971 steps. That is 87 rounds. That is nearly 17 times the steps of the halving loop.