CP1 / COURSE HOME

Week 05 / Describe and decide

Give a search a stopping rule

Repeat an action until an outcome is known.

A for loop worked when we chose the observation times in advance. A reference search ends when a switch is found, so the number of moves is not known beforehand.

A simulated carriage searches for its reference switch. It may make at most five moves; the switch is checked before moving and after each move.

Start with the problem

Try this first.

Act out two searches on paper: the switch is already active, and the switch never activates. How many moves should each make, and what message should each return?

Why this week's tool?

A while loop continues while a condition holds. A counter limits the attempts, and an explicit result separates finding the reference from running out of moves.

By the end: Trace the search without an extra move, including when the switch activates on the fifth move.

The idea behind the program

A while loop needs a progress story

Identify the initial state, condition and update. In this model, position increases by one on each move. If the update is missing, the condition may remain true forever.

Success and exhaustion are different

A bounded loop can stop because it found the reference or because it ran out of moves. The exit alone is not success. Inspect the final state before choosing the outcome message.

Check the final boundary

A switch reached on move five counts as found. Reporting timeout immediately after the fifth move without checking the switch would create an off-by-one error. A real homing design needs hardware-specific limits and supervision beyond this teaching model.

A short Python example

Read the example alongside the explanation. Run it in a new notebook cell and change one input to see how it behaves.

position = 0
reference_at = 5
max_moves = 5
while position < reference_at and position < max_moves:
    position = position + 1
    print('Move', position)
if position >= reference_at:
    print('REFERENCE FOUND')
else:
    print('SEARCH LIMIT REACHED')

Example output

Move 1
Move 2
Move 3
Move 4
Move 5
REFERENCE FOUND

A while loop needs progress as well as a condition

A while loop checks the current state before each iteration. Its condition says when to continue; an update must move the state toward stopping. A correct condition alone cannot guarantee termination.

Draw or trace

Draw a cycle: test attempts < 3 → perform one attempt → increase attempts → test again. Mark the exit when the test is false.

Predict before running. Starting with attempts = 0, how many attempts occur? What if continue runs before the increment every time?

Trace and explanation — after your prediction
  1. Tests at attempts 0, 1 and 2 are true; each completed iteration increments the count.
  2. At attempts 3 the test is false, so no fourth attempt starts.
  3. If every iteration skips the update, attempts stays 0 and the loop does not terminate.

There are three attempts in the first version. Every path that continues must make the required progress, or another stopping condition must apply. break exits immediately; continue skips the rest of the current iteration.

Change one thing. Start at attempts = 3 and predict whether the body runs. Distinguish zero iterations from running once and then checking.

Türkçe: Koşul devam etmeyi söyler; güncelleme bitişe ilerlemeyi sağlar. continue güncellemeyi atlarsa döngü sonsuza gidebilir.

Examples and variations

Each example changes something about the same problem. Open the ones you want to explore and follow the worked explanation.

01Found early

Switch becomes active at position 3; limit 5 moves

Question: How many moves occur, and why does the loop stop?

  1. Positions 0, 1, 2: switch inactive
  2. Move to position 3
  3. Switch active; loop condition becomes false

3 moves; REFERENCE FOUND

The success condition ended the search before the budget was exhausted.

02Found at the limit

Switch becomes active at position 5; limit 5 moves

Question: Is the fifth move success or exhaustion?

  1. Move 5 reaches the reference
  2. Loop exits at position 5
  3. Final state check sees the active switch

5 moves; REFERENCE FOUND

The final check prevents a boundary success from being mislabeled as failure.

03Never found in budget

Switch would activate at position 8; limit 5 moves

Question: What should be reported after the fifth move?

  1. Positions 1–5 do not reach 8
  2. Move budget ends at 5
  3. Final state does not satisfy reference condition

5 moves; SEARCH LIMIT REACHED

Reaching a software limit does not establish where the physical reference is. Do not silently report success.

See the Colab code run

Interactive walkthroughs of while Loops, break & continue. Enable JavaScript to step through code, variables, collections and output. The companion notebook remains available below.

Work on it in Colab

Use the notebook to try the ideas yourself. The steps below connect this week's example to the programming practice.

  1. Draw a state trace with position, switch state and remaining moves. Start with a switch already active at position zero.
  2. Test reference positions 3, 5 and 8. State the reason for every loop exit.
  3. Describe what removing the position update would do; do not run an unbounded version. Add a written invariant: moves never exceed five.
  4. Replace the success message with a generic 'done' and discuss what useful information an operator loses.

Something to take away: A trace for early success, boundary success and exhaustion, plus explicit messages for each outcome.

Suggested exercises, downloads & solutions

Read the notebook's teaching cells before these exercises.

  • EX01 Countdown (Easy)
  • EX02 Sum Until Zero (Easy)
  • EX04 Password Checker (Medium)
Download notebookWorked solutions

Use the notebook's core and optional labels to choose your workload. This activity fits within guided class time.

Optional notes & guidance
My notes
Using AI or working with a partner

Ask AI to implement the bounded simulator. Challenge it with an already-active switch and a switch reached on the last allowed move. Look for code that equates every loop exit with success.

You can also review the supplied example with a partner. Use the same inputs to compare the reasoning. Follow the syllabus rules for assessed work.