ICS3U Computer Science • Ontario Grade 11

Revision sheet: repetition, for and while loops (ICS3U)

This sheet is not a summary of the loops chapter of ICS3U, Introduction to Computer Science, Grade 11: you already have your notes.

What the sheet covers

It answers one question only, what makes students lose marks on for and while loops, and which precise gesture avoids each loss.

Most loop mistakes are silent: a range one value short, a total reset on every pass, a counter that never restarts all run to the end and print a plausible number. A trace table, one row per pass, shows them. The code is in Python 3, and every value on this sheet comes from a program that was run.

  • 8 mistakes that cost marks
  • 4 figures
  • 15 min reading
Do the chapter's exercises

The thread of the chapter

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.

Topics covered

  • Repetition structure
  • For loop
  • While loop
  • Range function
  • Loop counter
  • Accumulator
  • Sentinel value
  • Infinite loop
  • Nested loops
  • Trace table
  • Off-by-one error
  • Random number generator

The essentials

Two loops, two ways to stop

  • • for i in range(...): makes one pass per value of range. The values are fixed when the loop starts: changing i or the stop variable in the body changes nothing.
  • • 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.
  • • while condition: tests BEFORE every pass. When the test is False, the loop ends; it can make zero passes.
  • • A while loop stops when its condition becomes False. When the condition tests variables, the body must change one of them, in a direction that makes the test False; otherwise the loop is infinite.
  • • Use for when the number of passes is known before the loop starts; use while when the loop runs until something happens.
for: range gives the next valuestart rangevalue left ?i = next valuebodyyesafter the loopnowhile: the condition decidesset the variablecondition ?bodyupdate the variableyesafter the loopno
On the left, range hands out the next value until none is left; on the right, the test runs before each pass, and the body must change what the test reads to make it False.

Before, in, after: where each line goes

  • • Before the loop: the counters and accumulators, set once (count = 0, total = 0), and the first read of a sentinel loop.
  • • In the body: what happens once per pass, the update (total = total + x) and, for a while loop, the change of its variable.
  • • After the loop, at the indentation of for or while: the result, printed once.
  • • In nested loops, what must start over for each outer pass (an inner counter, a seat number) goes inside the outer loop, just before the inner one.
  • • Python reads a block by its indentation: a line moved four spaces left leaves the loop.

When the output has too many lines, the print is in the body; when the total is too small, the accumulator is in the body.

The rules in table form

Each row reads from left to right: the assumptions, then the result. A red cell is not an answer, it is the finding that the form settles nothing and the instruction to rewrite it. Every case is followed by a worked example.

range, value by value

The passes of for i in range(...), one row per form. Every row was run in Python 3.

CallValues givenPasses
range(5) 0, 1, 2, 3, 4 5

Example: for i in range(5): print(i) prints 0 first and 4 last.

range(2, 7) 2, 3, 4, 5, 6 7 - 2 = 5

Example: The start is given, the stop is not: 7 does not appear.

range(1, 11) 1 to 10 10

Example: To end on a value, the stop is the next whole number: range(1, 11) for 1 to 10.

range(0, 25, 5) 0, 5, 10, 15, 20 5

Example: With a step, list the values: 25 is the stop and is not given.

range(10, 0, -2) 10, 8, 6, 4, 2 5

Example: A negative step counts down and stops before 0.

range(6, 6) none 0

Example: The start 6 equals the stop 6: the body never runs, and Python shows no error.

range(10, 0) none 0 not a countdown

Example: range(10, 0) counts up from 10 and is already past 0: no value at all.

What to do: A countdown needs a negative step: range(10, 0, -1) gives 10 down to 1.

Check a range by its first value, its last value and its count, before writing the body.

The mistakes that cost marks

These are the errors I correct most often in session. Each one costs marks on a paper, even when the reasoning behind it is right.

1. A range one value short

1 mark, and a result wrong by one term that looks plausible

What not to write

“Attendance for days 1 to 30 of a month: for day in range(1, 30):”

What to write

“for day in range(1, 31): gives the days 1 to 30. range(1, 30) stops at day 29.”

Why: range never gives its stop value: the stop is one past the last value wanted.

2. The total set inside the loop

1 to 2 marks: the program runs and prints a wrong total

What not to write

“for day in range(5): total = 0, then rain = int(input()), then total = total + rain: the rain of the five days is 4 + 0 + 7 + 2 + 5 = 18 mm.”

What to write

“total = 0 goes before the loop. Inside the body, it resets the sum on every pass, and the program prints 5, the rain of the last day.”

Dayraintotal144204371142135518total = 0 before the loopDayraintotal144200377422555total = 0 inside the loop
Same five entries: with total = 0 before the loop the last row reads 18; with total = 0 inside it, each row starts again from 0 and the last one reads 5.

Why: A line in the body runs once per pass; an accumulator must survive the passes, so it is set once, before them.

3. A != condition that jumps over its value

the whole question: the program never ends

What not to write

“k = 10, then while k != 0: k = k - 3 counts down to 0.”

What to write

“k takes 10, 7, 4, 1, then -2, and never equals 0: the loop is infinite. Write while k > 0:, which ends after 4 passes with k = -2.”

Why: A variable that moves by more than 1 can skip the value a != test waits for; a > or < test cannot be skipped.

4. The update left outside the body

the whole question: an infinite loop

What not to write

“i = 1, then while i <= 10: print(i), and i = i + 1 on the next line, not indented.”

What to write

“Indent i = i + 1 under the while, at the level of print(i). Outside the body, it never runs during the loop, i stays 1, and 1 is printed forever.”

Why: Python reads the body of a loop by its indentation; a while loop on a variable ends when its body changes that variable towards the stop.

5. Changing the variable of a for loop

1 to 2 marks on a predicted output

What not to write

“for i in range(10): print(i), then i = i + 1, prints every other number.”

What to write

“It prints 0 to 9, all ten numbers: range gives the next value at the top of each pass. To print every other number, write for i in range(0, 10, 2):.”

Why: A for loop over range does not test its variable; Java's for loop does, which is why the same idea works in Java and not in Python.

6. Nested passes added instead of multiplied

1 mark, and a wrong count in every later question

What not to write

“for day in range(5):, then for period in range(8): print(day, period) inside it: 5 + 8 = 13 lines.”

What to write

“The inner loop runs its 8 passes on each of the 5 days: 5 × 8 = 40 lines.”

day 112345678day 2910111213141516day 31718192021222324day 42526272829303132day 5333435363738394012345678period5 days x 8 periods: the inner body runs 40 times
Each row is one pass of the outer loop and runs the 8 inner passes; the numbers give the order of the 40 lines, and each row starts again at period 1.

Why: The inner loop runs its whole course on each pass of the outer loop, starting again from its first value.

7. An inner while counter set only once

1 to 2 marks, and a program that works for the first row only

What not to write

“p = 1 before both loops, then while d <= 5: with while p <= 8: inside it, prints the 40 periods.”

What to write

“p = 1 goes inside the outer loop, just before the inner while. Set once, p ends day 1 at 9, the inner test is False for days 2 to 5, and only 8 lines are printed.”

Why: range starts over each time an inner for starts; a while counter starts over only if a line sets it back.

8. The sentinel counted as data

1 to 2 marks: the count is one too high, and the average too low

What not to write

“x = 1, then while x != 0: x = int(input()), count = count + 1: the 0 that ends the entry is not counted.”

What to write

“Read once before the loop and again at the end of the body: x = int(input()), while x != 0: count = count + 1, x = int(input()). The test then sees each value before it is used.”

Why: Read, test, use, read again: a value read at the top of the body is used before the condition has seen it.

Which method to choose

for or while?

Ask whether the number of passes is known when the loop starts.

  • If the passes are counted in advance: a number of days, of shots, of seats, a range of values → a for loop over range, with the range checked by its first value, last value and count

    Example: for shot in range(25): for 25 simulated shots

  • If the loop runs until something happens: a sentinel, a threshold reached, a limit → a while loop, with the variable of its condition set before it and changed in its body

    Example: while height <= 200: height = height + 18

  • If the entry ends with a special value → a sentinel loop: read before the loop, test, use, read again at the end of the body

    Example: weight = float(input()), then while weight != 0:

  • If each item of one group goes with each item of another → nested loops, the inner one inside the body of the outer one

    Example: for row in range(1, 5): with for seat in range(1, 7): inside it

A for loop over range is a while loop whose counter Python writes for you: when the count is known, it is the safer choice.

How the answer is expected to be written

A marker ticks steps. Here they are in order, with the concluding sentence expected word for word.

Tracing a loop on a unit test

When to use it: « What does this program display? », « How many times does line 4 run? », « What is the final value of total? »

  1. 1 Write the lines before the loop once: the starting value of each variable.
  2. 2 Draw the trace table: one column per variable, one for the condition of a while loop, one row per pass.
  3. 3 For a for loop, list the values of range first; for a while loop, write each test with its value before the pass.
  4. 4 Fill each row with the values at the end of the pass, in the order of the lines of the body.
  5. 5 Stop at the first False test of a while loop, then run the lines after the loop once.

Concluding sentence

“Test 11: height = 205, 205 <= 200 is False, so the loop ends after 10 passes, and line 6 prints 10 years, 205 cm.”

The trap: Stopping the trace when the variable reaches the limit, instead of at the first False test: the last pass often goes past the limit.

Marking: A common split: 1 mark per correct row, 1 for the final output.

Writing a loop from a specification

When to use it: « Write a program that reads ... until ... », « that adds ... for each ... »

  1. 1 Decide the kind of loop: for when the passes are counted in advance, while otherwise.
  2. 2 Write what goes before the loop: counters and accumulators at 0, the first read of a sentinel loop.
  3. 3 Write the condition from the words: « at most », « up to and including » give <=; « below », « under » give <.
  4. 4 Write the body: the update, then, for a while loop, the line that changes the variable of the condition.
  5. 5 Trace the loop on the smallest case (zero passes), on one pass and on the boundary value.

Concluding sentence

“With 0 typed first, the loop makes 0 passes and count = 0, so the program tests count > 0 before dividing.”

The trap: Testing only a typical entry, which does not show the zero-pass case or the boundary.

Marking: A common split: 1 mark for the initial values, 1 for the condition, 1 for the update, 1 for the output.

Check before you hand in

Five minutes of checking recover more marks than one more problem started in a hurry.

  • The pass count by formula

    For range(start, stop) with step 1, the count is stop - start; compare it with your trace.

    range(3, 11) makes 8 passes: a trace with 9 rows has one row too many.

  • The variable of the condition changes

    In every while loop, point to the line of the body that moves the condition towards False.

    while i <= 5: with no i = ... in its body is an infinite loop.

  • The zero-pass case

    Ask what the program does when the loop makes no pass: an empty entry, a start already past the limit.

    A sentinel typed first gives count = 0: an average total / count then stops the program.

  • One initialisation per accumulator

    Look at the indentation of total = 0 and count = 0: the same column as the for or the while, not one step to the right.

    A total equal to the last entry means total = 0 is in the body.

The typical problem, taken apart

How many years before a sapling passes 2 m?

A tree nursery plants a sapling 25 cm tall. In this model it grows 18 cm a year. Write a loop that finds after how many whole years it first passes 2 m, that is 200 cm, and trace it.

Python
height = 25        # cm, at planting
years = 0
while height <= 200:
    height = height + 18
    years = years + 1
print(years, 'years,', height, 'cm')

Step 1

Kind of loop: the number of years is the unknown, so a while loop. Before it: height = 25 and years = 0.

Why

A for loop needs its number of passes before it starts; here the loop runs until the height passes 200.

Step 2

Condition: « first passes 200 cm » means the loop goes on while height <= 200, and stops at the first height above 200.

Why

The condition says when to go on, the opposite of the stop rule: the opposite of height > 200 is height <= 200.

Step 3

Body: height = height + 18, which moves the condition towards False, then years = years + 1.

Why

Without the change of height, the test would stay True forever; the counter years records the passes.

Step 4

Trace: the tests for 25, 43, 61, ..., 169, 187 are True, 10 passes; the eleventh test, 205 <= 200, is False. The program prints 10 years, 205 cm.

height testedheight <= 200height afteryears25True43143True61261True79379True97497True1155115True1336133True1517151True1698169True1879187True20510205FalseEleven tests, ten passes

Why

The trace stops at the first False test, not at 200: the last pass takes the height from 187 to 205.

Step 5

Check by arithmetic: 25 + 18 × 9 = 187, still at most 200, and 25 + 18 × 10 = 205, above 200.

Why

A second method on the boundary catches a < written in place of <=, or a trace that stopped one row early.

The conclusion, written out

“The loop makes 10 passes: the sapling first passes 2 m after 10 years, at 205 cm.”

The classic mistake on this problem: Writing while height < 200: gives the same answer here, since no height of the model equals 200, but it stops one year early for a height that lands exactly on the limit: say why your condition is <= and not <.

Learn by heart

  • • range(start, stop) never gives stop: range(1, 11) for 1 to 10.
  • • A countdown needs a negative step: range(10, 0, -1).
  • • for: passes fixed when the loop starts; while: a test before every pass.
  • • A while body must change what its condition reads.
  • • Counters and accumulators before the loop, the result after it.
  • • Sentinel loop: read, test, use, read again.
  • • Nested loops: passes multiply, and the inner loop starts over.
  • • Trace table: one row per pass, the values at the end of the pass.

Frequently asked questions

Why does range(1, 10) stop at 9 in Python?

Because range never gives its stop value: it starts at the first number and stops just before the second. So range(1, 10) gives the numbers 1 to 9, nine values. To go up to 10, write the next whole number as the stop, range(1, 11). This rule makes range(n) give n values, from 0 to n minus 1.

When should I use a for loop instead of a while loop?

Use a for loop when you know the number of passes before the loop starts: a number of days, of shots, a range of values. Use a while loop when the loop must run until something happens: a sentinel value is typed, a threshold is passed, a limit is reached. A while loop needs its variable set before it and changed in its body.

Why does my while loop never stop?

A while loop stops only when its condition becomes false, so its body must change the variable the condition reads. Check three things: the update line is indented inside the loop, it moves the variable towards the stop, and a not-equal test cannot be jumped over, as with a countdown by 3 waiting for 0. Prefer greater than or less than in such tests.

How do you make a trace table for a loop?

Write one column per variable, plus one for the condition of a while loop, and one row per pass. Start with the values set before the loop. For each pass, write the values at the end of the pass, line by line. Stop at the first false test, then run the lines after the loop once. The last row gives the output.

How many times does the inside of a nested loop run?

The inner body runs the number of outer passes multiplied by the number of inner passes, because the inner loop runs its whole course on each outer pass. Five days of eight periods give forty passes, not thirteen. When the inner range depends on the outer variable, add the inner passes row by row instead.

Mark this sheet as read or add it to your favourites: a free account, no password, keeps your read sheets and favourites from one visit to the next, tells you which chapter to tackle next and lets you ask for the method or exercise you are missing. Create your space, an email is enough.

Practise it

Corrected exercises: Repetition: for and while loops, ICS3U

A method is proved on a paper, not on a sheet. The set for the same chapter takes each of these traps into a problem, with the solution written out step by step.

  • 11 corrected exercises
  • 110 points
  • 150 minutes
Do the exercises
Something missing from this sheet? A method, a trap, an exercise to practise it, 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. Revision sheet published at www.letuteurscientifique.ca/en/fiches/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.

Site by Studio Squalli