While loops
A while loop repeats a block of code while a condition is true. You create a while loop this way:
while <CONDITION> {
<LOOP CODE>
}
Every iteration, the loop checks the condition. If the condition is true, then the loop executes and moves on to another iteration. If the condition is false, then the loop stops. Just like if statements, while loops introduce a scope.
The simplest while loop takes this form:
while true {
}
This is a while loop that never ends because the condition is always true. Of course, you would never write such a while loop, because your program would spin forever! This situation is known as an infinite loop, and while it might not cause your program to crash, it will very likely cause your computer to freeze.
Here’s a more useful example of a while loop:
var sum = 1
while sum < 1000 {
sum = sum + (sum + 1)
}
This code calculates a mathematical sequence, up to the point where the value is greater than 1000.
The loop executes as follows:
- Before iteration 1: sum = 1, loop condition = true
- After iteration 1: sum = 3, loop condition = true
- After iteration 2: sum = 7, loop condition = true
- After iteration 3: sum = 15, loop condition = true
- After iteration 4: sum = 31, loop condition = true
- After iteration 5: sum = 63, loop condition = true
- After iteration 6: sum = 127, loop condition = true
- After iteration 7: sum = 255, loop condition = true
- After iteration 8: sum = 511, loop condition = true
- After iteration 9: sum = 1023, loop condition = false
After the ninth iteration, the sum variable is 1023, and therefore the loop condition of
sum < 1000 becomes false. At this point, the loop stops.