Planning & pseudocode
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Plan before you code
- An algorithm is a clear list of steps that solves a problem.
- Good programmers plan the steps before they type code.
- A plan helps you spot mistakes early and explain your idea.
Decomposition
- Decomposition means breaking a big problem into smaller parts.
- Solve each small part on its own.
- Small parts are easier to write, test, and fix.
Abstraction
- Abstraction means keeping only the details that matter.
- You hide the parts you do not need right now.
- A map is an abstraction: it shows roads, not every tree.
Structured English
- Structured English writes the steps as plain numbered sentences.
- It is not real code, so anyone can read it.
1. Read the number.
2. If it can be divided by 2 with no remainder, it is even.
3. Otherwise it is odd.
4. Output the answer.
Flowcharts
- A flowchart draws the steps as boxes joined by arrows.
- A rectangle is a step; a diamond is a decision (yes / no).
( start )
|
[ read n ]
|
< n > 0 ? > --no--> [ output "not positive" ]
| yes
[ output "positive" ]
|
( end )
Three building blocks
- Sequence: steps run one after another.
- Selection:
if/elif/elsechooses a path. - Iteration:
for/whilerepeats steps.
In Cambridge pseudocode
- The same plan in pseudocode, then in Python below.
total ← 0
FOR i ← 0 TO LENGTH(numbers) - 1
total ← total + numbers[i]
NEXT i
average ← total / LENGTH(numbers)
OUTPUT average
numbers = [4, 8, 6]
total = 0
for n in numbers:
total = total + n
average = total / len(numbers)
print(average)
Now you try
- Each task gives you a plan in words. Turn it into Python.
- Press Check answer to test your code.
Follow this plan: read a whole number; if it divides by 2 with no remainder print Even, otherwise print Odd. For input 4, print Even.
Click Run to see the output here.
Follow this plan: read a number N; add up every whole number from 1 to N; print the total. For input 5, print 15.
Click Run to see the output here.
Decompose this into a function. Write count_vowels(word) that returns how many letters of word are vowels (a e i o u, lowercase).
Click Run to see the output here.