Video lecture
Watch on YouTube(opens in a new tab)Sub topic 2
The Three Building Blocks: Sequence, Selection, Iteration
This chapter assumes you can read simple Python and know that a mod b (written a % b in Python) is the remainder of dividing a by b. The running example is Euclid's algorithm for the greatest common divisor (GCD).
Sequence, Selection, Iteration
Any step-by-step procedure can be built from three control structures:
| Structure | Meaning | Euclid example |
|---|---|---|
| Sequence | Do steps in order | compute `r`, then shift `a` and `b` |
| Selection | Choose a path based on a condition | if `b` is 0, stop |
| Iteration | Repeat steps while a condition holds | loop until `b` is 0 |
A common error is to leave a condition implicit. For example, "keep dividing" never says when to stop. Each selection and each loop needs an explicit test.
Pseudocode
Pseudocode is structured text that shows control flow without tying you to one language's syntax. Write the specification as comments, use <- for assignment, and close every block explicitly.
function GCD(a, b)
// Precondition: a >= 0, b >= 0, not both zero
// Postcondition: returns gcd(a, b)
while b != 0 do
r <- a mod b
a <- b
b <- r
end while
return a
end functionFlowcharts
A flowchart draws the same control flow. Rectangles are actions, a diamond is a decision, and arrows show order. In a flowchart, a loop shows up as an arrow that points back to an earlier decision.
Tracing by Hand
To trace an algorithm, you run it on paper and record every variable's value once per loop iteration in a state table. Here is the Python version:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6Trace of gcd(48, 18):
| Iteration | a | b | a mod b |
|---|---|---|---|
| start | 48 | 18 | 12 |
| 1 | 18 | 12 | 6 |
| 2 | 12 | 6 | 0 |
| 3 | 6 | 0 | — |
The test b != 0 fails, so the function returns 6.
Exercise
Trace gcd(35, 14) with a state table. What does it return, and how many loop iterations run?
Show answer
States are (35, 14), then (14, 7) because 35 mod 14 = 7, then (7, 0) because 14 mod 7 = 0. Two iterations run, and the function returns 7.