03. The three building blocks — Homework solutions
Problem 1 — Spot the pattern
Sample answers.
- Counting the marbles in a jar — repetition. Look at one marble, add 1 to a count, then the next, and the next, until none are left.
- Deciding whether you can afford a new game — decision. The question is is the price less than my savings?. Yes leads to buy; no leads to wait.
- Following a recipe with no choices in it — sequence. Each step happens once, in order.
- Asking the user to enter a number until they type a valid one — repetition on the outside (keep asking), with a decision inside (was the answer valid?). The repetition is the main pattern.
- Printing each name on a class list — repetition. The pattern is "for each name, print it". Whether the list has 20 names or 200, the loop runs once per name.
Common mistakes.
- Calling everything a decision because the description has an if. If often sits inside a loop without being the main pattern. Ask: would this stop after one round, or keep going? If it keeps going, the main pattern is repetition.
Problem 2 — Sequence only
Sample answer.
Common mistakes.
- Sneaking in a question. Is the toast brown enough? is a diamond, and this problem said no diamonds. Trust the toaster to pop on its own.
Problem 3 — Sequence and decision
Sample answer.
Common mistakes.
- Putting turn out the light on only one branch. Both branches end the same way, so the step belongs after they join, not inside one of them.
Challenge — All three patterns
Sample answer. This flowchart uses all three patterns at once: a sequence of setup steps at the top, a loop in the middle that keeps calling the pet, and a decision at the end about the treat.
Every pattern is here:
- A sequence at the top fills the bowls and starts the counter.
- A loop in the middle calls the pet up to five times, with a small decision inside it (has the pet arrived? and is call count 5?).
- A decision at the bottom checks what happened and either treats the pet or puts the food away.
Both paths out of the loop lead to the same place (the decision at the bottom), so the rest of the program runs the same way no matter how the loop ended.
Common mistakes.
- The hardest part is the two ways out of the loop: the pet showed up, or the counter hit 5. Forget either one and it is a bug — the loop never ends, or it gives up too early.
- Losing track of "did the pet show up?" after the loop. In code you would store the answer in a variable. On paper, label the arrow leaving the loop so the bottom decision knows what to check.
Done?
You can now spot the three building blocks in any plan. The next two chapters sharpen the reading side of the same skill: Tracing a program by hand shows you how to work out what code does on paper, and Naming and decomposition shows you how to keep a program clear enough to trace at all. Then the Part 1 mini-project ties the planning skills together.