Counting with a while loop
A while loop can print a run of numbers. The loop variable holds the current number, the body prints it, and an update moves to the next one. Here are the numbers 0 through 4:
var i = 0
while i < 5 {
print(i)
i += 1
}
0
1
2
3
4
What the computer does
The variable i starts at 0. Before each pass the condition i < 5 is checked.
- With
iequal to 0, 1, 2, 3 and 4 the condition is true. The body prints the value and adds 1. - After the fifth pass
iis 5. The condition 5 < 5 is false, so the loop stops without printing 5.
Two choices shape the output: the starting value and the condition. With < the last number is excluded. With <= it is included. Choosing between them is the main thing to get right.
The exercise
The assignment is to print all the numbers from 3 to 10, both included.
- Start at the first number. Declare
var counter = 3. It must be avar, because the loop changes it. - Choose the condition. Ten must be printed, so use
counter <= 10. With<the output would stop at 9. Swift takes no parentheses around the condition, but the braces are required. - Print the counter in the body with
print(counter). Each call ends with a newline, so every number is on its own line. - Update the counter with
counter += 1. Without it,counterstays 3, the condition is always true and the loop never ends.
var counter = 3
while counter <= 10 {
print(counter)
counter += 1
}
The output is the eight numbers from 3 to 10, one per line. After the loop, counter is 11, the first value that failed the condition.
Reading the loop as a table
When a loop misbehaves, write down the variable's value at the start of each pass. For the loop above, counter is 3 on the first pass and 10 on the last, so there are eight passes, one per number from 3 to 10. After the update on the eighth pass it is 11, and the condition 11 <= 10 is false. The number of passes is the last value minus the first plus one, which is why a range that includes both ends has one more element than their difference.
Swift details
- No
++. Swift removed the increment operator. Usecounter += 1. - The type is inferred.
var counter = 3makescounteranInt, so you don't write the type. - A different tool. For a fixed range,
for counter in 3...10does the same without a manual update. The while form is useful when you need to control the update yourself.
Common mistakes
- Off by one at the end.
counter < 10misses the 10. Count the numbers you expect: 3 to 10 is eight lines. - Wrong start. Starting at 0 or 1 prints extra numbers.
- Update before print. If
counter += 1comes first, the first line is 4 and the last is 11. - Using
let. A constant can't be increased.
Key takeaways
- The initial value sets the first number printed.
- The condition sets the last. Use
<=to include it. - The update must move the variable toward ending the loop.
