Recap
An algorithm is a finite list of precise steps that solves a problem. Every algorithm is assembled from three building blocks.
| Block | What it does | Everyday example | Flowchart shape |
|---|---|---|---|
| Sequencing | Steps run one after another, in order | Fill the kettle, then boil it, then pour | Boxes joined by arrows |
| Selection | A true or false decision picks one path | If it is raining, take an umbrella | Diamond with two exits |
| Repetition | A process repeats until a desired outcome is reached | Stir until the sauce thickens | An arrow that goes back to an earlier step |
Order matters in two ways.
- The order of the steps: shoes before socks is a different algorithm from socks before shoes.
- The nesting of the blocks: a decision inside a loop is asked on every pass; a loop inside a decision runs only if the decision comes out the right way.
Key relationships
| Idea | Rule to remember |
|---|---|
| Selection vs repetition | Selection asks once; repetition asks again and again |
| Typical pattern | A selection inside a repetition: go through everything, act only on some |
| Stopping condition | Every repetition needs one, and something must move toward it |
| Tracing | One row per pass, one column per changing value |
| Two ways to describe | Numbered steps in plain language, or a flowchart |
Assumptions
- The steps are precise: anyone following them gets the same result.
- The algorithm finishes after a finite number of steps.
- A decision is a question whose answer is exactly true or false.
Mistakes to avoid
- Treating a loop and an
ifas interchangeable because both involve a test. - Moving a step inside or outside a loop without checking how many times it now happens.
- Writing a repeat step with no condition that can ever end it.
- Describing the algorithm vaguely (“deal with the late books”) instead of with exact steps and values.
- Tracing without writing the values down.
Quick self-check
- Which building block does this describe? “Keep adding eggs until the bowl holds 6.” Answer: repetition, the process repeats until the desired outcome (6 eggs) is reached.
- A program asks whether a number is negative once and prints a message if it is. Which block is that? Answer: selection (a single decision, no repeating).
- In which algorithm is the decision made more times: “for each of 5 students, if the student is absent, record it” or “if student 1 is absent, then for each of 5 students, record it”? Answer: the first: its decision is inside the loop, so it is made 5 times; the second makes it once.
- Trace:
total = 0; repeat 4 times: if total < 6, add 2 to total.What istotalat the end? Answer: 0, 2, 4, 6 after passes 1 to 3; on pass 4 the test 6 < 6 is false, so total stays 6.
Full explanations and diagrams are in the Topic 2.1 study guide.