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.
Chapters
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).
| Rule | What it means |
|---|---|
| One row per word | A word gets a row the first time it is seen. Later occurrences only change that row's count. |
| Case is ignored | It at the start and it later share the same row, which is why It ends with count 2. |
| Words, not punctuation | Full 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).
- Read the next word W of the paragraph, moving left to right.
- Look up W in the table.
- Not found: add a new row for W with count
0. - Increment the count in W's row by 1. A new word therefore ends at
1, and a repeated word goes up by one.
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
Max-frequency = 0. Go through the rows; whenever a row's count is greater than Max-frequency, replace it with that count.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).
- 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.
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.
- Initialise: the table is empty and
Max-frequency = 0. - For each word W, update its row exactly as before (add with 0 if new, then increment).
- Immediately compare the new count of W with
Max-frequency. - If the count is greater, set
Max-frequencyto that count; otherwise leave it alone.
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 processed | Its count after the update | Max-frequency |
|---|---|---|
| (before the first word) | - | 0 |
| It (1st word) | 1 | 1 |
| was (2nd occurrence) | 2 | 2 |
| was (3rd occurrence) | 3 | 3 |
| the (4th occurrence) | 4 | 4 |
| the (5th occurrence) | 5 | 5 |
| the (6th occurrence) | 6 | 6 |
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.
| Aspect | Two iterations | Single iteration |
|---|---|---|
| Passes | Paragraph once, then the table once | Paragraph once only |
| What is compared | Each row's final count with Max-frequency | Each updated count with Max-frequency, after every word |
| When the max is known | Only after iteration 2 ends | At every moment: the max of the words seen so far |
| Structure | Two 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:
| Word | Count after update | Max-frequency | Max updated? |
|---|---|---|---|
| the | 1 | 1 | yes |
| cat | 1 | 1 | no |
| saw | 1 | 1 | no |
| the | 2 | 2 | yes |
| dog | 1 | 2 | no |
| and | 1 | 2 | no |
| the | 3 | 3 | yes |
| cat | 2 | 3 | no |
| ran | 1 | 3 | no |
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-frequencychanges. 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
- 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.
- 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)
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:
Found: no new row; increment the count.
- The word is found with count
k = 3, so no new row is added and the count becomesk + 1 = 4. - Answer: option 3.
Numerical Answer Type (NAT).
How many rows does the frequency table have for the cat saw the dog and the cat ran?
One row per distinct word.
- The distinct words are the, cat, saw, dog, and, ran: 6 rows.
- Answer: 6
Numerical Answer Type (NAT).
What is the Max-frequency for to be or not to be?
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
Numerical Answer Type (NAT).
In the single iteration over a b a c a b, how many times is Max-frequency changed?
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
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
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.
Case ignored: It = it
Punctuation is not a word
Seen: increment its count
Both methods agree
2: scan rows, keep the max
Non-nested
After each update: count > max?
4, 5, 6 (the)
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?
| Blank in the template | What we must decide |
|---|---|
Initialise | Which variables we need and their starting values |
Check for ? | The condition tested on each card X |
Do something for Yes | The update when the condition is True |
Do something for No | The update when the condition is False (possibly nothing) |
2.2Modify the template for the maximum
- Initialise
maxto 0. The box becomesmax = 0. Marks cannot be negative, so any real mark is at least this value. - The check: are the Maths marks of card X greater than
max? If so updatemax; else do nothing. - Write the check precisely as
CardX.Maths > max?, whereCardX.Mathsmeans the Maths marks of card X. - Yes (True):
max = CardX.Maths. - No (False): nothing to do, so the Do something for No box is removed and the No arrow goes straight back to the loop.
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.
- Initialise
maxCardIdto-1. Card index numbers start at 0, so -1 stands for "no card yet". - Update
maxCardIdat the same moment we updatemax:maxCardId = CardX.id, whereCardX.idis the index number on card X. - Both assignments sit in the same Yes (True) box, so
maxandmaxCardIdalways describe the same 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.
- On the No (False) branch of
CardX.Maths > max?, ask a second question: is card X also at the max marks,CardX.Maths = max? - Yes (True): append
CardX.idtomaxCardId. Appending b to a gives the lista, b. - No (False): card X is below the max; nothing to do.
- The first Yes branch is unchanged: a strictly bigger mark sets
maxand restarts the list with justCardX.id.
| Card X compared with max | Path taken | Effect |
|---|---|---|
CardX.Maths > max | Yes on the first decision | max becomes the new marks; list restarts as just CardX.id |
CardX.Maths = max | No, then Yes | CardX.id is appended to the list |
CardX.Maths < max | No, then No | Nothing changes |
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 id | Maths | max | maxCardId (single id) | maxCardId (list) |
|---|---|---|---|---|
| 0 | 45 | 45 | 0 | [0] |
| 1 | 78 | 78 | 1 | [1] |
| 2 | 91 | 91 | 2 | [2] |
| 3 | 78 | 91 | 2 | [2] |
| 4 | 91 | 91 | 2 | [2, 4] |
| 5 | 60 | 91 | 2 | [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 = 0and a strict>, a dataset where every mark is 0 never takes the Yes branch, somaxCardIdstays-1even 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
maxto 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
- 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.
- Updating
maxCardIdoutside the Yes box so it no longer matchesmax. - Using
>=and expecting the first maximum card. - Initialising
maxCardIdto 0, which looks like a real card.
Practice questions (graded-assignment style)
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?
The largest mark.
- The updates are to 45, 78 and 91; the later 78, 91 and 60 never exceed 91 strictly.
- Answer: 91
Numerical Answer Type (NAT).
With the single-id flowchart (strict >), what is maxCardId at the end for the same marks?
Card 4 ties with card 2 but is ignored.
maxreaches 91 at card 2. Card 4 has 91, which is not strictly greater, somaxCardIdstays 2.- Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
For the same marks, the list flowchart finishes with maxCardId equal to:
[2][2, 4][1, 3][4]Both 91s end up in the list.
- Card 2 sets
max = 91and restarts the list as[2]. Card 4 has 91 = max, so 4 is appended:[2, 4]. - Answer: option 2.
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:
0-1Is 0 > 0?
- No mark is strictly greater than
max = 0, so the Yes branch never runs andmaxCardIdkeeps its starting value-1. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Current max = 80. Which statements are true?
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.
Multiple Choice Question (MCQ): choose the one correct option.
Why is maxCardId initialised to -1?
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.
Yes / No actions
Both paths return to the loop
CardX.Maths > max?
Yes: max = CardX.Maths
Yes: also maxCardId = CardX.id
Only the first card is kept
Yes: append CardX.id
Bigger mark restarts the list
maxCardId: all ids with max
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.
| Element | Name | What it does |
|---|---|---|
Start / End | Terminal | Indicates the start or end of the program. |
Count = 0 | Process or activity | A set of operations that change the value of data (variables). |
→ | Flowline or arrow | Shows the order of execution of the program steps. |
More cards? | Decision | Determines which path the program will take. |
3.2Pros and cons of flowcharts
- Visual representation of computation.
- Easy to understand.
- 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.
| Step | Text | Comes from |
|---|---|---|
| 0 | Start | Start terminal |
| 1 | Initialise Count to 0 | process box |
| 2 | Check cards in Pile 1 | decision (check) |
| 3 | If no more cards, go to Step 8 | decision (No branch) |
| 4 | Pick a card X from Pile 1 | process box |
| 5 | Move X to Pile 2 | process box |
| 6 | Increment Count | process box |
| 7 | Go back to Step 2 | the arrow looping back |
| 8 | End | End 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:
3.5Pseudocode
Pseudocode tunes the notation so these standard features are written directly instead of through jumps.
Start
Count = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
Increment Count
}
End- Assign a value to a variable:
Count = 0. - Repeat steps while a condition holds:
while (...). - Mark the start and end of the repeated block:
{ }.
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
- 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.
- 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)
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)?
2 to start, 6 per card, 3 to finish.
2 + 6 × 3 + 3 = 23.- Answer: 23
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?
Which element repeats the steps?
- The loop-back arrow becomes Step 7, Go back to Step 2.
- Answer: option 2.
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"?
while (...) { } blockOne construct captures the check and the repetition.
- The decision plus its loop-back arrow become one
whileline and a pair of braces. - Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Which are disadvantages of flowcharts listed in the lecture?
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.
Numerical Answer Type (NAT).
The counting-cards pseudocode listing has how many lines (Start and End included)?
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
Terminal, Process, Decision
Arrows: operation flow
Size, Collaboration, Versions
"If ..., go to Step 8"
"Go back to Step 2"
Repeated execution
2 while (condition)
3 { } marks the block
No "go to" jumps
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
Start
Count = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
Increment Count
}
EndEvery 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 = 0
while (Pile 1 has more cards) {
Pick a card X from Pile 1
Move X to Pile 2
Sum = Sum + X.Maths
}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 on the right is the current value. The whole right side is worked out first.Sum on the left is the updated value: the result is stored back into it.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
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
}
}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 (=)
| Symbol | Meaning | Example |
|---|---|---|
= | 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
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
}
}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
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
}
}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
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
}
}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 id | Gender | Maths | BoySum after | GirlSum after |
|---|---|---|---|---|
| 0 | M | 45 | 45 | 0 |
| 1 | F | 78 | 45 | 78 |
| 2 | M | 91 | 136 | 78 |
| 3 | F | 78 | 136 | 156 |
| 4 | M | 91 | 227 | 156 |
| 5 | F | 60 | 227 | 216 |
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
| Idea | Pseudocode |
|---|---|
| Assignment | Count = 0, Sum = Sum + X.Maths |
| Conditional, once | if (condition) { ... } / if ... else ... |
| Conditional, repeatedly | while (condition) { ... } |
| Equality versus assignment | if (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
Sumstays 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 cardsis 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.
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 :
| Card | Maths | Test X.Maths < MinM | MinM after |
|---|---|---|---|
| start | 100 | ||
| 0 | 70 | 70 < 100: True | 70 |
| 1 | 55 | 55 < 70: True | 55 |
| 2 | 80 | 80 < 55: False | 55 |
| 3 | 55 | 55 < 55: False (strict, so the first 55 is kept) | 55 |
| 4 | 40 | 40 < 55: True | 40 |
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:
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 / CountOn the six cards: , , . 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 , , . For the boys , , .
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 = 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 (card 2) and (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:
| Compound | Same 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) |
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 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 . A card that satisfies both parts is still added only once.
E. Where the initialisation goes
- Initialise before the
while. WritingCount = 0inside 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:
0for 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
- To read pseudocode, first spot the
while, then list the initialisations above it, then read the body line by line. - Decide
ifalone orif ... elseby asking whether the No branch has work.
- Writing
=inside anifcondition instead of==. - Reading
Sum = Sum + X.Mathsas a false equation. - Putting the initialisation (
Sum = 0) inside the loop. - Forgetting the
-1start forMaxCard.
Practice questions (graded-assignment style)
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?
Add the marks of the cards with gender M.
- The boys are cards 0, 2, 4:
45 + 91 + 91 = 227. - Answer: 227
Numerical Answer Type (NAT).
For the same cards, what is GirlSum at the end of the boys' and girls' program?
The else block adds the girls' marks.
- The girls are cards 1, 3, 5:
78 + 78 + 60 = 216. - Answer: 216
Numerical Answer Type (NAT).
For the same cards, what is MaxCard at the end of the max-card program?
The strict > keeps the first maximum.
MaxMbecomes 45, 78, 91 at cards 0, 1, 2; the later 91 at card 4 is not strictly greater, soMaxCard = 2.- Answer: 2
Multiple Choice Question (MCQ): choose the one correct option.
Which line stores a value?
if (X.Gender == M)Sum = Sum + X.Mathswhile (Pile 1 has more cards)if (X.Maths > MaxM)Which statement changes a variable?
=assigns: it stores the right side inSum. The other lines only test conditions.- Answer: option 2.
Multiple Select Question (MSQ): select all that apply.
Choose the correct pairings.
if (...) { ... }if (...) { ... } else { ... }while (...) { ... }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.
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?
The condition is either True or False.
- Exactly one of the two blocks runs, then control returns to the
whilecheck. - Answer: option 3.
Numerical Answer Type (NAT).
For the same six cards, what does the plain sum program (Sum = Sum + X.Maths for every card) give?
Add all six marks.
45 + 78 + 91 + 78 + 91 + 60 = 443, which equals227 + 216.- Answer: 443
Numerical Answer Type (NAT).
Six cards have Maths marks 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?
MinM takes each smaller value in turn: .
- The test fails for 80 (not less than 55), for the second 55 (strict), and for 65 (not less than 40).
- Answer: 40
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?
Both accumulators sit inside the if, so they see only the girls.
- Girls are cards 1, 3, 5 with marks . , .
- .
- Answer: 72
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?
A card counts only if both parts are True.
- Boys: cards 0, 2, 4 with marks 45, 91, 91. Card 0 fails ( is False). Cards 2 and 4 pass.
- Answer: 2
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?
A card is added once if at least one part is True.
- Cards 1, 3, 5 (girls): .
- Boys with Maths above 85: cards 2 and 4: . Card 0 (45) passes neither part.
- .
- Answer: 398
Multiple Select Question (MSQ): select all that apply.
Choose the correct statements.
MinM = 0 is the starting value and the test is X.Maths < MinM, then MinM stays 0 for marks that are all positive.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).Avg = Sum / Count placed after the loop fails when no card passed the filter, because Count is 0.not (A and B) is the same as (not A) and (not B).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.
Sum = Sum + X.Maths
Right: current, left: updated
Pick X, move X to Pile 2
Start / End omitted
runs once when reached
No branch: nothing
No: GirlSum += X.Maths
Exactly one block runs
if (X.Maths > MaxM) MaxM = X.Maths
MaxCard = -1, then X.Id
= stores a value
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
| Method | How it works | Words dataset result |
|---|---|---|
| Two iterations | Pass 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 iteration | After each count update, compare it with Max-frequency and replace it if larger. | Same answer, one pass |
Flowchart patterns on the Scores dataset
| Goal | Initialise | Check inside the loop | Yes (True) | No (False) |
|---|---|---|---|---|
| Max marks | max = 0 | CardX.Maths > max? | max = CardX.Maths | nothing |
| Max and its card | max = 0, maxCardId = -1 | CardX.Maths > max? | also maxCardId = CardX.id | nothing |
| All cards with max | max = 0, maxCardId = -1 | > max? then = max? | >: reset list to CardX.id | =: append CardX.id; else nothing |
Flowchart to pseudocode
| Flowchart element | Pseudocode |
|---|---|
| Process box that sets a variable | Assignment: Count = 0, Sum = Sum + X.Maths, Count = Count + 1 |
| Loop decision + arrow back | while (Pile 1 has more cards) { ... } |
| Filter decision, No does nothing | if (condition) { ... } |
| Filter decision, both branches work | if (condition) { ... } else { ... } |
| Start / End terminals | Dropped from pseudocode after Lecture 2.10's first example |
Why pseudocode, and notation to remember
- 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".
X.Maths,X.Gender,X.Id: fields of card X.=assigns;==compares and gives a Boolean.{ }marks where a block starts and ends.-1as an id means "no card yet".
Common mistakes
- In the two-pass method iteration 2 is not inside iteration 1.
- A strict > keeps only the first maximum card; use the list version for all.
==tests;=stores.
- It only works for non-negative marks; all-zero marks leave maxCardId at -1.
- A new maximum must restart the list, not extend it.
- Use
whileandif, not "go to Step n".