Skip to content
S3U
Login Create Account

Science / Programming basics / Grade 7 / sc7s2

First Match: Repair the Missing Stop

Explain why a faulty search replaces the first match, then test the repair with duplicates and empty input.

All worksheets

Watch the lesson | Build and test in Route Coder

5 questions0m 0s

Learn first

Programs follow precise instructions

A program is a set of instructions. A variable stores a value. A condition chooses between paths. A loop repeats steps. Output is the result produced.

How to work it out Trace one instruction at a time. Keep a record of values and check exactly when a condition or repeated step is evaluated.

A separate example In a separate trace, start with n = 2, add 3, then double n. The two instructions happen in order: 5 is an intermediate value before the final result.

Learn the skill

Copying a matching value does not itself stop a loop. Put the early scan exit immediately after copying inside the successful branch. End closes a block; after the loop, Main continues. With the rule value >= 2, fallback 0 cannot be confused with a valid match.

Worked example

A faulty scan of [1, 3, 2] copies 3, then keeps scanning and copies 2. It reports 2, the last match, instead of the required first match 3. Stop after the first copy to preserve 3.

The faulty scan starts at zero, checks each value in 1, 4, 2, copies every match, continues to the next item and finally reports. No early stop is present.
Repair the continuation, not the supplied list.

A robot left out one instruction

Faulty program: set result to 0; for each value in [1, 4, 2], if value >= 2, copy value to result; end If; end For each; report result. There is no Stop instruction. The task is to find the FIRST value at least 2. Use the given order; item numbers begin at 1.

Question 1 What does the faulty program report for [1, 4, 2]?
Question 2 Which repair preserves the required first match?
Question 3 With the repair, how many comparisons run for [2, 2, 4]?
Question 4 With the repair, what happens for an empty list [ ]?
Question 5 Which statement correctly describes the early stop?