What the exercise asks for
The exercise is to compute the sum of all the integers from 14 to 73, using a for loop, and to print the result. Both ends are included, so the numbers are 14, 15, 16 and so on up to 73. That is 60 numbers.
The pattern is the accumulator: a variable starts at 0, a loop visits each number once, and each pass adds the current number to the variable. After the loop, the variable holds the total.
Loops and ranges in Swift
A for-in loop runs its body once for each value in a sequence. The sequence is often a range:
14...73is a closed range. It includes both 14 and 73.14..<73is a half-open range. It includes 14 but stops before 73.
The loop variable is created by the loop itself, with no let or var in front of it, and it holds a new value on each pass. It exists only inside the loop body. The range's bounds can't run backwards: a closed range whose lower bound is above its upper bound makes the program crash.
The accumulator is different. It must exist before the loop and survive after it, so it is declared outside, with var, because its value changes. A constant declared with let can't be updated. The expression sum += number is shorthand for sum = sum + number.
Step by step
- Declare the accumulator as
var sum = 0. Swift infers the typeIntfrom the literal. - Write the loop as
for number in 14...73. The closed range makes sure 73 is counted. - Add inside the loop:
sum += number. - Print after the loop, outside the braces, so the total is printed once and not on every pass.
The solution in Swift
var sum = 0
for number in 14...73 {
sum += number
}
print(sum)
This prints:
2610
You can check the result without a loop. The 60 numbers pair up from the outside in: 14 + 73, 15 + 72 and so on, and every pair adds up to 87. There are 30 pairs, and 30 * 87 is 2610. In general, the sum of the integers from a to b is (a + b) * (b - a + 1) / 2.
Common mistakes
- Using
14..<73. The loop would stop at 72 and the total would be 2537, which is 73 short. - Printing inside the loop. The code would print 60 running totals instead of one answer.
- Declaring the accumulator inside the loop. It would reset to 0 on every pass and also be invisible to the final
print. - Declaring it with
let. The compiler rejectssum += numberbecause a constant can't change. - Forgetting to start at 0. Swift requires a variable to have a value before it is read, so this mistake is caught by the compiler.
Key takeaways
- Use
...for a range that includes its last value, and..<for one that stops before it. - An accumulator is declared with
varbefore the loop, updated inside it, and used after it. - The loop variable needs no declaration of its own.
- A formula can confirm the answer: here, 30 pairs of 87 give 2610.
