GoalExplain that a count-controlled loop repeats steps a set number of times.
New words
iteration · one trip through the steps of a loopcounter · a number that counts how many times a loop has runcount-controlled loop · a loop that repeats a set number of times
Explanation
In a story, the same thing often happens again and again. A giant knocks on a door four times. A bell rings. In a program, a loop repeats instructions. Some loops go on forever. A count-controlled loop repeats a set number of times. A counter keeps track of how many times the loop has run. Each trip through the loop is called one iteration. When the counter reaches the number, the loop stops and the program carries on with the next step.
Iteration
Counter
Action
1
1
knock and wait
2
2
knock and wait
3
3
knock and wait
4
4
knock and wait; the counter has reached 4, so the loop stops
Worked examples
Time
Iterations of “ring the bell”
3 o’clock
3
7 o’clock
7
12 o’clock
12
A clock tower rings its bell once for every hour. At 3 o’clock the loop runs 3 times, at 7 o’clock it runs 7 times and at 12 o’clock it runs 12 times. The number of iterations changes, but each one is the same: ring the bell.
Loop
How many times?
Repeat 6 times
exactly 6: count-controlled
Repeat forever
never stops: not count-controlled
Repeat until someone opens the door
we do not know: not count-controlled
Not every loop is count-controlled. Only a loop with a set number tells us how many times it runs.
Iteration
Claps so far
Stamps so far
1
2
1
2
4
2
3
6
3
Here the loop is “repeat 3 times: clap twice, then stamp once”. Each iteration adds 2 claps and 1 stamp, so after 3 iterations there are 6 claps and 3 stamps.
Class activity
Be the counter (with family): one person is the loop and does an action, such as a hop. Another person is the counter and holds up one more finger after every iteration. The loop “hop 7 times” stops when the counter shows 7. Try “clap 5 times” and “stamp 9 times” (use both hands for the counter). Then try “repeat 3 times: clap twice, stamp once”. How many claps and stamps in all?
Practice
1
What does a counter do in a loop?
It keeps track of how many times the loop has run.
2
A clock tower rings its bell 9 times at 9 o’clock. How many iterations does the loop have?
9.
3
Which loop is count-controlled? A Repeat 5 times: draw a star. B Repeat forever: spin. C Repeat until I say stop: clap.
Loop
A
Repeat 5 times: draw a star
B
Repeat forever: spin
C
Repeat until I say stop: clap
A. It runs a set number of times, 5.
4
In “repeat 4 times: clap, clap, stamp”, how many claps and how many stamps are there in all?