University of Toronto · FACULTY OF COMPUTER SCIENCE

CSC108H1 Chap.9 While Loops and Index-Based Search

- one subject, every graph, every model, every mark
6 Chapters3-page Bible
Our own words - no uploaded lecturer files
Updated for this semester
Chapter 9 of 10 · CSC108H1

While Loops and Index-Based Search

Repeating while a condition holds

A while loop checks its condition at the start of every pass and repeats its body while the condition is True. Something in the body must move the loop toward stopping, or it runs forever.

While loops suit problems where you do not know in advance how many passes are needed.

Searching by index

Unlike a for loop, a while loop can walk a string by index and stop at the first match.

The guard that checks i against len(s) must come before any test that reads s[i], so that short-circuit evaluation stops the expression before an index runs past the end.

How while loops are assessed

Worksheet 15 asks you to fill in a missing loop condition and update line from a docstring, to count the steps of a rule applied repeatedly until a value reaches 1, and to recover a header, type contract and examples from a finished loop body.

Each of these is a tracing question in disguise, so practise them with a table rather than by running code.

In this chapter

What this chapter covers

  • 01

    The while condition and when it is checked

  • 02

    Progress lines and infinite loops

  • 03

    Stop conditions and their negation

  • 04

    Guarded searches over string indices

  • 05

    Trace tables for loop variables

  • 06

    Debugging loops in Wing 101

Worked example · free

Count the passes of a halving loop

Q [4 marks]. AskSia-authored practice. Starting from n = 40 and steps = 0, a loop runs while n > 1 and sets n = n // 2 and steps = steps + 1. Trace n and give steps when the loop ends. The marks shown are an AskSia study allocation, not an official University marking scheme.
Figure 9.1.Figure 9.1. The loop halves n with integer division until it is no longer greater than 1. The condition is checked six times: five True answers send control through the body, the sixth, with n equal to 1, sends it down the False arrow with steps equal to 5.n = 40, steps = 0n > 1 ?n = n // 2; steps += 1after loop: steps 5TrueFalsen: 40 20 10 5 2 1
Figure 9.1. The loop halves n with integer division until it is no longer greater than 1. The condition is checked six times: five True answers send control through the body, the sixth, with n equal to 1, sends it down the False arrow with steps equal to 5.
  • 2n takes the values 20, 10, 5, 2 and 1 on successive passes.
  • 1The condition is True five times and False when n is 1.
  • 1steps ends at 5.
Integer division halves n each pass: 40 to 20, 10, 5, 2 and 1. The condition n > 1 is checked six times, True five times and False on the sixth, so the body ran five times and steps is 5 when the loop ends.
Sia tip — Count checks of the condition separately from runs of the body; there is always one more check than there are passes.
Glossary

Key terms

Loop Condition
The expression a while loop checks before each pass, repeating while it is True.
Infinite Loop
A loop whose condition never becomes False because nothing in the body moves it toward stopping.
Guard
A test placed first in an and expression so that a later, riskier test never runs when it would fail.
FAQ

While Loops and Index-Based Search FAQ

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

When you do not know in advance how many passes you need, or when you want to stop as soon as a condition is met, such as finding the first space in a string. A for loop always visits every element.

Why must the length guard come first in a search condition?

Because and stops at the first False. If i has reached len(s), the guard is False and s[i] is never read. Written the other way round, Python reads s[i] first and raises an IndexError when no match exists.

How do I write the condition for a while loop?

State when the loop should stop, then negate it. If you stop when you find a match or run out of characters, the loop continues while there is no match and there are characters left, two conditions joined by and.

What causes an infinite while loop?

A body that never changes what the condition depends on. If the condition checks n and nothing in the body updates n, the condition stays True and the loop never ends. Name the progress line before writing the rest of the body to avoid it.

How do I trace a while loop on paper?

Make a table with one column per variable and a column for the condition. Add a row each time the condition is checked, write its value, and stop at the first row where it is False. That row holds the values the code after the loop will use.

Study strategy

Exam move

For each Week 4 while-loop exercise, write the stop condition in words, negate it into the loop condition, and name the progress line before writing the rest. Trace every loop with a table holding one row per check of the condition. Then break one loop deliberately by removing its progress line or reversing its guard, and predict the failure. Add one loop that should run zero times and check that your table shows no passes.

Keep every table; a wrong row is the quickest way to find which line of a loop you misread.

Working through While Loops and Index-Based Search in CSC108H1? Sia is AskSia’s AI Computer Science tutor — ask any CSC108H1 While Loops and Index-Based Search question and get a clear, step-by-step explanation grounded in how CSC108H1 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.

A+Everything unlocked
Unlocks this Bible + all 21 of your University of Toronto subjects - and 1,000+ Bibles across every Australian university.
Sia - your CSC108H1 tutor, unlimited, worked the way the exam marks it
The full 3-page Bible + practice bank with worked solutions
Chrome extension - sync your LMS so Sia knows your deadlines
Bilingual EN / Chinese on every Bible and every Sia answer
$0.99 Trial
30-day money-back · cancel in one tap · how it works