Why Control Flow Matters
Most algorithms are built from three control flow patterns: sequence (do steps in order), selection (choose a path based on a condition), and repetition (repeat steps while a condition holds). You can combine these patterns to express surprisingly complex behavior.
A key skill is tracing: manually simulating the algorithm with specific inputs, writing down intermediate values after each step. Tracing reveals mistakes early, especially off-by-one errors, wrong conditions, and incorrect ordering of steps.
1) Sequence (Ordered Steps)
Sequence means instructions run top-to-bottom in the order written. There are no branches and no repeats—just a pipeline of transformations.
Example: Compute a Receipt Total
Task: given price, quantity, and taxRate, compute subtotal, tax, and total.
subtotal = price * quantity
tax = subtotal * taxRate
total = subtotal + taxTrace It (Manual Walkthrough)
Use sample inputs: price = 12.50, quantity = 3, taxRate = 0.08. Record intermediate states:
Continue in our app.
You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.
Or continue reading below...Download the app
| Step | Operation | Resulting values |
|---|---|---|
| 1 | subtotal = price * quantity | subtotal = 37.50 |
| 2 | tax = subtotal * taxRate | tax = 3.00 |
| 3 | total = subtotal + tax | total = 40.50 |
Tracing habit: after every assignment, write the new value. If you can’t trace it on paper, you likely can’t debug it in code.
Common Sequence Pitfalls
- Wrong order: computing
taxbeforesubtotal. - Overwriting: reusing a variable name and losing a value you still need.
- Hidden dependencies: a later step assumes an earlier step already happened.
2) Selection (Decisions)
Selection chooses between paths based on a condition. The condition should be something that can be evaluated as true/false.
Example: Free Shipping Decision
Rule: if subtotal is at least 50, shipping is free; otherwise shipping costs 6.
if subtotal >= 50 then
shipping = 0
else
shipping = 6Trace It with Two Inputs
Trace selection by testing both sides of the condition.
| Case | subtotal | Condition subtotal >= 50 | shipping |
|---|---|---|---|
| A | 40 | false | 6 |
| B | 75 | true | 0 |
Flowchart-Style Decision Points
You can express selection as a decision node:
[Decision] subtotal >= 50 ?
Yes -> shipping = 0
No -> shipping = 6Multi-Branch Selection (Else-If Ladder)
Example: apply a discount rate based on membership level.
if level == "gold" then
discountRate = 0.15
else if level == "silver" then
discountRate = 0.10
else
discountRate = 0.00Tracing tip: once a branch matches, the rest are skipped. When tracing, circle the first condition that becomes true.
Selection Pitfalls to Watch For
- Overlapping conditions: two branches could both be true; ordering then matters.
- Missing default: forgetting the
elsepath can leave variables unset. - Boundary mistakes: using
>instead of>=(or vice versa).
3) Repetition (Loops)
Repetition runs a block of steps multiple times. A loop needs:
- a start state (initial values),
- a condition that decides whether to continue,
- an update that changes state so the loop eventually ends.
Example: Sum Numbers from 1 to n
Given n, compute sum = 1 + 2 + ... + n.
sum = 0
i = 1
while i <= n do
sum = sum + i
i = i + 1Trace It (n = 5)
When tracing loops, make a table per iteration. Record the condition check and the updated variables.
| Iteration | i (start) | sum (start) | Action | i (end) | sum (end) |
|---|---|---|---|---|---|
| 1 | 1 | 0 | sum = sum + i | 2 | 1 |
| 2 | 2 | 1 | sum = sum + i | 3 | 3 |
| 3 | 3 | 3 | sum = sum + i | 4 | 6 |
| 4 | 4 | 6 | sum = sum + i | 5 | 10 |
| 5 | 5 | 10 | sum = sum + i | 6 | 15 |
Stop when the condition fails: when i = 6, i <= 5 is false, so the loop ends.
Loop Pitfalls
- Infinite loop: forgetting
i = i + 1(condition never changes). - Off-by-one: using
i < ninstead ofi <= n. - Wrong initialization: starting
iat 0 when you intended 1.
Combining Sequence + Selection + Repetition into One Procedure
Now combine all three patterns into a larger, realistic procedure: process a shopping cart (a list of item prices), apply a discount if eligible, then decide shipping.
Procedure: Checkout Total
Inputs:
prices: a list of item prices (e.g.,[12.50, 8.00, 25.00])member: true/falsetaxRate: e.g.,0.08
Rules:
- Compute
subtotalby summing prices (repetition). - If
memberandsubtotal >= 30, apply 10% discount (selection). - If discounted subtotal is at least 50, shipping is free; else shipping is 6 (selection).
- Compute tax and final total (sequence).
subtotal = 0
for each price in prices do
subtotal = subtotal + price
if member == true and subtotal >= 30 then
discount = subtotal * 0.10
else
discount = 0
discountedSubtotal = subtotal - discount
if discountedSubtotal >= 50 then
shipping = 0
else
shipping = 6
tax = discountedSubtotal * taxRate
total = discountedSubtotal + shipping + taxFull Trace with Sample Input
Sample input: prices = [12.50, 8.00, 25.00], member = true, taxRate = 0.08.
Trace Part A: Loop (Repetition)
| Item | price | subtotal (before) | subtotal (after) |
|---|---|---|---|
| 1 | 12.50 | 0.00 | 12.50 |
| 2 | 8.00 | 12.50 | 20.50 |
| 3 | 25.00 | 20.50 | 45.50 |
After the loop: subtotal = 45.50.
Trace Part B: Discount Decision (Selection)
Condition: member == true and subtotal >= 30 becomes true and true → true.
So:
discount = 45.50 * 0.10 = 4.55discountedSubtotal = 45.50 - 4.55 = 40.95
Trace Part C: Shipping Decision (Selection)
Condition: discountedSubtotal >= 50 becomes 40.95 >= 50 → false, so shipping = 6.
Trace Part D: Final Sequence
tax = 40.95 * 0.08 = 3.276total = 40.95 + 6 + 3.276 = 50.226
Depending on your rounding rules, you might round tax and total to cents. When tracing, write down the rounding rule you are using so your results are consistent.
Tracing Toolkit: How to Practice Like a Programmer
1) State Table Template
Use a consistent table format. For any algorithm, list the variables that matter and fill them after each step.
Step | What happened? | var1 | var2 | var3 | ...2) Decision Checklist
- Write the condition.
- Substitute actual values.
- Simplify to true/false.
- Mark which branch runs.
3) Loop Checklist
- What are the initial values?
- What is the loop condition?
- What changes each iteration?
- When does it stop (first value that makes condition false)?
Exercises: Convert Between Narrative, Pseudocode, and Flowchart-Style Decisions
Exercise 1: Sequence Conversion
Narrative: “Take a temperature in Celsius. Convert it to Fahrenheit using F = C * 9/5 + 32. Then print the Fahrenheit value.”
- Write pseudocode with three lines (assignment/compute/print).
- Trace with
C = 0andC = 25, recording intermediate values.
Exercise 2: Selection Conversion (Single Decision)
Narrative: “If the password length is at least 12, mark it as ‘strong enough’; otherwise mark it as ‘too short’.”
- Write pseudocode using
if/else. - Write a flowchart-style decision point in text form:
[Decision] length >= 12 ?with Yes/No branches. - Trace with lengths 8, 12, and 20.
Exercise 3: Selection Conversion (Multiple Branches)
Narrative: “Assign a letter grade: 90+ is A, 80–89 is B, 70–79 is C, 60–69 is D, otherwise F.”
- Write pseudocode using an ordered
if / else if / elseladder. - Trace with scores 59, 60, 70, 85, 90, 100.
- Identify which boundary comparisons must be
>=and which can be>.
Exercise 4: Repetition Conversion (Counting Loop)
Narrative: “Ask for 5 daily step counts and compute the average.”
- Write pseudocode using a loop that runs exactly 5 times.
- Create a trace table with columns: iteration, inputSteps, runningSum.
- Test with inputs: 4000, 6000, 5000, 7000, 8000.
Exercise 5: Repetition Conversion (Condition-Controlled Loop)
Narrative: “Keep reading numbers until the user enters 0. Compute the sum of the numbers entered (excluding the 0).”
- Write pseudocode using a
whileloop. - Trace with inputs: 5, 2, -3, 0.
- In your trace, explicitly show the moment the loop stops (the condition becomes false).
Exercise 6: Combine All Three Patterns
Narrative: “Given a list of quiz scores, drop any score below 0 or above 100 (ignore invalid). Compute the average of valid scores. If the average is at least 70, output ‘pass’; otherwise output ‘fail’. If there are no valid scores, output ‘no data’.”
- Write pseudocode that uses: a loop over scores (repetition), an
ifto filter invalid scores (selection), and a finalif/elsefor pass/fail/no-data (selection), plus ordered computations (sequence). - Trace with:
[80, 90, 200, -5, 70]and then with[200, -1]. RecordcountValidandsumValidafter each item.
Exercise 7: Flowchart-Style Decision Points for the Checkout Procedure
For the combined checkout procedure earlier, write the two decision nodes in flowchart-style text:
[Decision] member == true AND subtotal >= 30 ?[Decision] discountedSubtotal >= 50 ?
Then, for each decision, provide two example inputs that force the Yes branch and the No branch, and trace the resulting variable changes.