University of Toronto · FACULTY OF COMPUTER SCIENCE

CSC108H1 Chap.8 For Loops and the Accumulator Pattern

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

For Loops and the Accumulator Pattern

Repeating with a for loop

A for loop executes its body one time per element of a sequence, and on each pass the loop variable refers to the next element.

Week 4 pairs it with the accumulator pattern: initialise a variable before the loop, update it when the current character matters, and return it afterwards.

Counting, building and deciding

The starting value comes from the kind of answer: 0 to count or add, the empty string to build text, False for an any question and True for an every question.

Boolean accumulators flip once and never flip back, which is why those loops usually have no else.

How loops are assessed

Worksheet 14 gives three for-loop functions: one counts characters with a property, one decides whether every character qualifies, and one builds a new string.

Assignment 2 opened with a counting task that had to use a provided constant, and the annotated worksheet asks the question that comes before any code: is this an accumulator problem or a search problem?

In this chapter

What this chapter covers

  • 01

    Loop bodies, passes and the loop variable

  • 02

    The three steps of the accumulator pattern

  • 03

    Counting and totalling characters

  • 04

    Building a new string from an empty one

  • 05

    Any and every questions with a Boolean flag

  • 06

    Searching with an early return

Worked example · free

Check a string for a hyphen and for letters only

Q [3 marks]. AskSia-authored practice. For s = 'ok-go', trace two loops: one sets found to True when a character is a hyphen, the other sets all_alpha to False when a character is not a letter. Give both final values. The marks shown are an AskSia study allocation, not an official University marking scheme.
Figure 8.2.Figure 8.2. For the string ok-go, the top row tracks whether a hyphen has been seen and the bottom row tracks whether every character so far is a letter. Each row changes once, at the hyphen, and keeps that value for the rest of the loop.ok-goFalseFalseTrueTrueTrueTrueTrueFalseFalseFalsefound, from Falseall_alpha, from Trueone flip, never flipped back
Figure 8.2. For the string ok-go, the top row tracks whether a hyphen has been seen and the bottom row tracks whether every character so far is a letter. Each row changes once, at the hyphen, and keeps that value for the rest of the loop.
  • 1found starts False and becomes True at the third character, the hyphen.
  • 1all_alpha starts True and becomes False at the same character.
  • 1Neither flag changes again, so found is True and all_alpha is False.
found reads False, False, True, True, True across the five passes, and all_alpha reads True, True, False, False, False. One hyphen is enough to answer both questions, and because neither loop has an else, the later letters g and o cannot undo the flip.
Sia tip — Before writing a Boolean loop, say which value means no evidence yet: False for any, True for every; that is the starting value.
Glossary

Key terms

Loop Body
The indented block of code that a loop repeats.
Accumulator
A variable that collects a loop's answer, initialised before the loop and returned after it.
Accumulator Pattern
Initialise a variable, update it on each relevant pass of a loop, and return it afterwards.
Early Return
A return inside a loop that ends the function as soon as the answer is known.
FAQ

For Loops and the Accumulator Pattern FAQ

What starting value should an accumulator have?

It depends on the answer you are building: 0 for a count or a total, the empty string for new text, False when asking whether any character qualifies and True when asking whether every character does. The course reference sheet lists these choices.

Why do many accumulator loops have no else?

Because you usually act only when a character is interesting. An else that resets a Boolean flag would let a later character undo an earlier finding, so one failure could be forgotten. Counting loops also need no else, since other characters change nothing.

When is returning from inside a loop correct?

When the answer is settled: an existence check can return True at the first match and a universal check can return False at the first failure. An else that returns the opposite value on the first ordinary character is wrong, because it stops after one character.

How is a for loop over a string different from a while loop?

A for loop runs once for each character, with the loop variable holding that character, and ends when the characters run out. A while loop repeats as long as its condition is True, so it can stop early or run without a fixed number of passes.

What is the difference between counting and searching loops?

A counting loop must look at every character, so it runs to the end and returns its accumulator afterwards. A search loop only needs the first match or the first failure, so it can return early from inside the loop, as the Week 4 slides show.

Study strategy

Exam move

Classify every Week 4 loop exercise as count, build, any or every before writing it, and write the starting value first. Trace each on paper with a table of the loop variable and accumulator per pass. Then step through two of them in the Wing 101 debugger to confirm your tables, paying attention to passes where nothing changes.

Add one loop where nothing should change on most passes and confirm your table shows those passes too.

Working through For Loops and the Accumulator Pattern in CSC108H1? Sia is AskSia’s AI Computer Science tutor — ask any CSC108H1 For Loops and the Accumulator Pattern 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 4-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