02. Solving problems on paper first — Homework solutions
The flowcharts below are sample answers. Yours can be drawn by hand with the same shapes — ovals, rectangles, diamonds, arrows.
Problem 1 — Brush your teeth
Problem. A straight-line flowchart with no questions and no loops.
Sample answer.
Common mistakes.
- Skipping a boring step (squeezing toothpaste, rinsing). The computer skips it too.
- Combining two actions into one box (Brush teeth and spit out). A box is one action. An and usually means two boxes.
Problem 2 — What to watch
Problem. One diamond. The yes-branch loops back; the no-branch ends with press play.
Sample answer.
The yes branch loops back to pick a show, so
the program tries again.
Common mistakes.
- Looping back to open the app. It is already open. The loop should return to the first step that changes — picking a show, not opening the app.
Problem 3 — What to wear
Problem. At least two diamonds. The paths join at the end.
Sample answer.
Four paths run through it: cold + rainy, cold + dry, warm + rainy, warm + dry. Each makes different choices, then all four meet at put it on and leave.
Common mistakes.
- Forgetting the second diamond's paths join back up. If they do not, half the time the program never reaches put it on and leave. Check that every arrow eventually reaches an end.
Challenge — A loop with a counter
Problem. Stop exactly after ten press-ups. Needs a counter and a question.
How to think about it. A loop that runs N times has this shape:
- Set a counter to 0.
- Has the counter reached N? If yes, stop.
- Do one round of work.
- Add 1 to the counter.
- Go back to step 2.
Sample answer.
Trace it: counter starts at 0. Is it 10? No. Press-up 1, counter becomes 1. Is it 10? No. Press-up 2, counter becomes 2. ... When it hits 10 the answer is yes and we stop at exactly ten.
This is the pattern of a for i = 1, 10 do ... end loop
you will write in Chapter 18. The flowchart is the picture; the Lua code
is that picture written down.
Common mistakes.
- Forgetting the add 1 to the counter box. The counter stays at 0 forever and you do press-ups for the rest of your life — an infinite loop, a real bug in real code.
- Checking is the counter greater than 10 and stopping there. It can work, but it is easy to be off by one. Equal to 10, with the add 1 after the press-up, is cleanest.
Done?
The next chapter zooms out to the three building blocks you have already met here: doing things in sequence, asking yes/no questions to pick a path, and looping back to repeat work.