The problem loops solve
Programs often repeat work. Suppose a teacher asks a student to print a sentence five times. Without loops, the only tool is the print function, called once per line.
print("I promise to learn coding.")
print("I promise to learn coding.")
print("I promise to learn coding.")
print("I promise to learn coding.")
print("I promise to learn coding.")
Each call prints the text and ends the line, so the output is five identical lines. The program works, and for five lines the cost is small.
Why it does not scale
Now change the request to 10 lines, then 100, then 100,000. Writing that many lines by hand is slow, and copying and pasting invites mistakes: one line may be missed, one may be pasted twice, and a typo in one copy leaves the output inconsistent.
A second problem is change. If the sentence has to change to I promise to practise every day., every one of those lines has to be edited. With 100,000 copies, that is a large job, and any copy left behind gives a wrong result.
What you want to say is: print this sentence, and do it five times. The sentence should appear in the program once, and the number of repetitions should be a single value you can change. A loop expresses exactly that.
What a loop gives you
- Less code. The repeated statement is written once, however many times it runs.
- One place to change. Edit the statement or the count in one spot.
- Counts that are not fixed. A loop can repeat once per element of an array, whose length may not be known when you write the program.
Swift has two main loops. A while loop repeats as long as a condition is true. A for-in loop repeats once for each element of a sequence, such as an array or a range like 1...5. The next lessons teach them, starting with while.
The exercise
The assignment is to feel the cost of the manual approach. Using only print, print "I promise to learn coding." five times. The text must match exactly, including the capital I and the full stop, because the lesson's tests compare the output.
- Write one call:
print("I promise to learn coding."). - Repeat it on four more lines, five calls in total.
- Count the lines. Four calls give four lines, six give six. Only five passes.
The program is the five-line block shown above. Notice how repetitive it is, and keep that feeling in mind for the next lesson.
Common mistakes
- Printing the wrong number of lines. Count the calls before running.
- Changing the sentence in one line. A lowercase letter or a missing full stop in one copy fails the tests.
- Printing everything in one call. One
printcall with the sentence five times in it gives one line, not five.
Key takeaways
- Repeating a statement by hand is slow, error-prone and hard to change.
- Loops run a block of code many times while it is written once.
- Swift's two loops are
whileandfor-in.
