Computer Science · Ch 6 — Flow of Control
Repetition
Repetition
Many tasks in daily life repeat: the electricity bill is paid every month, seasons return every year. Nature repeats too — Figure 6.3 shows the life cycle of a butterfly, which passes through four stages: the butterfly lays eggs, the eggs turn into a caterpillar, the caterpillar becomes a pupa, and the pupa matures into a butterfly — which then lays eggs and the cycle begins again. This kind of repetition is also called iteration.
In a program, repeating a set of statements is made possible by looping constructs.
Why loops are needed
Printing the first five natural numbers can be done with plain sequence:
# Print first five natural numbers — no loop
print(1)
print(2)
print(3)
print(4)
print(5)
1
2
3
4
5
But what if the task were to print the first 100,000 natural numbers? Writing 100,000 print statements is obviously tedious and inefficient — it is simply not the right way to solve the problem. A program built around a loop is the better solution. The logic is:
- Take a variable, say
count, and set its value to 1. - Print the value of
count. - Increment the variable (
count += 1). - Repeat steps 2 and 3 as long as
countis less than or equal to 100,000 (count <= 100000).
How a loop behaves
Looping constructs let a program execute a set of statements repetitively, based on a condition. The statements in the loop's body run again and again as long as a particular logical condition remains true. That condition is checked using the value of a variable called the loop's control variable (count in the logic above). The moment the condition becomes false, the loop terminates. …
Drawn by us to help you understand the concept clearly, and verified to make sure it's accurate. For exams, practice from your textbook's own diagram.
Figure 6.3 is a circular life-cycle diagram of a butterfly — an illustration from nature, not a flowchart — used to introduce the idea of repetition (iteration) before loops are written in code.
The diagram shows four stages arranged in a circle, connected clockwise by curved black arrows that form a closed cycle:
- at the top, a green leaf with eggs laid on it;
- to the right, a green caterpillar (the eggs hatch into this stage);
- at the bottom, a pupa (chrysalis) hanging from a twig;
- to the left, a blue-and-yellow butterfly, the mature insect —
and from the butterfly the arrow curves back up to the leaf with eggs, closing the loop.
The point of the closed shape is that the process has no end point: the butterfly lays eggs, the eggs become a caterpillar, the caterpillar becomes a pupa, the pupa matures into a butterfly — and the cycle starts again with the laying of eggs. The same four steps repeat over and over. …