Weeks
Computational ThinkingWeek 2 · Max, Flowcharts and Pseudocode
Week 2 Notes

Computational
Thinking 2

Finding the maximum in one pass or two, flowcharts that track the best card, and moving from pictures to pseudocode. Lectures 2.6 to 2.10.

5 chapters28 worked examples~37 min read
MaximumWord frequencyFlowchartsPseudocodeFiltering

Chapters

  1. 01Max in a Single Iteration and in Two IterationsLecture 2.6
  2. 02Flowchart for Max MarksLecture 2.8
  3. 03Introduction to PseudocodeLecture 2.9
  4. 04Pseudocode for Iteration with FilteringLecture 2.10
  5. 05Week 2 Summary SheetAll lectures
01
Lecture 2.6

Max in a Single Iteration and in Two Iterations

Word frequencies, and how to find the maximum frequency in two non-nested passes or in a single pass.

This lecture works on the Words dataset: a paragraph (the opening of R. K. Narayan's Swami and Friends) whose words are kept on cards. We want two things: how many times each word occurs, and the maximum frequency, the count of the most frequent word. We can get the maximum with two iterations run one after the other, or fold both jobs into a single iteration.

1.1The word frequency table

As we walk through the paragraph we build a table with one row per distinct word. Each row has two cells: the word and its count (frequency).

word frequency table (one row per distinct word)It2was3Monday3morning1Swaminathan1…the6first time a word appears: new rowlater times: only the count changescase ignored: It and it share a rowlargest count: Max-frequency = 6
Figure 1. A few rows of the final table; the largest count is 6, for the word "the"
RuleWhat it means
One row per wordA word gets a row the first time it is seen. Later occurrences only change that row's count.
Case is ignoredIt at the start and it later share the same row, which is why It ends with count 2.
Words, not punctuationFull stops, commas and semicolons are not part of a word. Hyphenated words such as fire-eyed and class-teacher stay single words.

1.2What happens to one word

The same few steps run for every word (on the slides the current word is highlighted in yellow in the paragraph and the table changes beside it).

  1. Read the next word W of the paragraph, moving left to right.
  2. Look up W in the table.
  3. Not found: add a new row for W with count 0.
  4. Increment the count in W's row by 1. A new word therefore ends at 1, and a repeated word goes up by one.
CASE 1 · W is not in the tableCASE 2 · W is already in the table…………look up W: not found, add row…………W0increment count of W…………W1……Wk……look up W: found with count kno new row; count becomes k + 1……Wk+1……each word is visited exactly once; the table row is the variable being updated
Figure 2. The two cases when a word is processed
Same iteration pattern as the cards

Each word is visited exactly once: pick the next unvisited word, mark it as visited by moving on, and update a variable, which here is a row of the table.

1.3Maximum in two iterations

Iteration 1 · over the wordsGo through the whole paragraph and build the complete frequency table. At the end every word has its final count.
Iteration 2 · over the tableStart with Max-frequency = 0. Go through the rows; whenever a row's count is greater than Max-frequency, replace it with that count.
ITERATION 1 · over the wordsITERATION 2 · over the rowsStartFrequency table is emptyMore words inthe paragraph?Yes (True)Read the next word WAdd W with count 0 if new,then increment count of WNo (False)table is completeMax-frequency = 0More rowsin the table?NoEndYesPick the next row RR.count >Max-frequency?YesMax-frequency = R.countNo
Figure 3. Two non-nested iterations: build the table, then scan it

Read the flowchart column by column. The left loop is iteration 1. Its No (False) exit, taken once no words are left, is the only way into the right loop, so iteration 2 always starts on a finished table. The right loop is the familiar max pattern: a decision inside the loop, with an update only on Yes (True).

Result for the paragraph
  • Iteration 2 finds Max-frequency = 6, reached by the word the.
  • The next highest counts are 3: was, Monday, his, of and and.
  • The word his appears three times (his eyes, his class-teacher, his thin long cane), so its count is 3. The last slides show 2 for it; the maximum is unaffected.
Why "non-nested". The two iterations run one after the other. Iteration 2 is not inside iteration 1; it begins only when iteration 1 has ended. So the paragraph is scanned once and then the table is scanned once.

1.4Maximum in a single iteration

We can avoid the second pass. Keep a Max-frequency box beside the table, starting at 0, and check it every time a count changes.

  1. Initialise: the table is empty and Max-frequency = 0.
  2. For each word W, update its row exactly as before (add with 0 if new, then increment).
  3. Immediately compare the new count of W with Max-frequency.
  4. If the count is greater, set Max-frequency to that count; otherwise leave it alone.
StartFrequency table is emptyMax-frequency = 0More words inthe paragraph?No (False)EndYes (True)Read the next word WAdd W with count 0 if new,then increment count of Wcount of W >Max-frequency?Yes (True)Max-frequency =count of WNo (False)
Figure 4. Single iteration: count and compare in the same pass (the highlighted parts are new)

The highlighted parts are what changed from iteration 1 of the two-pass method: Max-frequency is initialised along with the table, and a decision is added at the end of the loop body. Its No (False) branch does nothing, so the loop simply continues.

When Max-frequency changes during the pass on the paragraph (the first words and the repeated was and the):

Word being processedIts count after the updateMax-frequency
(before the first word)-0
It (1st word)11
was (2nd occurrence)22
was (3rd occurrence)33
the (4th occurrence)44
the (5th occurrence)55
the (6th occurrence)66
Max-frequency after each word that sets a new record0start1It1st2was2nd occ.3was3rd occ.4the4th occ.5the5th occ.6the6th occ.a count goes up one step at a time, so the maximum is caught the moment it is reached
Figure 5. Max-frequency rises as the counts reach new records
Why one pass is enough

A count only ever goes up, one step at a time. The largest count in the final table must therefore have passed the current maximum at the moment it was incremented, and that is exactly when we compare. So the single pass ends with the same answer, 6, as the two-pass method.

AspectTwo iterationsSingle iteration
PassesParagraph once, then the table onceParagraph once only
What is comparedEach row's final count with Max-frequencyEach updated count with Max-frequency, after every word
When the max is knownOnly after iteration 2 endsAt every moment: the max of the words seen so far
StructureTwo loops in sequence (non-nested)One loop with a decision inside

1.5A small example you can check by hand (extra)

Take the nine words the cat saw the dog and the cat ran. Both methods give the table the 3, cat 2, saw 1, dog 1, and 1, ran 1 (6 rows) and Max-frequency = 3. Here is the single-iteration trace:

WordCount after updateMax-frequencyMax updated?
the11yes
cat11no
saw11no
the22yes
dog12no
and12no
the33yes
cat23no
ran13no

Max-frequency changed 3 times (to 1, 2 and 3), whenever a count set a new record. The words cat (count 2 while the max was already 2) and the new words with count 1 never changed it.

1.6Going deeper

  • Why start at 0. Every count is at least 1, so the very first word already beats Max-frequency = 0.
  • Strictly greater. A count equal to the current max does not change the value, so > is enough for the maximum value.
  • Which word (extra). To know the word, not just the count, also store it whenever Max-frequency changes. Chapter 2 does exactly this for cards.
  • Trade-off. The two-pass method is simpler to reason about; the single pass needs no second scan and always knows the max so far.

1.7Exam tips and common mistakes

Exam tips
  • For a table question, keep the rows in order of first appearance and tick each word as you pass it.
  • For "when does the max change?" questions, track the count of the word just processed, not the whole table.
Common mistakes
  • Counting It and it as different words.
  • Treating the second iteration as nested inside the first.
  • Forgetting to add a new word with count 0 before incrementing.

Practice questions (graded-assignment style)

Q1One word

Multiple Choice Question (MCQ): choose the one correct option.

A word W is already in the table with count 3. After processing one more occurrence of W, its count is:

1
1
2
3
3
4
4
0
Solution
Idea

Found: no new row; increment the count.

  • The word is found with count k = 3, so no new row is added and the count becomes k + 1 = 4.
  • Answer: option 3.
Q2Distinct words

Numerical Answer Type (NAT).

How many rows does the frequency table have for the cat saw the dog and the cat ran?

Solution
Idea

One row per distinct word.

  • The distinct words are the, cat, saw, dog, and, ran: 6 rows.
  • Answer: 6
Q3Max frequency

Numerical Answer Type (NAT).

What is the Max-frequency for to be or not to be?

Solution
Idea

Count each word, then take the largest.

  • to 2, be 2, or 1, not 1: the maximum is 2 (reached by both to and be).
  • Answer: 2
Q4Updates of the max

Numerical Answer Type (NAT).

In the single iteration over a b a c a b, how many times is Max-frequency changed?

Solution
Idea

Trace the count of each word as it is processed.

  • a gives 1 (max 1), b gives 1 (no), a gives 2 (max 2), c gives 1 (no), a gives 3 (max 3), b gives 2 (no): 3 changes.
  • Answer: 3
Q5Two iterations versus one

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
In the two-iteration method, iteration 2 is nested inside iteration 1.
2
In the two-iteration method, iteration 2 starts only after the table is complete.
3
The single-iteration method compares each updated count with Max-frequency.
4
The two methods can give different answers.
Solution
Idea

Recall the comparison table.

  • Statements 2 and 3 are true.
  • Statement 1 is false (the iterations are non-nested) and statement 4 is false (both give the same maximum).
  • Answer: options 2 and 3.
Revision overview
Frequency tableOne row per distinct word
Case ignored: It = it
Punctuation is not a word
One word, two casesNew: add row with 0, increment
Seen: increment its count
Max-frequencyResult: 6, the word "the"
Both methods agree
Max frequencyLecture 2.6
Two iterations1: build the full table
2: scan rows, keep the max
Non-nested
Single iterationMax-frequency = 0 at start
After each update: count > max?
Trace0, 1 (It), 2, 3 (was)
4, 5, 6 (the)
Revision: finding the most frequent word count in one pass or two
Next · Lecture 2.8Flowchart for Max Marks
02
Lecture 2.8

Flowchart for Max Marks

Filling in the filtering template to find the maximum, the card that has it, and all cards that tie.

We now draw the maximum as a flowchart on the Scores dataset. Instead of starting from scratch, we take the flowchart for iteration with filtering and fill in its blanks. Then we extend it to remember which card has the maximum, and finally all such cards.

2.1Starting point: iteration with filtering

This is the general shape from Week 1. The outer loop visits every card; inside it a decision Check for ? sends each card down one of two branches. Both branches return to the same place, the check More cards in Pile 1?

StartInitialiseMore cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Check for ?Yes (True)Do somethingfor YesNo (False)
Figure 6. Template: iteration with filtering
Blank in the templateWhat we must decide
InitialiseWhich variables we need and their starting values
Check for ?The condition tested on each card X
Do something for YesThe update when the condition is True
Do something for NoThe update when the condition is False (possibly nothing)

2.2Modify the template for the maximum

  1. Initialise max to 0. The box becomes max = 0. Marks cannot be negative, so any real mark is at least this value.
  2. The check: are the Maths marks of card X greater than max? If so update max; else do nothing.
  3. Write the check precisely as CardX.Maths > max?, where CardX.Maths means the Maths marks of card X.
  4. Yes (True): max = CardX.Maths.
  5. No (False): nothing to do, so the Do something for No box is removed and the No arrow goes straight back to the loop.
Startmax = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2CardX.Maths > max?Yes (True)max = CardX.MathsNo (False)
Figure 7. Flowchart for the max of Maths marks
At the end. When Pile 1 is empty the loop exits through No (False), and the variable max holds the maximum Maths marks over all the cards.

2.3Keep track of the card with the maximum

Knowing the maximum value is often not enough; we also want to know whose card it is. We add one more variable.

  1. Initialise maxCardId to -1. Card index numbers start at 0, so -1 stands for "no card yet".
  2. Update maxCardId at the same moment we update max: maxCardId = CardX.id, where CardX.id is the index number on card X.
  3. Both assignments sit in the same Yes (True) box, so max and maxCardId always describe the same card.
Startmax = 0maxCardId = -1More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2CardX.Maths > max?Yes (True)max = CardX.MathsmaxCardId = CardX.idNo (False)
Figure 8. Max of Maths marks, keeping track of the card

2.4The problem: ties for the maximum

What if more than one card has the same maximum marks? The test CardX.Maths > max? is a strict "greater than". A later card with marks equal to max answers No, so it is ignored. Only the first card with the maximum is retained.

2.5Solution: keep a list of cards

Keep a list of ids in maxCardId instead of a single id.

  1. On the No (False) branch of CardX.Maths > max?, ask a second question: is card X also at the max marks, CardX.Maths = max?
  2. Yes (True): append CardX.id to maxCardId. Appending b to a gives the list a, b.
  3. No (False): card X is below the max; nothing to do.
  4. The first Yes branch is unchanged: a strictly bigger mark sets max and restarts the list with just CardX.id.
Startmax = 0maxCardId = -1More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2CardX.Maths > max?Yes (True)max = CardX.MathsmaxCardId = CardX.idNo (False)CardX.Maths = max?Yes (True)NoAppend CardX.idto maxCardId
Figure 9. Max of Maths marks, keeping track of the list of cards
Card X compared with maxPath takenEffect
CardX.Maths > maxYes on the first decisionmax becomes the new marks; list restarts as just CardX.id
CardX.Maths = maxNo, then YesCardX.id is appended to the list
CardX.Maths < maxNo, then NoNothing changes
At the end. maxCardId contains the list of all card indices with the max Maths marks, and max contains the max Maths value. All three paths return to the same place in the iteration.

2.6Trace the three versions on a small dataset (extra)

Six cards with ids 0 to 5 and Maths marks 45, 78, 91, 78, 91, 60. We process them in order of id.

Card idMathsmaxmaxCardId (single id)maxCardId (list)
045450[0]
178781[1]
291912[2]
378912[2]
491912[2, 4]
560912[2, 4]

The single-id version ends with max = 91, maxCardId = 2: card 4 also has 91 but is ignored. The list version ends with max = 91, maxCardId = [2, 4]. Along the way the list restarts as [1] when 78 beats 45, restarts again as [2] when 91 arrives, ignores the later 78 (below the max), and appends 4 for the later 91 (equal to the max).

2.7Going deeper

  • The zero-marks gotcha (extra). With max = 0 and a strict >, a dataset where every mark is 0 never takes the Yes branch, so maxCardId stays -1 even though cards exist. The list version records [0, 1] because the = test catches them.
  • Why 0 is safe here. The source relies on marks being non-negative. If marks could be negative, initialise max to the first card's marks instead (extra).
  • Strict versus non-strict. Changing > to >= would keep the last maximum card instead of the first (extra).
  • Same shape every time. Max, max-with-card and max-with-list all keep the template; only the blanks change.

2.8Exam tips and common mistakes

Exam tips
  • Name the blanks first: Initialise, Check, Yes, No. Then fill them one by one.
  • When a question says "all cards with the max", the answer needs the second decision and a list.
  • Trace with a table: one row per card, columns for each variable.
Common mistakes
  • Updating maxCardId outside the Yes box so it no longer matches max.
  • Using >= and expecting the first maximum card.
  • Initialising maxCardId to 0, which looks like a real card.

Practice questions (graded-assignment style)

Q1The max

Numerical Answer Type (NAT).

For the Maths marks 45, 78, 91, 78, 91, 60 (ids 0 to 5), what is max at the end of the max flowchart?

Solution
Idea

The largest mark.

  • The updates are to 45, 78 and 91; the later 78, 91 and 60 never exceed 91 strictly.
  • Answer: 91
Q2Which card?

Numerical Answer Type (NAT).

With the single-id flowchart (strict >), what is maxCardId at the end for the same marks?

Solution
Idea

Card 4 ties with card 2 but is ignored.

  • max reaches 91 at card 2. Card 4 has 91, which is not strictly greater, so maxCardId stays 2.
  • Answer: 2
Q3The list version

Multiple Choice Question (MCQ): choose the one correct option.

For the same marks, the list flowchart finishes with maxCardId equal to:

1
[2]
2
[2, 4]
3
[1, 3]
4
[4]
Solution
Idea

Both 91s end up in the list.

  • Card 2 sets max = 91 and restarts the list as [2]. Card 4 has 91 = max, so 4 is appended: [2, 4].
  • Answer: option 2.
Q4All zeros

Multiple Choice Question (MCQ): choose the one correct option.

Every card has Maths marks 0. In the single-id flowchart (max = 0, maxCardId = -1, strict >), maxCardId at the end is:

1
0
2
-1
3
The id of the last card
4
It is a list
Solution
Idea

Is 0 > 0?

  • No mark is strictly greater than max = 0, so the Yes branch never runs and maxCardId keeps its starting value -1.
  • Answer: option 2.
Q5Paths in the list flowchart

Multiple Select Question (MSQ): select all that apply.

Current max = 80. Which statements are true?

1
A card with 85 restarts the list as just that card's id.
2
A card with 80 is appended to the list.
3
A card with 70 changes the list.
4
A card with 85 is appended to the old list.
Solution
Idea

Recall the path table.

  • 85 > 80 takes the first Yes: new max, list restarts. 80 = 80 takes No then Yes: appended.
  • 70 changes nothing, and 85 never appends to the old list.
  • Answer: options 1 and 2.
Q6Why -1

Multiple Choice Question (MCQ): choose the one correct option.

Why is maxCardId initialised to -1?

1
Because card ids are negative
2
Because ids start at 0, so -1 means "no card yet"
3
Because max is -1
4
It makes the loop stop
Solution
Idea

What are the valid ids?

  • Card index numbers start at 0, so a value outside that range cannot be mistaken for a real card.
  • Answer: option 2.
Revision overview
TemplateInitialise, Check for ?
Yes / No actions
Both paths return to the loop
Max valuemax = 0
CardX.Maths > max?
Yes: max = CardX.Maths
Which cardmaxCardId = -1 (no card yet)
Yes: also maxCardId = CardX.id
Max flowchartLecture 2.8
The problemTies: equal marks answer No
Only the first card is kept
List of cardsNo branch: CardX.Maths = max?
Yes: append CardX.id
Bigger mark restarts the list
At the endmax: the max Maths value
maxCardId: all ids with max
Revision: turning the template into max, max-with-card and max-with-list
Next · Lecture 2.9Introduction to Pseudocode
03
Lecture 2.9

Introduction to Pseudocode

Why flowcharts need a text companion, and how pseudocode writes assignment and repetition directly.

Flowcharts draw a procedure as a picture. This lecture asks how to write the same procedure as text, keeping what flowcharts do well and fixing what they do badly. The answer is pseudocode.

3.1Flowcharts: a recap

A flowchart is a pictorial representation of a computational process. Our running example is counting the number of cards. It uses three node types joined by arrows that indicate the operation flow.

ElementNameWhat it does
Start / EndTerminalIndicates the start or end of the program.
Count = 0Process or activityA set of operations that change the value of data (variables).
→Flowline or arrowShows the order of execution of the program steps.
More cards?DecisionDetermines which path the program will take.
StartCount = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Increment Count
Figure 10. Counting the number of cards

3.2Pros and cons of flowcharts

Advantages
  • Visual representation of computation.
  • Easy to understand.
Disadvantages
  • Size: complex processes generate large flowcharts.
  • Collaboration: sharing pictures in an editable format is hard.
  • Versions: it is hard to compare changes between flowcharts.

3.3From pictures to text

The first idea is simply to describe the process in words, one numbered step per box or arrow of the flowchart.

StepTextComes from
0StartStart terminal
1Initialise Count to 0process box
2Check cards in Pile 1decision (check)
3If no more cards, go to Step 8decision (No branch)
4Pick a card X from Pile 1process box
5Move X to Pile 2process box
6Increment Countprocess box
7Go back to Step 2the arrow looping back
8EndEnd terminal

The numbered badges show the match: boxes become plain steps (0, 1, 4, 5, 6, 8). The decision becomes two steps: Step 2 checks, Step 3 jumps to the End on No. The arrow looping back to the decision becomes Step 7, Go back to Step 2.

3.4Towards a programming language

A programming language is a succinct notation for computational processes. Writing steps in plain words works, but two common patterns read awkwardly and need a better textual representation:

Conditional executionStep 3 "If no more cards, go to Step 8" and Step 4 "Pick a card X from Pile 1": whether Step 4 runs depends on a condition, but we express this by jumping to a step number.
Repeated executionStep 2 "Check cards in Pile 1" ... Step 7 "Go back to Step 2": the steps in between repeat, but we only see this by following the jump back.

3.5Pseudocode

Pseudocode tunes the notation so these standard features are written directly instead of through jumps.

counting-cards.pseudo
Start
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Increment Count
}
End
  1. Assign a value to a variable: Count = 0.
  2. Repeat steps while a condition holds: while (...).
  3. Mark the start and end of the repeated block: { }.
flowchartpseudocodeStartCount = 0More cardsin Pile 1?YesPick a card X from Pile 1Move X to Pile 2Increment CountNoEndCount = 01while (Pile 1 has more cards) {2 Pick a card X from Pile 1 Move X to Pile 2 Increment Count}3End
Figure 11. Each pseudocode line next to the flowchart node it replaces

Every process box becomes one line at the same height. The decision and its loop-back arrow together become a single while line plus a pair of braces: the condition Pile 1 has more cards is tested before each repetition, the lines inside the braces are the repeated block, and when the condition fails execution continues after }, at End. No step numbers or "go to" jumps are needed.

3.6Running the numbered steps (extra)

Follow the numbered steps for a Pile 1 that has 2 cards. The steps are visited in this order, and Count ends at 2:

Visited steps
0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 2 → 3 → 4 → 5 → 6 → 7 → 2 → 3 → 8

That is 17 steps: 2 to start, then 6 steps (2, 3, 4, 5, 6, 7) for each of the 2 cards, then 3 (2, 3, 8) to finish. The jump back at Step 7 is what the single while line replaces.

3.7Summary

  • Flowcharts are easy to read, visual descriptions of procedures, but they are cumbersome, hard to share and edit.
  • Writing down steps in text is an alternative.
  • Tune the notation to capture standard features: assigning values to variables, conditional execution, repeated execution.

3.8Exam tips and common mistakes

Exam tips
  • Pair every flowchart element with its text form: process box → assignment, decision plus loop-back → while.
  • Remember the three disadvantages by the words Size, Collaboration, Versions.
Common mistakes
  • Thinking a decision becomes only one numbered step (it becomes two: the check and the jump).
  • Forgetting that the loop-back arrow becomes "Go back to Step 2".
  • Forgetting the braces that mark the repeated block.

Practice questions (graded-assignment style)

Q1Steps executed

Numerical Answer Type (NAT).

Following the numbered steps for a Pile 1 with 3 cards, how many steps are visited in all (counting each visit)?

Solution
Idea

2 to start, 6 per card, 3 to finish.

  • 2 + 6 × 3 + 3 = 23.
  • Answer: 23
Q2Which step?

Multiple Choice Question (MCQ): choose the one correct option.

In the numbered steps, "Go back to Step 2" comes from which part of the flowchart?

1
The Start terminal
2
The arrow looping back to the decision
3
The Count = 0 box
4
The End terminal
Solution
Idea

Which element repeats the steps?

  • The loop-back arrow becomes Step 7, Go back to Step 2.
  • Answer: option 2.
Q3Which construct?

Multiple Choice Question (MCQ): choose the one correct option.

Which pseudocode construct replaces "If no more cards, go to Step 8" together with "Go back to Step 2"?

1
Assignment
2
The while (...) { } block
3
A comment
4
The End line
Solution
Idea

One construct captures the check and the repetition.

  • The decision plus its loop-back arrow become one while line and a pair of braces.
  • Answer: option 2.
Q4Flowchart drawbacks

Multiple Select Question (MSQ): select all that apply.

Which are disadvantages of flowcharts listed in the lecture?

1
Complex processes give large flowcharts
2
They cannot show decisions
3
Sharing and editing is hard
4
Comparing versions is hard
Solution
Idea

Size, Collaboration, Versions.

  • Options 1, 3 and 4 are Size, Collaboration and Versions. Flowcharts can show decisions (option 2 is false).
  • Answer: options 1, 3 and 4.
Q5Lines in the listing

Numerical Answer Type (NAT).

The counting-cards pseudocode listing has how many lines (Start and End included)?

Solution
Idea

Count Start, Count = 0, while, three body lines, }, End.

  • The lines are Start, Count = 0, while, Pick, Move, Increment, } and End: 8 lines.
  • Answer: 8
Revision overview
FlowchartsPictures of a computation
Terminal, Process, Decision
Arrows: operation flow
Pros and consVisual, easy to understand
Size, Collaboration, Versions
Steps in wordsStep 0 Start ... Step 8 End
"If ..., go to Step 8"
"Go back to Step 2"
PseudocodeLecture 2.9
Better notation forConditional execution
Repeated execution
Pseudocode features1 Count = 0 (assignment)
2 while (condition)
3 { } marks the block
ResultNo step numbers
No "go to" jumps
Revision: moving from pictures to text
Next · Lecture 2.10Pseudocode for Iteration with Filtering
04
Lecture 2.10

Pseudocode for Iteration with Filtering

Every flowchart of Weeks 1 and 2 written as pseudocode, with assignment, if/else and ==.

We now write every flowchart from Weeks 1 and 2 as pseudocode. Along the way we meet the assignment statement, conditional execution with if and else, and the difference between == and =. Each pseudocode listing is shown next to its flowchart.

4.1Counting cards

count.pseudo
Start
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Increment Count
}
End
Convention from now on

Every procedure has a Start and an End, so we dispense with Start and End in the pseudocode henceforth. The flowcharts still show them.

4.2Sum of Maths marks

sum.pseudo
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Sum = Sum + X.Maths
}
StartSum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2Sum = Sum + X.Maths
Figure 12. Sum of Maths marks

Only two lines differ from counting: the variable is Sum, and Increment Count becomes Sum = Sum + X.Maths. Here X.Maths means the Maths marks in card X.

Sum = Sum + X.MathsLEFT SIDEupdated value (written)RIGHT SIDEcurrent value (evaluated first)2store1 work out the right side= is an instruction, not a claim of equalitySum is 10, X.Maths is 7 → Sum becomes 17
Figure 13. How to read the assignment Sum = Sum + X.Maths
Right sideSum on the right is the current value. The whole right side is worked out first.
Left sideSum on the left is the updated value: the result is stored back into it.
The = sign is not mathematical equality! As an equation, Sum = Sum + X.Maths would be false (unless X.Maths is 0); as an assignment it is an instruction. Increment Count can now be written as the assignment Count = Count + 1.

4.3Sum of boys' Maths marks

boys-sum.pseudo
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == M) {
        Sum = Sum + X.Maths
    }
}
StartSum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Gender == M?Yes (True)Sum = Sum + X.MathsNo (False)
Figure 14. Sum of boys' Maths marks

The filter decision X.Gender == M? becomes if (X.Gender == M) { ... }. The block inside the braces runs only when the condition is True. The No branch has nothing to do, so there is no extra code for it. This is conditional execution, once: the if block runs at most one time each time it is reached. Compare while, which keeps repeating its block as long as the condition holds.

4.4Equality (==) versus assignment (=)

=assignmentstore the right value in the left variableSum = Sum + X.Maths==equality testcompare; answer is True or Falseif (X.Gender == M)
Figure 15. = stores a value; == compares two values
SymbolMeaningExample
=Assignment: store the value of the right side in the variable on the left.Sum = Sum + X.Maths
==Equality test: compare two values; the answer is a Boolean, True or False. Nothing is changed.if (X.Gender == M)

4.5Sum of boys' and girls' Maths marks

boys-girls-sum.pseudo
BoySum = 0
GirlSum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == M) {
        BoySum = BoySum + X.Maths
    }
    else {
        GirlSum = GirlSum + X.Maths
    }
}
StartBoySum = 0GirlSum = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Gender == M?Yes (True)BoySum = BoySum+ X.MathsNo (False)GirlSum = GirlSum+ X.Maths
Figure 16. Sum of boys' and girls' Maths marks

Now both branches of the decision do work, so we use if (condition) { ... } else { ... }. The if block is the Yes (True) branch and adds to BoySum; the else block is the No (False) branch and adds to GirlSum. Exactly one of the two blocks runs for each card, and then control returns to the while check.

4.6Finding the maximum Maths marks

max.pseudo
MaxM = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > MaxM) {
        MaxM = X.Maths
    }
}
StartMaxM = 0More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Maths > MaxM?Yes (True)MaxM = X.MathsNo (False)
Figure 17. Maximum Maths marks

This is the flowchart of Lecture 2.8 in text form, with the variable named MaxM. It has the same shape as the boys' sum: an if with no else, because nothing happens when the marks are not bigger.

4.7The card with the maximum Maths marks

max-card.pseudo
MaxM = 0
MaxCard = -1
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths > MaxM) {
        MaxM = X.Maths
        MaxCard = X.Id
    }
}
StartMaxM = 0MaxCard = -1More cardsin Pile 1?No (False)EndYes (True)Pick a card X from Pile 1Move X to Pile 2X.Maths > MaxM?Yes (True)MaxM = X.MathsMaxCard = X.IdNo (False)
Figure 18. Card with maximum Maths marks

MaxCard starts at -1 (no card yet). Both assignments sit inside the same if block, so they always happen together: whenever a new maximum is found, its card id X.Id is recorded as well.

4.8Run them on a small dataset (extra)

Six cards, ids 0 to 5, genders M F M F M F and Maths marks 45, 78, 91, 78, 91, 60.

Card idGenderMathsBoySum afterGirlSum after
0M45450
1F784578
2M9113678
3F78136156
4M91227156
5F60227216

Final values: BoySum = 227, GirlSum = 216, and the plain Sum = 443 (their total). The max program gives MaxM = 91 and MaxCard = 2 (card 4 is ignored by the strict >).

4.9Summary

IdeaPseudocode
AssignmentCount = 0, Sum = Sum + X.Maths
Conditional, onceif (condition) { ... } / if ... else ...
Conditional, repeatedlywhile (condition) { ... }
Equality versus assignmentif (X.Gender == M) tests; Sum = Sum + X.Maths stores

4.10Going deeper

  • while tests first. The condition is checked before each repetition, so with an empty pile the block never runs and Sum stays 0 (extra).
  • Indentation helps. The braces mark the blocks; indenting the lines inside them makes the nesting easy to see (extra).
  • Words as conditions. Pile 1 has more cards is a condition written in plain words; pseudocode is not tied to a real language's syntax (extra).
  • Pattern reuse. Every program here is the same while loop with different initialisations and different bodies.

4.11More templates: the minimum, the average, counting with a condition, and compound conditions

Every program in this part is the same while loop with different initial values and a different body. Four more variations are needed so often that they are worth learning as templates. All the traces below use the same six cards as 4.8 (ids 0 to 5, genders M F M F M F, Maths marks 45, 78, 91, 78, 91, 60).

A. The minimum

The minimum is the maximum turned upside down: test with < instead of >. The initial value must be at least as large as any possible mark (for marks out of 100, use 100), because a starting value of 0 could never be beaten by a smaller mark.

min.pseudo
MinM = 100
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths < MinM) {
        MinM = X.Maths
    }
}

On the six cards, the first card (45) is already the smallest, so MinM = 45 at the end. A better trace uses Maths marks 70,55,80,55,4070, 55, 80, 55, 40:

CardMathsTest X.Maths < MinMMinM after
start100
07070 < 100: True70
15555 < 70: True55
28080 < 55: False55
35555 < 55: False (strict, so the first 55 is kept)55
44040 < 55: True40

To remember which card has the minimum, add MinCard = X.Id inside the same if, exactly as for the maximum.

B. The average

The average needs two accumulators, a sum and a count, and one division after the loop:

average.pseudo
Sum = 0
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    Sum = Sum + X.Maths
    Count = Count + 1
}
Avg = Sum / Count

On the six cards: Sum=443Sum = 443, Count=6Count = 6, Avg=443/6≈73.83Avg = 443/6 \approx 73.83. For the average over a filtered group, put both updates inside the same if. For the girls: if (X.Gender == F) { Sum = Sum + X.Maths; Count = Count + 1 } gives Sum=216Sum = 216, Count=3Count = 3, Avg=72Avg = 72. For the boys Sum=227Sum = 227, Count=3Count = 3, Avg≈75.67Avg \approx 75.67.

Guard the division. If no card passes the filter, Count is 0 and Sum / Count is a division by zero. Write if (Count > 0) { Avg = Sum / Count }. Also never divide inside the loop and expect the final value to be a sum: the division belongs after the loop.

C. Counting with a condition

Counting is the sum template with the update Count = Count + 1 placed inside an if. "How many cards have Maths of at least 80?":

count-high.pseudo
Count = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Maths >= 80) {
        Count = Count + 1
    }
}

On the six cards, the marks 9191 (card 2) and 9191 (card 4) qualify, so Count = 2.

D. Compound conditions: and, or, not

A condition can combine tests. A and B is True only when both are True; A or B is True when at least one is True; not A flips it. A compound condition does the same job as nesting:

CompoundSame as
if (A and B) { S }if (A) { if (B) { S } }
if (A or B) { S }S runs once if either is True (not twice if both are)
not (A and B)(not A) or (not B) (De Morgan)
not (A or B)(not A) and (not B)
compound.pseudo
Sum = 0
while (Pile 1 has more cards) {
    Pick a card X from Pile 1
    Move X to Pile 2
    if (X.Gender == M and X.Maths > 50) {
        Sum = Sum + X.Maths
    }
}

On the six cards, the boys are cards 0, 2, 4 with marks 45, 91, 91. Only 91 and 91 pass X.Maths > 50, so Sum=182Sum = 182 and a counter beside it would end at 2. With or instead: X.Gender == F or X.Maths > 85 picks the three girls (78, 78, 60) and the two boys with 91, so Sum=216+182=398Sum = 216 + 182 = 398. A card that satisfies both parts is still added only once.

E. Where the initialisation goes

  • Initialise before the while. Writing Count = 0 inside the loop resets it every round, so it ends at 1 at most (for a non-empty pile).
  • Pick the start value so the first update always works: 0 for sums and counts and for a maximum of non-negative marks, a large number for a minimum.
  • Updates that need the old value (like Sum = Sum + X.Maths) rely on the initialisation being there. A missing initialisation is the most common reason a trace comes out wrong.

4.12Exam tips and common mistakes

Exam tips
  • To read pseudocode, first spot the while, then list the initialisations above it, then read the body line by line.
  • Decide if alone or if ... else by asking whether the No branch has work.
Common mistakes
  • Writing = inside an if condition instead of ==.
  • Reading Sum = Sum + X.Maths as a false equation.
  • Putting the initialisation (Sum = 0) inside the loop.
  • Forgetting the -1 start for MaxCard.

Practice questions (graded-assignment style)

Q1Boys' sum

Numerical Answer Type (NAT).

Cards: ids 0 to 5, genders M F M F M F, Maths 45, 78, 91, 78, 91, 60. What is Sum at the end of the boys' sum program?

Solution
Idea

Add the marks of the cards with gender M.

  • The boys are cards 0, 2, 4: 45 + 91 + 91 = 227.
  • Answer: 227
Q2Girls' sum

Numerical Answer Type (NAT).

For the same cards, what is GirlSum at the end of the boys' and girls' program?

Solution
Idea

The else block adds the girls' marks.

  • The girls are cards 1, 3, 5: 78 + 78 + 60 = 216.
  • Answer: 216
Q3MaxCard

Numerical Answer Type (NAT).

For the same cards, what is MaxCard at the end of the max-card program?

Solution
Idea

The strict > keeps the first maximum.

  • MaxM becomes 45, 78, 91 at cards 0, 1, 2; the later 91 at card 4 is not strictly greater, so MaxCard = 2.
  • Answer: 2
Q4= or ==

Multiple Choice Question (MCQ): choose the one correct option.

Which line stores a value?

1
if (X.Gender == M)
2
Sum = Sum + X.Maths
3
while (Pile 1 has more cards)
4
if (X.Maths > MaxM)
Solution
Idea

Which statement changes a variable?

  • = assigns: it stores the right side in Sum. The other lines only test conditions.
  • Answer: option 2.
Q5Which construct?

Multiple Select Question (MSQ): select all that apply.

Choose the correct pairings.

1
Filter decision, No does nothing: if (...) { ... }
2
Filter decision, both branches work: if (...) { ... } else { ... }
3
Loop decision plus arrow back: while (...) { ... }
4
Start and End terminals: always written in every pseudocode
Solution
Idea

Recall the summary table.

  • The first three pairings are correct. Start and End are dropped from the pseudocode after the first example (option 4 is false).
  • Answer: options 1, 2 and 3.
Q6How many blocks run?

Multiple Choice Question (MCQ): choose the one correct option.

In the boys' and girls' program, for one card how many of the if/else blocks run?

1
Both
2
None
3
Exactly one
4
It depends on the loop
Solution
Idea

The condition is either True or False.

  • Exactly one of the two blocks runs, then control returns to the while check.
  • Answer: option 3.
Q7Sum of all

Numerical Answer Type (NAT).

For the same six cards, what does the plain sum program (Sum = Sum + X.Maths for every card) give?

Solution
Idea

Add all six marks.

  • 45 + 78 + 91 + 78 + 91 + 60 = 443, which equals 227 + 216.
  • Answer: 443
Q8The minimum with a strict test

Numerical Answer Type (NAT).

Six cards have Maths marks 70,55,80,55,40,6570, 55, 80, 55, 40, 65 in this order. The program starts with MinM = 100 and runs if (X.Maths < MinM) { MinM = X.Maths } for each card. What is MinM at the end?

Solution
Idea

MinM takes each smaller value in turn: 100→70→55→55→55→40→40100 \to 70 \to 55 \to 55 \to 55 \to 40 \to 40.

  • The test fails for 80 (not less than 55), for the second 55 (strict), and for 65 (not less than 40).
  • Answer: 40
Q9A filtered average

Numerical Answer Type (NAT).

For the six cards of 4.8 (genders M F M F M F, Maths 45, 78, 91, 78, 91, 60), the program updates Sum and Count only when X.Gender == F, and then computes Avg = Sum / Count. What is Avg?

Solution
Idea

Both accumulators sit inside the if, so they see only the girls.

  • Girls are cards 1, 3, 5 with marks 78,78,6078, 78, 60. Sum=216Sum = 216, Count=3Count = 3.
  • Avg=216/3=72Avg = 216/3 = 72.
  • Answer: 72
Q10Counting with and

Numerical Answer Type (NAT).

On the same six cards, a counter is increased whenever X.Gender == M and X.Maths > 50. What is the final count?

Solution
Idea

A card counts only if both parts are True.

  • Boys: cards 0, 2, 4 with marks 45, 91, 91. Card 0 fails (45>5045 > 50 is False). Cards 2 and 4 pass.
  • Answer: 2
Q11Compound condition with or

Numerical Answer Type (NAT).

On the same six cards, Sum = Sum + X.Maths runs whenever X.Gender == F or X.Maths > 85. What is the final Sum?

Solution
Idea

A card is added once if at least one part is True.

  • Cards 1, 3, 5 (girls): 78+78+60=21678 + 78 + 60 = 216.
  • Boys with Maths above 85: cards 2 and 4: 91+91=18291 + 91 = 182. Card 0 (45) passes neither part.
  • 216+182=398216 + 182 = 398.
  • Answer: 398
Q12Where do the initialisations go?

Multiple Select Question (MSQ): select all that apply.

Choose the correct statements.

1
If MinM = 0 is the starting value and the test is X.Maths < MinM, then MinM stays 0 for marks that are all positive.
2
If Count = 0 is written inside the while block, then for a non-empty pile Count ends at 1 (when it is increased after being reset).
3
Avg = Sum / Count placed after the loop fails when no card passed the filter, because Count is 0.
4
not (A and B) is the same as (not A) and (not B).
Solution
Idea

Check each against the templates and De Morgan's laws.

  • 1 ✓ No positive mark is below 0, so the update never fires.
  • 2 ✓ The reset happens at the start of every round, so only the last increment is left.
  • 3 ✓ Division by zero; guard with if (Count > 0).
  • 4 ✗ De Morgan: not (A and B) is (not A) or (not B).
  • Answer: options 1, 2 and 3.
Revision overview
AssignmentCount = 0
Sum = Sum + X.Maths
Right: current, left: updated
Loopwhile (Pile 1 has more cards)
Pick X, move X to Pile 2
Start / End omitted
Filterif (X.Gender == M) { ... }
runs once when reached
No branch: nothing
Iteration and filtering in pseudocodeLecture 2.10
if ... elseYes: BoySum += X.Maths
No: GirlSum += X.Maths
Exactly one block runs
MaximumMaxM = 0
if (X.Maths > MaxM) MaxM = X.Maths
MaxCard = -1, then X.Id
== versus === compares: True or False
= stores a value
Revision: writing every flowchart as pseudocode
Next · All lecturesWeek 2 Summary Sheet
05
All lectures

Week 2 Summary Sheet

One page to revise all of Week 2: the two ways to find a maximum, the flowchart patterns and the flowchart-to-pseudocode table.

Maximum: two ways

MethodHow it worksWords dataset result
Two iterationsPass 1 builds the frequency table; pass 2 scans the table keeping the largest count. The passes are non-nested (one after the other).Max-frequency = 6 ("the")
Single iterationAfter each count update, compare it with Max-frequency and replace it if larger.Same answer, one pass

Flowchart patterns on the Scores dataset

GoalInitialiseCheck inside the loopYes (True)No (False)
Max marksmax = 0CardX.Maths > max?max = CardX.Mathsnothing
Max and its cardmax = 0, maxCardId = -1CardX.Maths > max?also maxCardId = CardX.idnothing
All cards with maxmax = 0, maxCardId = -1> max? then = max?>: reset list to CardX.id=: append CardX.id; else nothing

Flowchart to pseudocode

Flowchart elementPseudocode
Process box that sets a variableAssignment: Count = 0, Sum = Sum + X.Maths, Count = Count + 1
Loop decision + arrow backwhile (Pile 1 has more cards) { ... }
Filter decision, No does nothingif (condition) { ... }
Filter decision, both branches workif (condition) { ... } else { ... }
Start / End terminalsDropped from pseudocode after Lecture 2.10's first example

Why pseudocode, and notation to remember

Why pseudocode
  • Flowcharts: visual and easy to understand.
  • But: large, hard to share and edit, hard to compare versions.
  • Pseudocode writes assignment, conditional and repeated execution directly, with no "go to Step n".
Notation to remember
  • X.Maths, X.Gender, X.Id: fields of card X.
  • = assigns; == compares and gives a Boolean.
  • { } marks where a block starts and ends.
  • -1 as an id means "no card yet".

Common mistakes

Nested iterations
  • In the two-pass method iteration 2 is not inside iteration 1.
Ties lost
  • A strict > keeps only the first maximum card; use the list version for all.
= versus ==
  • == tests; = stores.
max = 0 assumed
  • It only works for non-negative marks; all-zero marks leave maxCardId at -1.
Reset forgotten
  • A new maximum must restart the list, not extend it.
Jumps in pseudocode
  • Use while and if, not "go to Step n".
Back to top