Learn/Swift/5. Loops
Lesson 5 of 8
Sign in

Swift, lesson 5

Loops

Computers are good at doing the same thing many times without getting bored. A loop runs a block of code again and again, either a set number of times or until something changes.

for-in over a range

The most common loop walks through a range of numbers. Each time round, the loop constant takes the next value:

1...3 includes the 3. Use 0..<count when you want to stop just before the end, which is handy for counting from zero. The loop constant (lap here) is a new let each time round; you cannot change it inside the loop. If you don't need it at all, write _:

To count in steps or count down, use stride. stride(from:to:by:) stops the end value, while can include it:

2 exercises to try what you just read.

Exercise 1

Times table

Press Ctrl Enter or Check to test your code.

Exercise 2

Sum until zero

Press Ctrl Enter or Check to test your code.

before
stride(from:through:by:)

while and repeat-while

A while loop keeps going as long as its condition is true. It checks the condition before each pass, so the body might never run at all:

repeat-while checks after each pass, so its body always runs at least once:

Use for-in when you know how many times to loop, and while when you only know the condition for stopping.

Reading until the input runs out

Remember that readLine() returns nil when there is no more input. A while let loop uses exactly that: it reads a line, runs the body if there was one, and stops at the end of input.

Leaving early: break and continue

  • break exits the loop immediately. Nothing else in the loop runs.
  • continue skips the rest of the current pass and jumps to the next one.

Be careful with while loops: if nothing inside the body ever makes the condition false, the loop runs forever and the test runner will stop your program when it runs out of time.

Further reading

  • Control Flow: for-in, while and control transfer statements
  • Basic Operators: range operators

Read a whole number n and print its multiplication table from 1 to 10, one line each, in the form n x i = result.

Input: one line with an integer (it may be zero or negative).

Output: ten lines.

Sample input:

Sample output:

A cashier scans prices one by one. A price of 0 means the customer is done. Add up the prices until you see a 0 or the input ends, whichever comes first. Anything after the 0 belongs to the next customer, so ignore it.

Input: zero or more lines, each with one whole number.

Output: two lines, Total: with the sum and Items: with how many prices were added (the 0 itself does not count).

Sample input:

Sample output:

for lap in 1...3 {
    print("Lap \(lap)")
}
// Lap 1, Lap 2, Lap 3 (each on its own line)
for _ in 1...3 {
    print("Hip hip hooray!")
}
for n in stride(from: 10, through: 0, by: -5) {
    print(n)   // 10, 5, 0
}
var balance = 100
var months = 0
while balance < 200 {
    balance += balance / 10
    months += 1
}
print("Doubled after \(months) months")
var roll = 0
repeat {
    roll += 2
} while roll < 5
var lines = 0
while let line = readLine() {
    print("Got: \(line)")
    lines += 1
}
print("\(lines) lines read")
for n in 1...10 {
    if n % 2 == 0 {
        continue   // skip even numbers
    }
    if n > 7 {
        break      // stop completely
    }
    print(n)       // 1, 3, 5, 7
}
7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
4
10
3
0
99
Total: 17
Items: 3