Free Ebook cover Programming Logic Foundations: Thinking Like a Programmer

Programming Logic Foundations: Thinking Like a Programmer

New course

10 pages

Control Flow Foundations: Sequence, Selection, and Repetition

Capítulo 5

Estimated reading time: 6 minutes

+ Exercise

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 + tax

Trace 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 App

Download the app

StepOperationResulting values
1subtotal = price * quantitysubtotal = 37.50
2tax = subtotal * taxRatetax = 3.00
3total = subtotal + taxtotal = 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 tax before subtotal.
  • 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 = 6

Trace It with Two Inputs

Trace selection by testing both sides of the condition.

CasesubtotalCondition subtotal >= 50shipping
A40false6
B75true0

Flowchart-Style Decision Points

You can express selection as a decision node:

[Decision] subtotal >= 50 ?
    Yes -> shipping = 0
    No  -> shipping = 6

Multi-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.00

Tracing 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 else path 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 + 1

Trace It (n = 5)

When tracing loops, make a table per iteration. Record the condition check and the updated variables.

Iterationi (start)sum (start)Actioni (end)sum (end)
110sum = sum + i21
221sum = sum + i33
333sum = sum + i46
446sum = sum + i510
5510sum = sum + i615

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 < n instead of i <= n.
  • Wrong initialization: starting i at 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/false
  • taxRate: e.g., 0.08

Rules:

  • Compute subtotal by summing prices (repetition).
  • If member and subtotal >= 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 + tax

Full Trace with Sample Input

Sample input: prices = [12.50, 8.00, 25.00], member = true, taxRate = 0.08.

Trace Part A: Loop (Repetition)

Itempricesubtotal (before)subtotal (after)
112.500.0012.50
28.0012.5020.50
325.0020.5045.50

After the loop: subtotal = 45.50.

Trace Part B: Discount Decision (Selection)

Condition: member == true and subtotal >= 30 becomes true and truetrue.

So:

  • discount = 45.50 * 0.10 = 4.55
  • discountedSubtotal = 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.276
  • total = 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 = 0 and C = 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 / else ladder.
  • 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 while loop.
  • 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 if to filter invalid scores (selection), and a final if/else for pass/fail/no-data (selection), plus ordered computations (sequence).
  • Trace with: [80, 90, 200, -5, 70] and then with [200, -1]. Record countValid and sumValid after 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.

Now answer the exercise about the content:

In the checkout procedure, which statement correctly describes how discount and shipping are determined before computing tax and total?

You are right! Congratulations, now go to the next page

You missed! Try again.

The procedure first checks member == true and subtotal >= 30 to decide a 10% discount, producing discountedSubtotal. It then checks discountedSubtotal >= 50 to choose shipping (0 or 6) before computing tax and total.

Next chapter

Determinism, State, and Tracing: Predicting What an Algorithm Will Do

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.