ICS3U Computer Science • Ontario Grade 11

Corrected exercises: repetition, for and while loops (ICS3U)

Exercises: repetition, for and while loops (ICS3U)

Name: Class: Date:

Solutions

Suggested time: 2 h 30 · No calculator · 11 exercises
https://www.letuteurscientifique.ca/en/exercices/ics3u-loops-repetition

These ten corrected exercises, preceded by a list of direct calculations, cover the third chapter of ICS3U, Introduction to Computer Science, Grade 11, University Preparation, in Ontario: the repetition structure, with the for loop over range and the while loop, counters and accumulators, the sentinel value that ends an entry, nested loops, infinite loops and how to avoid them, and the trace table that follows a loop pass by pass.

What the set covers, the traps it targets

A simulation with the random number generator closes the set. The code is in Python 3; traces, pass counts and loop designs are reasoned the same way in any language, and a line of the solutions says where Java behaves differently.

Exercise 0.1 counts the passes of ten loops over range. By the end, you can write the range that gives the values wanted (exercise 1), fill a trace table with a total and a count (exercise 2), count the passes and the tests of a while loop and find its last value (exercise 3), say why a loop never ends and fix it (exercise 4), and predict what happens when the body changes the variable of a for loop (exercise 5). Part B prints the seat labels of a hall with nested loops (exercise 6), ends an entry with a sentinel at a food bank (exercise 7), corrects five statements (exercise 8), states what a free-throw simulation can and cannot display (exercise 9), and writes the boarding loop of an elevator with two limits (exercise 10).

The thread of the set: a loop is read pass by pass; a for loop gets its number of passes from range before the first pass, a while loop tests its condition before every pass and stops only when its body changes what the condition tests, and whatever must survive the passes is set before the loop. Five traps are named in the solutions: (1) forgetting that range(1, 10) stops at 9, exercises 0.1, 1 and 8; (2) setting the accumulator inside the loop, which resets it on every pass, exercises 2, 6 and 9; (3) a while loop whose condition never becomes False, exercises 4 and 7; (4) expecting a change of the loop variable to change the passes of a for loop, exercises 5 and 8; (5) adding the passes of nested loops instead of multiplying them, or forgetting that the inner loop starts over on each outer pass, exercises 6 and 8. The sentinel counted as data (exercise 7), < against <= in a stop condition (exercises 3 and 10) and a limit tested after the change it forbids (exercise 10) come back as well.

No calculator is needed: every pass count, every trace and every output is worked out by hand, as on a unit test.

  • 11 corrected exercises • 110 points • 150 minutes
  • Self-checking, 104 answers
  • No calculator
Start exercise 0.1 The chapter sheet
Print

Print the homework or the solutions

The homework without solutions, one exercise per page, and the solutions on their own: it comes with your free space. An email is enough, no password, and you come back here.

Create my free space

Already have one? Sign in

Course recap

  • • range(stop) gives 0 to stop - 1; range(start, stop) gives start to stop - 1; range(start, stop, step) moves by step. The stop value is never given.
  • • A countdown needs a negative step: range(10, 0, -1) gives 10 down to 1.
  • • A for loop over range makes as many passes as range has values, fixed when the loop starts.
  • • A while loop tests its condition before every pass; it can make zero passes, and it stops only when its body changes what the condition tests.
  • • A counter or an accumulator is set once, before the loop, and changed in the body; a result is printed after the loop.
  • • A sentinel loop: read, test, use, read again. The sentinel is not counted as data.
  • • Nested loops: the inner body runs (outer passes) × (inner passes) times, and the inner loop starts over on each outer pass.
  • • Trace table: one column per variable, one row per pass, the values at the end of the pass.

Calculations: passes to count

Exercise 0.1: range: the number of passes of ten for loops

10 answers to check

Each loop has the form for i in range(...): followed by its body. Give the number of passes, that is the number of times the body runs.

Method: range(stop) gives 0, 1, ..., stop - 1. range(start, stop) starts at start and stops BEFORE stop. range(start, stop, step) moves by step, up when step is positive and down when it is negative, and still stops before stop. With step 1, the count is stop - start when stop is greater than start, and 0 otherwise; with another step, list the values.

  • a) range(6)
  • b) range(1, 10)
  • c) range(4, 11)
  • d) range(0, 21, 4)
  • e) range(5, 30, 6)
  • f) range(9, 0, -1)
  • g) range(20, 0, -5)
  • h) range(7, 7)
  • i) range(10, 2)
  • j) range(-4, 4)

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
f)
g)
h)
i)
j)
Show the solution

Answers

  • a) 6 passes: 0 to 5
  • b) 9 passes: 1 to 9
  • c) 7 passes: 4 to 10
  • d) 6 passes: 0, 4, 8, 12, 16, 20
  • e) 5 passes: 5, 11, 17, 23, 29
  • f) 9 passes: 9 down to 1
  • g) 4 passes: 20, 15, 10, 5
  • h) 0 passes
  • i) 0 passes
  • j) 8 passes: -4 to 3

Count the values that range gives; the stop value itself is never given.

a)

range(6) starts at 0: 0, 1, 2, 3, 4, 5, so 6 passes.

b)

range(1, 10) gives 1 to 9: 10 - 1 = 9 passes.

Pitfall: counting 10 passes. 10 is the stop value, and range never gives it.

c)

11 - 4 = 7 passes: 4, 5, 6, 7, 8, 9, 10.

d)

0, 4, 8, 12, 16, 20: 6 passes. 20 is given, since 20 is below the stop 21; the next value, 24, is not.

e)

5, 11, 17, 23, 29: 5 passes; the next value, 35, is past 30.

f)

With a negative step, range counts down and stops before 0: 9, 8, ..., 1, so 9 passes.

g)

20, 15, 10, 5: 4 passes; 0 is the stop value.

h)

The start equals the stop, so range gives no value: 0 passes. The body never runs, and Python shows no error.

i)

range(10, 2) counts up by 1 from 10, which is already past 2: 0 passes.

A countdown needs a negative step: range(10, 2, -1) gives 10 down to 3.

j)

4 - (-4) = 8 passes: -4, -3, -2, -1, 0, 1, 2, 3.

Tick the exercises you have done or want to review: a free account, no password, keeps your ticks and your right answers from one visit to the next, tells you which chapter to tackle next and lets you ask for the exercise you are missing. Create your space, an email is enough.

Part A: the basics (/50)

Exercise 1: range stops before its stop value: writing the right header

10 answers to check

A for loop over range runs its body once for each value that range gives. range(start, stop, step) starts at start, moves by step and stops BEFORE it reaches stop: the stop value itself is never given.

Python
for k in range(4, 13):     # line 1
    print(k)               # line 2
  • a) What is the first number printed by the program above? The last one? How many lines are printed?
  • b) Which loop header makes a loop that prints the whole numbers 1 to 10, each one once?
  • c) Which header prints 20, 25, 30, and so on up to 60? How many numbers does it print?
  • d) A countdown must print 12, 9, 6, 3, 0. Which header does it? What is the last number printed by for t in range(12, 0, -3): print(t)?
  • e) A student wants the sum 1 + 2 + ... + 10 and writes total = 0, then for n in range(1, 10): total = total + n, then print(total). What does the program print? What should it print?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) First 4, last 12; 9 lines
  • b) for n in range(1, 11):
  • c) for x in range(20, 61, 5):; 9 numbers
  • d) for t in range(12, -1, -3):; the other loop ends on 3
  • e) It prints 45; it should print 55

range(start, stop, step) gives start, then start + step, and so on, and stops before it reaches stop. The values of range(4, 13) are drawn below.

a)

The first value is the start, 4. The last value is the one just before the stop: 12, since 13 is never given.

Lines printed: 13 - 4 = 9.

b)

To end on 10, the stop must be the next whole number, 11: range(1, 11) gives 1 to 10, 10 passes.

range(1, 10) stops at 9; range(10) gives 0 to 9; range(0, 11) prints an extra 0.

c)

Start 20, step 5, and the last value 60 must be given, so the stop goes past it: range(20, 61, 5). Any stop from 61 to 65 gives the same values.

range(20, 60, 5) stops at 55.

Count: (60 - 20) / 5 + 1 = 9 numbers.

d)

A decreasing range needs a negative step, and its stop lies past the last value wanted: range(12, -1, -3) gives 12, 9, 6, 3, 0. Any stop from -1 down to -3 works.

range(12, 0, -3) stops before 0: it prints 12, 9, 6, 3, and its last number is 3.

range(0, 13, 3) prints the right numbers in increasing order, and range(12, -1, 3) prints nothing: a positive step cannot go down from 12.

e)

range(1, 10) stops at 9: total = 1 + 2 + ... + 9 = 45. The sum wanted, 1 + ... + 10, is 55: the program misses the last term, 10.

Pitfall: the off-by-one error. The loop runs and prints a plausible number, and no message warns. Compare the first and last values of the range, here 1 and 9, with the first and last terms wanted, 1 and 10. The fix: range(1, 11).

41526374859610711812913range(4, 13): the values of k, with the pass number belowstop: never given

Exercise 2: A trace table, one row per pass: a total and a count

9 answers to check

A trace table has one column per variable and one row per pass of the loop; each row holds the values at the END of the pass. An accumulator (here total) and a counter (here count) are set before the loop and changed in its body.

Python
total = 0                     # line 1
count = 0                     # line 2
for n in range(3, 16, 3):     # line 3
    total = total + n         # line 4
    if n % 2 == 0:            # line 5
        count = count + 1     # line 6
print(total, count)           # line 7
  • a) How many passes does the loop make?
  • b) Trace the program. What does total hold at the end of pass 3? What does count hold at the end of pass 4?
  • c) What does line 7 print?
  • d) A student moves line 1 into the loop, indented, just above line 4. What does line 7 print now?
  • e) Another student indents line 7 under line 3, at the level of line 4, as the last line of the body. How many lines does the program print? What is the first one?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 5 passes: n = 3, 6, 9, 12, 15
  • b) total = 18 after pass 3; count = 2 after pass 4
  • c) 45 2
  • d) 15 2
  • e) 5 lines; the first is 3 0

The lines before the loop run once; the body runs once per pass. One row per pass, with the values at the end of the pass: the complete table is below.

a)

range(3, 16, 3) gives 3, 6, 9, 12, 15: 5 passes. 18 would be past the stop 16.

b)

Pass 1: total = 0 + 3 = 3; 3 % 2 == 0 is False, count stays 0.

Pass 2: total = 3 + 6 = 9; 6 is even, count = 1.

Pass 3: total = 9 + 9 = 18; 9 is odd, count stays 1.

Pass 4: total = 18 + 12 = 30; 12 is even, count = 2.

At the end of pass 3, total holds 18; at the end of pass 4, count holds 2.

c)

Pass 5 adds 15: total = 45, and 15 is odd, so count stays 2. Line 7 runs once, after the loop: 45 2.

Check: 3 + 6 + 9 + 12 + 15 = 45, and the even values are 6 and 12.

d)

With total = 0 as the first line of the body, every pass starts again from 0: pass 5 gives total = 0 + 15 = 15. Line 7 prints 15 2; count is still set once, before the loop, and does not change.

Pitfall: an accumulator set inside the loop is reset on every pass, so only the last term survives. Set it once, before the loop.

e)

Indented, the print is part of the body and runs once per pass: 5 lines, from 3 0 to 45 2. The first line shows the values at the end of pass 1: 3 0.

A result that is complete only after the last pass is printed after the loop, at the indentation of the for.

Passntotaln % 2 == 0count133False0269True13918False141230True251545False2Trace table: values at the end of each pass

Exercise 3: A while loop tests before every pass: how many passes, and what is left

10 answers to check

A while loop tests its condition before every pass: when the condition is True, the body runs and Python goes back to the test; when it is False, the loop ends and the line after it runs. The flowchart draws the program below.

The program of the exercise as a flowchartn = 2, steps = 0n < 400 ?n = n * 3steps = steps + 1yesprint(n, steps)no
Python
n = 2                    # line 1
steps = 0                # line 2
while n < 400:           # line 3
    n = n * 3            # line 4
    steps = steps + 1    # line 5
print(n, steps)          # line 6
  • a) How many passes does the loop make? How many times is the condition on line 3 evaluated?
  • b) What does line 6 print?
  • c) What is the value of n the last time the condition is True?
  • d) Line 3 becomes while n < 162:. What does line 6 print? How many passes does the loop make if line 3 becomes while n > 400: instead?
  • e) Line 1 becomes n = int(input()), and the user types a whole number n of at least 1. For which inputs does the original loop make zero passes? Exactly one pass?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Inputs with zero passes ,
Inputs with one pass ,
Show the solution

Answers

  • a) 5 passes; 6 tests
  • b) 486 5
  • c) n = 162
  • d) 162 4; 0 passes, and line 6 prints 2 0
  • e) Zero passes for {n ∈ ℤ | n ≥ 400}; one pass for {n ∈ ℤ | 134 ≤ n ≤ 399}

The test comes before each pass, and after each pass Python goes back to it. Trace one row per test: the table is below.

a)

The tests for n = 2, 6, 18, 54 and 162 are True: 5 passes. The test for n = 486 is False and ends the loop.

The condition is evaluated 6 times: once more than the number of passes, since the last test is the one that stops the loop.

b)

After the loop, n = 486 and steps = 5: line 6 prints 486 5.

c)

The last True test is for n = 162. The body then sets n = 3 × 162 = 486, past 400, and the loop ends at the next test.

Pitfall: expecting the loop to stop at 400. A while loop does not stop in the middle of its body, so its variable can end past the limit.

d)

while n < 162: the tests for 2, 6, 18 and 54 are True, and 162 < 162 is False: 4 passes, and line 6 prints 162 4. With while n <= 162:, the test for 162 would be True and the program would print 486 5: < and <= differ only when n lands on the limit, as with an if.

while n > 400: the first test, 2 > 400, is False: 0 passes, and line 6 prints 2 0. A while loop can run zero times.

e)

Zero passes when the first test is False: n < 400 is False for every n from 400 up, {n ∈ ℤ | n ≥ 400}.

Exactly one pass when n < 400 is True and 3n < 400 is False: 3n ≥ 400 means n ≥ 133.33..., so the whole numbers from 134 to 399.

Check: 133 gives 399, still below 400, so a second pass; 134 gives 402, and the loop stops.

Testn testedn < 400n aftersteps after12True6126True182318True543454True16245162True48656486FalseSix tests, five passes

Exercise 4: Four while loops: which ones end, and why the others never do

12 answers to check

A while loop ends only when its condition becomes False, so its body must change a variable that the condition reads, in a direction that makes the test False. A loop that never ends is an infinite loop: the program prints nothing more, or the same thing forever, until it is stopped by hand (the stop button of the editor, or Ctrl+C in a terminal). The four loops below are four separate programs.

Python
# Loop A
k = 15
while k != 0:
    k = k - 2

# Loop B
total = 0
i = 1
while i <= 5:
    total = total + i
i = i + 1

# Loop C
x = 100
while x > 1:
    x = x // 2

# Loop D
level = 0
target = 5
while level < target:
    level = level + 1
    target = target + 1
  • a) Which of the four loops end?
  • b) For loop C, how many passes are made, and what does x hold after the loop?
  • c) Why does loop A never end? With while k > 0: in its place, how many passes are made, and what does k hold after the loop?
  • d) Why does loop B never end? Once it is fixed, what does total hold after the loop?
  • e) In loop D, what is target - level after 1000 passes?

Type your answers, the page tells you right or wrong 0/12

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) Only C ends; A, B and D never end
  • b) 6 passes; x = 1
  • c) k jumps from 1 to -1 and is never 0; with k > 0, 8 passes and k = -1
  • d) i = i + 1 is outside the body, so i stays 1; fixed, total = 15
  • e) 5: the gap never changes

For each loop, follow the variable of the condition for a few passes, and ask whether it reaches a value that makes the condition False.

a)

A never ends, B never ends, C ends, D never ends. The reasons follow.

b)

C: x = 100, 50, 25, 12, 6, 3, 1; // keeps the whole part, so 25 // 2 = 12 and 3 // 2 = 1.

The test 1 > 1 is False: 6 passes, and x = 1 after the loop.

c)

A: k = 15, 13, 11, ..., 3, 1, then -1, -3, and so on. k stays odd, so k != 0 stays True on every test.

Pitfall: a != condition on a variable that moves by more than 1 can jump over the value it waits for.

With while k > 0, the tests for 15, 13, 11, 9, 7, 5, 3 and 1 are True: 8 passes, and the loop ends with k = -1.

d)

B: i = i + 1 is not indented, so it comes after the loop, not in its body. Python reads the block of a while by its indentation. The body changes total only, i stays 1, and 1 <= 5 is True forever.

Indented, the line gives 5 passes, and total = 1 + 2 + 3 + 4 + 5 = 15.

e)

D: each pass adds 1 to level and 1 to target, so target - level stays 5 - 0 = 5. After 1000 passes, level = 1000 and target = 1005, and level < target is still True.

Pitfall: the body does change the variables of the condition, but never in a way that makes it False. Ask what the body does to the condition, not only to the variables.

k testedk != 015True13True......3True1True-1True-3TrueLoop A: k jumps over 0

Exercise 5: Changing the loop variable inside a for loop does not change the passes

8 answers to check

A for loop over range takes its next value from range at the top of every pass, whatever the body did to the loop variable. A while loop, on the other hand, tests the variable itself.

Python
for i in range(5):         # line 1
    print(i)               # line 2
    i = i + 2              # line 3
print('after:', i)         # line 4
  • a) How many lines do lines 1 to 3 print? What is the last number they print?
  • b) What does line 4 print after the word after:?
  • c) A student rewrites lines 1 to 3 as a while loop: i = 0, then while i < 5:, with print(i), i = i + 2 and i = i + 1 in the body. How many lines does this version print? What is the second number printed?
  • d) n = 3, then for i in range(n): n = n + 1, then print(n). How many passes does the loop make? What is printed?
  • e) Which header prints 0, 3, 6, 9 with a for loop?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 5 lines; the last number is 4
  • b) 6
  • c) 2 lines: 0 and 3
  • d) 3 passes; 6 is printed
  • e) for i in range(0, 10, 3):

A for loop over range does not test its variable: at the top of each pass it takes the next value of range and puts it in i, whatever the body stored there. The trace is below.

a)

Pass 1: i = 0, print 0, then i = 2. Pass 2: range gives 1, so i = 1, and the 2 is lost. The loop prints 0, 1, 2, 3, 4: 5 lines, and the last number is 4.

Pitfall: thinking that i = i + 2 skips values. It changes i until the end of the pass only.

In Java, the same change in for (int i = 0; i < 5; i++) does skip values, since Java's for tests i itself: it prints 0 and 3. This is one place where Python and Java differ.

b)

After the last pass, i holds 4 + 2 = 6: line 4 prints after: 6. The loop variable keeps its last value after a for loop.

c)

A while loop tests i itself. Pass 1: print 0, then i = 2, then i = 3. Pass 2: 3 < 5, print 3, then i = 5, then i = 6. The test 6 < 5 is False.

2 lines: 0 and 3. This version gives the Java result, not the result of lines 1 to 3.

d)

range(n) is computed once, when the loop starts: range(3), so 3 passes. Each pass adds 1 to n: 3 + 3 = 6, and print(n) shows 6. Changing n in the body does not lengthen the loop.

e)

To move by 3, give range a step: range(0, 10, 3) gives 0, 3, 6, 9.

range(0, 9, 3) stops before 9. range(10) with i = i + 3 in the body prints all ten numbers 0 to 9, for the reason of a).

Passi from rangeprintedi at the end10022113322443355446for: range gives i at the top of each pass

Part B: problems and reasoning (/50)

Exercise 6: Problem: nested loops print the seat labels of a hall

9 answers to check

A school drama club prints a label for every seat of its hall: 4 rows of 6 seats, rows and seats numbered from 1, as in the plan. The program uses two nested loops: the inner loop runs its whole course on each pass of the outer loop.

StageRow 1Row 2Row 3Row 4123456seat
Python
for row in range(1, 5):                      # line 1
    for seat in range(1, 7):                 # line 2
        print('Row', row, 'seat', seat)      # line 3
  • a) How many labels does the program print? How many times does the loop of line 2 start over?
  • b) Which label is printed right after Row 2 seat 6?
  • c) To count the labels, count = 0 is placed before line 1, count = count + 1 under line 3 in the inner body, and print(count) after both loops. What is printed? A student places count = 0 between lines 1 and 2 instead, indented in the outer body. What is printed now?
  • d) A classmate writes the program with while loops: row = 1, seat = 1, then while row <= 4:, and in its body while seat <= 6: with the print and seat = seat + 1, then row = row + 1 after the inner loop. How many labels does this version print? Which change makes it print the 24 labels?
  • e) The club moves to an auditorium of 6 rows, where row r has 2r + 8 seats. Line 1 becomes for row in range(1, 7): and line 2 becomes for seat in range(1, 2 * row + 9):. How many labels are printed? How many seats has row 6?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 24 labels; line 2 starts its loop 4 times
  • b) Row 3 seat 1
  • c) 24; then 6
  • d) 6 labels; set seat = 1 inside the outer loop, just before the inner while
  • e) 90 labels; 20 seats in row 6

In nested loops, the inner loop runs its whole course, from its first value to its last, on each pass of the outer loop. The order of the 24 labels is drawn below.

a)

The outer loop gives row = 1, 2, 3, 4: 4 passes. On each of them, the inner loop gives seat = 1 to 6: 6 passes. Line 3 runs 4 × 6 = 24 times, and line 2 starts its loop 4 times, once per row.

Pitfall: adding the passes, 4 + 6 = 10. Nested passes multiply.

b)

After Row 2 seat 6, the inner range is finished. The outer loop takes row = 3, and the inner loop starts again at seat = 1: Row 3 seat 1.

c)

count = 0 before line 1 runs once, and the inner body adds 1 per label: 24.

Between lines 1 and 2, count = 0 runs at the start of each row: the counts of rows 1 to 3 are lost, and print(count) shows the last row only, 6.

Pitfall: the accumulator reset inside a loop, here inside the outer one.

d)

seat = 1 runs once, before both loops. Row 1: seat goes from 1 to 6, 6 labels, and the inner while ends with seat = 7. Rows 2, 3 and 4: the test 7 <= 6 is False at once, so the inner body never runs. 6 labels in all.

The fix: seat = 1 as the first line of the outer body, just before the inner while, so that each row starts again at seat 1. A for loop needs no such line: range starts over each time the inner for starts.

What starts over for each row goes inside the outer loop; what counts the whole hall goes before both loops.

e)

Row r: range(1, 2r + 9) gives 1 to 2r + 8, so 2r + 8 seats: 10, 12, 14, 16, 18, 20 for rows 1 to 6.

The inner range depends on the outer variable, so the passes add up row by row: 10 + 12 + 14 + 16 + 18 + 20 = 90 labels. Row 6 has 2 × 6 + 8 = 20 seats.

StageRow 1123456Row 2789101112Row 3131415161718Row 4192021222324123456seatOrder of the 24 labels: each row starts again at seat 1

Exercise 7: Problem: a sentinel value ends the entry at a food bank

8 answers to check

At a food bank, a volunteer weighs each donated box and types its weight in kilograms; typing 0 ends the entry. The 0 is a sentinel: a value that marks the end of the data and is not itself a weight. The program displays the number of boxes, the total weight and the average weight of a box. The table gives the five entries of one evening, in the order they are typed.

Entry12345
Typed12.58.020.54.00
Python
count = 0                                    # line 1
total = 0                                    # line 2
weight = float(input('Weight (kg): '))       # line 3
while weight != 0:                           # line 4
    count = count + 1                        # line 5
    total = total + weight                   # line 6
    weight = float(input('Weight (kg): '))   # line 7
print(count, 'boxes,', total, 'kg')          # line 8
print('Average:', total / count, 'kg')       # line 9
  • a) Trace the program with the five entries. What does line 8 print?
  • b) What does line 9 print?
  • c) Why is the weight read twice, on line 3 and on line 7?
  • d) A classmate deletes line 3, writes weight = 1 before the loop, and moves line 7 to the top of the body, before line 5. With the same five entries, what do lines 8 and 9 print?
  • e) One evening no box arrives, and the volunteer types 0 first. How many passes does the original loop make, and what happens on line 9?

Type your answers, the page tells you right or wrong 0/8

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 4 boxes, 45.0 kg
  • b) Average: 11.25 kg
  • c) The first weight must be known before the test; line 7 reads the next one at the end of each pass
  • d) 5 boxes, 45.0 kg, then Average: 9.0 kg: the sentinel is counted as a box
  • e) 0 passes; a ZeroDivisionError stops the program on line 9

A sentinel loop reads one value before the loop, tests it, and reads the next one at the end of each pass: the test always sees the newest value, and the sentinel is tested before it can be counted. The trace is below, and a program that survives an empty evening below it.

a)

Line 3 reads 12.5. Pass 1: count = 1, total = 12.5, line 7 reads 8.0. Pass 2: count = 2, total = 20.5, then 20.5 is read. Pass 3: count = 3, total = 41.0, then 4.0. Pass 4: count = 4, total = 45.0, and line 7 reads 0.

The test 0 != 0 is False: line 8 prints 4 boxes, 45.0 kg.

b)

45.0 / 4 = 11.25: line 9 prints Average: 11.25 kg.

c)

The condition on line 4 needs a weight before the first pass: line 3 reads it, the priming read. Line 7 reads the next weight at the end of each pass, just before the test.

Without line 7, weight would never change and the loop would never end.

d)

weight = 1 only lets the loop start. Each pass now reads, then counts: the fifth pass reads 0, counts it as a box and adds 0 kg. Then 0 != 0 is False.

Line 8 prints 5 boxes, 45.0 kg and line 9 prints Average: 9.0 kg, too low.

Pitfall: the sentinel counted as data. Test a value before using it: read, test, use, read again.

e)

Line 3 reads 0 and the test is False at once: 0 passes, count = 0. Line 8 prints 0 boxes, 0 kg, then total / count is 0 / 0, and the program stops with a ZeroDivisionError.

The corrected program tests count > 0 before dividing, and prints No box weighed otherwise.

Python
count = 0
total = 0
weight = float(input('Weight (kg): '))
while weight != 0:
    count = count + 1
    total = total + weight
    weight = float(input('Weight (kg): '))
print(count, 'boxes,', total, 'kg')
if count > 0:
    print('Average:', total / count, 'kg')
else:
    print('No box weighed')
Passweight read lasttest beforecounttotalbefore12.50018.0True112.5220.5True220.534.0True341.040True445.0testFalse445.0Sentinel loop: read, test, use, read again

Exercise 8: Five statements to correct

10 answers to check

Each statement below was written by a student. Say whether it is true or false, answer the question that checks it, and correct the false ones.

  • a) « The loop for i in range(1, 10): runs its body 10 times. » How many passes does it make?
  • b) « The body of a while loop always runs at least once. » How many passes does x = 5, then while x < 3: x = x + 1 make?
  • c) « In for i in range(4):, the line i = 10 in the body ends the loop after the first pass. » How many passes does that loop make?
  • d) « for r in range(3):, with for c in range(4): print(r, c) inside it, prints 7 lines. » How many lines does it print?
  • e) « For every whole number n, the loop for i in range(n): and the loop i = 0, then while i < n:, with i = i + 1 as the last line of its body, make the same number of passes. » How many passes does each one make for n = 6?

Type your answers, the page tells you right or wrong 0/10

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) False: 9 passes
  • b) False: 0 passes
  • c) False: 4 passes
  • d) False: 12 lines
  • e) True: 6 passes each
a)

False. range(1, 10) gives 1 to 9: 9 passes. The stop value is never given.

Correct statement: « for i in range(1, 10): runs its body 9 times; range(1, 11) runs it 10 times. »

b)

False. A while loop tests its condition BEFORE each pass: 5 < 3 is False at once, so 0 passes, and x stays 5.

Java also has a do while loop, which tests after the body and so runs at least once; Python has no such loop.

Correct statement: « The body of a while loop can run zero times, when its condition is False on the first test. »

c)

False. range gives the next value at the top of each pass, so i = 10 is undone: i takes 0, 1, 2, 3, and the loop makes 4 passes.

Correct statement: « Changing the variable of a for loop over range does not change its number of passes. »

d)

False. The inner loop runs its 4 passes on each of the 3 outer passes: 3 × 4 = 12 lines. 7 is 3 + 4, a sum where the passes multiply.

Correct statement: « This program prints 3 × 4 = 12 lines. »

e)

True. For n = 6, range(6) gives 0 to 5, 6 passes; the while loop tests i = 0, 1, ..., 5 as True and 6 < 6 as False, 6 passes.

For n = 0 or a negative n, range(n) is empty and 0 < n is False at once: 0 passes for both. A for loop over range is a while loop with its counter written for you.

Exercise 9: Problem: simulating free throws with random

9 answers to check

A basketball player makes about 7 free throws out of 10. A student simulates a practice of 25 shots: random.randint(1, 10) returns a whole number from 1 to 10, each one equally likely, a new one at each call, and a draw of 7 or less counts as a made shot.

Python
import random                          # line 1
made = 0                               # line 2
for shot in range(25):                 # line 3
    if random.randint(1, 10) <= 7:     # line 4
        made = made + 1                # line 5
print(made, 'made out of 25')          # line 6
  • a) How many times is randint called during one run? Which values can line 6 display for made?
  • b) How many of the 10 values of randint count as a made shot? How many would count if line 4 used < 7? Two runs display 16, then 19: is one of them wrong?
  • c) In one run, the first eight draws are 3, 9, 7, 10, 1, 8, 5, 7. What does made hold after the eighth pass?
  • d) A student moves line 2 into the loop, just above line 4. Which values can line 6 display now?
  • e) A second program shoots until 10 shots are made: made = 0 and shots = 0, then while made < 10:, with shots = shots + 1 and the test of line 4 in the body. What is the smallest number of shots it can display? With the eight draws of c) followed by 2, 9, 6, 4, 8, 1, 5, what does it display?

Type your answers, the page tells you right or wrong 0/9

a)
Values of made ,
b)
c)
d)
Values of made ,
e)
Show the solution

Answers

  • a) 25 calls; any whole number from 0 to 25
  • b) 7 values; 6 with < 7; neither run is wrong
  • c) made = 5
  • d) 0 or 1 only
  • e) At least 10 shots; 15 shots with these draws

What can be said of a run is the set of values it can display, not the value it will display. A trace with given draws, as in c), is a test of the logic, not a prediction.

a)

Line 4 is in the body: one call per pass, 25 calls.

made goes up by 0 or 1 per pass: from 0, if every draw is 8, 9 or 10, up to 25, if every draw is 7 or less. Line 6 can display any whole number from 0 to 25.

b)

The draws 1 to 7 count as made: 7 values out of 10, the 70 % of the player. With < 7, the draw 7 is a miss: 6 values, 60 %.

Each run draws new numbers, so 16 and 19 are both possible: neither run is wrong. Over many runs, made averages about 70 % of 25, that is 17.5, a value no single run displays, since made is a whole number.

c)

3 made (1), 9 missed, 7 made (2), 10 missed, 1 made (3), 8 missed, 5 made (4), 7 made (5).

made = 5 after the eighth pass. The test 7 <= 7 is True: the boundary draw counts as made.

d)

made = 0 in the body runs at the top of every pass, so the last pass starts again from 0 and adds 0 or 1: line 6 can display 0 or 1 only.

Pitfall: the accumulator reset inside the loop.

e)

The loop ends when made reaches 10, and made goes up by at most 1 per shot: at least 10 shots, when the first ten draws are all 7 or less.

With the draws given: after the eight of c), made = 5; then 2 made (6), 9 missed, 6 made (7), 4 made (8), 8 missed, 1 made (9), 5 made (10). 8 + 7 = 15 shots.

No largest value can be given: a run of misses can last any number of shots. A for loop fixes the number of passes before it starts; a while loop runs until something happens.

ShotDraw<= 7 ?made13made129missed137made2410missed251made368missed375made487made5The eight draws of part c)

Exercise 10: Problem: the load limit of an elevator, from the specification to the program

9 answers to check

The elevator of an apartment building carries at most 8 people and at most 630 kg. People board in the order of the queue, and the weights are typed one at a time, in kilograms, as whole numbers. Before each person steps in, the controller checks both limits: the person boards only if the car will then hold at most 8 people and at most 630 kg; otherwise boarding stops for this trip, and that person waits for the next one. The queue is always longer than one trip.

Write a program that displays the number of people who board, the load, and the weight of the first person who waits. The two limits are constants of the program. The table gives the queue of one morning.

Place in the queue12345678910
Weight (kg)826495715890771026673
  • a) Write the program. For the queue in the table, how many people board, and what is the load?
  • b) What is the weight of the first person who waits?
  • c) The queue is now nine people of 70 kg each. How many people board, and what is the load?
  • d) A classmate writes people = 0 and load = 0, then while load <= 630:, with weight = int(input()), load = load + weight and people = people + 1 in the body. For the queue in the table, what load and how many people does that version report?
  • e) In the table, the person in place 8 weighs 93 kg instead of 102 kg. Does she board? Does she board if the condition is written load + weight < MAX_LOAD?

Type your answers, the page tells you right or wrong 0/9

a)
b)
c)
d)
e)
Show the solution

Answers

  • a) 7 people, 537 kg
  • b) 102 kg
  • c) 8 people, 560 kg: the limit of 8 people stops boarding
  • d) 639 kg and 8 people: 9 kg over the limit
  • e) Yes, 630 kg is allowed; no with <

IPO chart. Input: the weights, one at a time, in the order of the queue. Processing: a while loop that lets the next person in only if both limits still hold with that person aboard, a counter people and an accumulator load. Output: the number of people, the load, and the weight of the first person who waits.

The test comes before the person is added, as for the sentinel of exercise 7: read, test, add, read again. When the loop ends, weight holds the weight of the person who waits. The program is below, and the trace of the morning queue below it.

a)

82 (1 person, 82 kg), 64 (2, 146), 95 (3, 241), 71 (4, 312), 58 (5, 370), 90 (6, 460), 77 (7, 537).

Next weight 102: 7 < 8 is True, but 537 + 102 = 639 <= 630 is False, so the and is False.

7 people board, with a load of 537 kg.

b)

The first person who waits weighs 102 kg: the program displays Next in line: 102 kg.

c)

After 8 people, load = 8 × 70 = 560, and 560 + 70 = 630 <= 630 is True, but 8 < 8 is False.

8 people, 560 kg: here the limit of 8 people stops boarding, although the ninth person would fit by weight. Both limits are needed in the condition.

d)

This version adds first and tests after. The person in place 8 is added: load = 537 + 102 = 639, people = 8. Then 639 <= 630 is False and the loop ends.

It reports 639 kg and 8 people: 9 kg over the limit, and it never checks the limit of 8 people.

Pitfall: a while loop tests between passes, never inside them, so a limit must be tested before the change it forbids.

e)

537 + 93 = 630, and 630 <= 630 is True: she boards, 8 people and 630 kg. « At most 630 kg » includes 630.

With <, 630 < 630 is False and she waits, although the car may carry her. < in place of <= is wrong on the boundary value only.

Python
MAX_PEOPLE = 8
MAX_LOAD = 630      # kg
people = 0
load = 0
weight = int(input('Next weight (kg): '))
while people < MAX_PEOPLE and load + weight <= MAX_LOAD:
    people = people + 1
    load = load + weight
    weight = int(input('Next weight (kg): '))
print(people, 'people,', load, 'kg')
print('Next in line:', weight, 'kg')
Personkgpeople < 8loadResult182True82boards264True146boards395True241boards471True312boards558True370boards690True460boards777True537boards8102True537 + 102 = 639waitsEach person is tested before boarding
Something missing from this set? A type of exercise your teacher gives, a problem you are stuck on, a mistake you spotted: tell me, I read every request.

Sending goes through your free space: that is how I can answer you and tell you when the exercise is added. An email is enough, no password. Create your space. Rather not create an account? Write to me directly.

What is it about?
I read every request myself, nobody else sees it. No need to write your name or your school.
When your request is dealt with, you hear about it by email and in your space.

By sending, you agree that I read your request to answer it. It is kept with your account, erased with it, and never published: privacy policy.

© Ahmed Squalli Houssaini. Exercise set published at www.letuteurscientifique.ca/en/exercices/ics3u-loops-repetition. Free for personal and classroom use; republishing it elsewhere requires written permission (legal notice).

Preparing for an ICS3U unit test?

I tutor Grade 11 computer science in English or in French, online. Get in touch for a first session: loops and trace tables come back in every later unit of the course.

Site by Studio Squalli