CIE IGCSE | 7.9.2 Amend and Check a Complete Algorithm

Lesson objective

Understand an existing algorithm, plan a precise amendment and use dry runs and targeted tests to check new and original requirements.

Learn

7.9.2 | AMEND AND CHECK A COMPLETE ALGORITHM

01 | YOU ARE CHANGING A SYSTEM, NOT JUST A LINE

An algorithm already works, but its requirements change. Perhaps a shop adds a discount or a school wants an extra summary. Your job is to amend the solution: change it so that it meets the new requirements while preserving the behaviour that still applies.

This differs from correcting an error. A correct three-class algorithm becomes unsuitable if the school now needs four classes. There was no original mistake; the task has changed.

The difficult part is seeing the consequences. An extra output may require a new variable, an update inside a loop and a calculation after it. Reading only the final OUTPUT statement will miss those connections.

We will adapt the school attendance solution from the previous lesson. Read the original, plan the changes and check a complete amended version rather than patching isolated fragments.

02 | FIRST UNDERSTAND THE ORIGINAL

The school originally collects three accepted class attendance values. Every input is a whole number; values must lie from zero to thirty inclusive, with an out-of-range value retried. It outputs the total and classifies a total of at least sixty as Large session, otherwise Small session.

DECLARE Attendance : INTEGER
DECLARE Total : INTEGER
DECLARE ClassIndex : INTEGER
Total ← 0
FOR ClassIndex ← 1 TO 3
    REPEAT
        OUTPUT "Enter class attendance from 0 to 30"
        INPUT Attendance
    UNTIL Attendance >= 0 AND Attendance <= 30
    Total ← Total + Attendance
NEXT ClassIndex
OUTPUT "Total attendance: ", Total
IF Total >= 60
  THEN
    OUTPUT "Large session"
  ELSE
    OUTPUT "Small session"
ENDIF

Do not rush past code that looks familiar. Total starts once before the outer loop. The inner REPEAT obtains an acceptable value for the current class. Addition happens after validation, and the final classification happens after all three classes.

For inputs twelve, eighteen and thirty, the original outputs total sixty and Large session. This simple dry run establishes what the original instructions actually do.

03 | READ THE NEW REQUIREMENTS LITERALLY

Process four classes instead of three. Also output the number of participating classes, defined as classes with attendance greater than zero. Output average attendance per participating class. If no class participates, output “No participating classes” instead of calculating an average. Keep the existing input range, retry, total and session classification. Assume whole-number inputs.

Notice the definition of participating. A class with zero attendance still supplies a valid value and uses one of the four outer repetitions. It simply does not contribute to the participating-class count.

The average is not automatically Total divided by four. The requested denominator is the number of classes with positive attendance. Those two quantities can differ.

Translate the wording before editing. “Instead of” changes an existing quantity; “also” adds behaviour; “keep” explicitly preserves existing rules.

04 | MAKE A CHANGE PLAN

Map each new requirement to the statements it needs. This makes changes reviewable and helps you find missing pieces.

A requirement can affect more than one place
RequirementRequired amendmentLocation
Four classesChange FOR upper bound to 4Outer loop header
Count positive attendanceDeclare and initialise ParticipatingClasses; increment when Attendance > 0Before loop and after accepted input
Average of participating classesDeclare Average as REAL; divide total by participating countAfter loop
No participating classesGuard division and output alternative messageAfter loop
Keep existing behaviourRetain range retry, total and >= 60 decisionExisting relevant statements

Adding the name ParticipatingClasses to a declaration is not enough. It needs a starting value, an update rule and a meaningful output. Follow its complete life through the algorithm.

Keep an unchanged copy of the original for comparison. Make one coherent set of edits, then review the differences against this plan.

05 | DISTINGUISH THE LOOP COUNTER FROM THE NEW COUNT

ClassIndex controls the four outer repetitions. ParticipatingClasses records how many accepted attendance values are greater than zero. They have different jobs.

For accepted inputs zero, twelve, zero and eighteen, four classes have been processed but only two participate. Total is thirty.

ParticipatingClasses ← 0
// Inside FOR, after validation and total update:
IF Attendance > 0
  THEN
    ParticipatingClasses ← ParticipatingClasses + 1
ENDIF

Initialise the count before FOR. If you reset it inside FOR, the final value would describe only the last class. Increment by one, not by Attendance: you are counting classes rather than students.

Do not substitute ClassIndex for this count. Do not assume a particular value of the loop variable after NEXT to obtain a summary.

06 | PUT THE NEW UPDATE AFTER VALIDATION

Where a statement goes matters as much as what it says. An invalid input of thirty-one is positive, but it must not increase ParticipatingClasses.

Therefore both total accumulation and the positive-attendance count belong after the inner UNTIL. At that point Attendance holds an accepted value.

UNTIL Attendance >= 0 AND Attendance <= 30
Total ← Total + Attendance
IF Attendance > 0
  THEN
    ParticipatingClasses ← ParticipatingClasses + 1
ENDIF

If you placed the count inside the retry body, an invalid thirty-one followed by a valid twelve could count the same class twice. If you placed it after NEXT, only the final Attendance value would be examined.

Trace thirty-one then twelve within one class. The failed attempt changes neither summary. The accepted twelve adds twelve to Total and one to ParticipatingClasses.

07 | CHOOSE THE RIGHT AVERAGE AND HANDLE ZERO

Total contains attendance from all four classes. Zero-attendance classes contribute nothing, so that total is also the attendance of the participating classes.

With zero, twelve, zero and eighteen, divide thirty by two to obtain fifteen. Dividing by four would produce seven point five, which answers a different question: average across all processed classes.

IF ParticipatingClasses > 0
  THEN
    Average ← Total / ParticipatingClasses
    OUTPUT "Average attendance per participating class: ", Average
  ELSE
    OUTPUT "No participating classes"
ENDIF

If every attendance is zero, the count is zero. Division by zero is undefined, so the check must happen before the calculation. It is too late to calculate first and then check whether the denominator was zero.

Use REAL for Average because a mean can have a fractional part even when every input is an integer. The scenario does not specify rounding, so this algorithm leaves the calculated mean unrounded.

08 | CHECK THE WHOLE AMENDED ALGORITHM

Here is the complete amended solution. The assumed whole-number inputs still mean that the retry checks the range, without adding an unspecified conversion routine.

DECLARE Attendance : INTEGER
DECLARE Total : INTEGER
DECLARE ClassIndex : INTEGER
DECLARE ParticipatingClasses : INTEGER
DECLARE Average : REAL
Total ← 0
ParticipatingClasses ← 0
FOR ClassIndex ← 1 TO 4
    REPEAT
        OUTPUT "Enter class attendance from 0 to 30"
        INPUT Attendance
    UNTIL Attendance >= 0 AND Attendance <= 30
    Total ← Total + Attendance
    IF Attendance > 0
      THEN
        ParticipatingClasses ← ParticipatingClasses + 1
    ENDIF
NEXT ClassIndex
OUTPUT "Total attendance: ", Total
OUTPUT "Participating classes: ", ParticipatingClasses
IF ParticipatingClasses > 0
  THEN
    Average ← Total / ParticipatingClasses
    OUTPUT "Average attendance per participating class: ", Average
  ELSE
    OUTPUT "No participating classes"
ENDIF
IF Total >= 60
  THEN
    OUTPUT "Large session"
  ELSE
    OUTPUT "Small session"
ENDIF

The new IF inside FOR counts participating classes. After NEXT, one IF handles the average or its alternative. A separate IF classifies the total. These decisions are independent.

All-zero input therefore produces total zero, participating count zero, No participating classes and Small session. The new no-participation message does not replace the original session classification.

Check matching keywords and indentation: the inner UNTIL finishes validation; the first ENDIF finishes counting; NEXT closes class processing; the later ENDIFs close the two final decisions.

09 | TRACE THE NEW AND UNCHANGED STATE

Use attempts thirty-one, twelve, zero, eighteen and zero. The first attempt is rejected for class one, so five attempts supply four accepted class values.

Both summary variables begin at zero
ClassAttemptAccepted?Total after attemptParticipatingClasses
131No00
112Yes121
20Yes121
318Yes302
40Yes302

After NEXT, Average becomes thirty divided by two, or fifteen. Final outputs are total thirty, participating classes two, average fifteen and Small session.

This trace checks the relationship between validation and the new count. It also confirms that zero is accepted, that all four classes are processed and that the final mean uses only participating classes.

Record actual values, not just “the count increases”. A precise trace makes an incorrect placement or update visible.

10 | DESIGN TESTS FOR THE AMENDMENT

One successful run is useful evidence, but it cannot cover every important branch. Choose inputs with independently calculated expected results.

Expected results are planned, not claimed observations
Four accepted valuesTotalCountAverage or alternativeClassification
0, 12, 0, 1830215Small session
0, 0, 0, 000No participating classesSmall session
1, 2, 0, 0321.5Small session
30, 30, 30, 30120430Large session
20, 20, 19, 059359 / 3, unroundedSmall session
20, 20, 20, 060320Large session

The all-zero case exercises the new alternative. The fractional-mean case exposes an inappropriate integer result or integer division. The fifty-nine and sixty totals check the unchanged decision threshold.

Add invalid attempts such as minus one or thirty-one before a replacement. Check the repeated prompt and verify that neither invalid attempt alters Total or ParticipatingClasses.

If running an implementation, record its actual outputs separately and compare every requested output with its expected result. A correct total alone does not prove a correct amended solution.

11 | RETEST THE BEHAVIOUR YOU WERE ASKED TO KEEP

Regression testing means checking that a change has not broken behaviour that should still work. Here that includes accepting zero and thirty, rejecting values outside the range, retrying within the current class and using the inclusive sixty threshold.

Some old tests need adaptation because the intended number of classes changed. The old three-input sequence twelve, eighteen and thirty no longer completes a run. Add a fourth zero to preserve its total of sixty, then expect Large session as before.

Do not call the new fourth prompt an error: it is required by the amendment. Preserve the old rules, not outputs that conflict with the new specification.

If a test reveals a fault, correct the relevant statement, repeat the failed test and rerun other affected cases. Keep evidence of expected and actual behaviour rather than assuming that an edit fixed everything.

12 | FIND INCOMPLETE AMENDMENTS

A common patch changes the FOR limit and adds a final average, but forgets the new count. Another declares the count but never initialises it. Both look plausible until you follow the data.

Explain the effect, not just the replacement text
Faulty amendmentWhy it failsCorrection
Average ← Total / 4Includes non-participating classes in denominatorDivide by ParticipatingClasses when positive
Count before range acceptanceInvalid positive attempts can be countedUpdate after UNTIL
Count ← Count + AttendanceTotals students rather than counting classesAdd 1 for each positive accepted value
Average calculated before zero checkMay divide by zeroPut division inside positive-count branch
Final IF changed to Total > 60Breaks the retained equality ruleKeep Total >= 60

Separate the new requirement from an accidental change. For example, raising the input limit to forty has no justification here. Four classes does not mean forty students per class.

Review the final complete version, including declarations and outputs, rather than checking only the lines you remember editing.

13 | THE SAME REASONING APPLIES TO FLOWCHARTS

If given a flowchart instead of pseudocode, identify the same jobs. The positive-attendance decision must be reached only through the accepted-input path. Its Yes branch updates the count, and both branches rejoin before the outer loop advances.

After the class-processing loop, a decision checks whether the count is positive. Only its Yes path reaches the division. The No path outputs the alternative message. Both paths then lead to the unchanged total-classification decision.

Follow every arrow for zero, positive and invalid inputs. An attractive new box is not a correct amendment if a branch bypasses it or reaches it at the wrong stage.

Use the representation requested by the question. A written description of a change may help your planning, but does not replace a complete amended algorithm when one is required.

14 | EXPLAIN WHY YOUR CHANGES WORK

A clear explanation links placement and effect: “The count is updated after validation because only accepted values should represent a class. It increases by one when attendance is positive, therefore it counts participating classes rather than students.”

For the calculation: “The mean is calculated after all four classes have been processed. Division happens only if the participating count is positive, preventing division by zero and allowing the required alternative output.”

Your final check has three questions: does the amendment meet every new requirement, does the original required behaviour still work, and is the final algorithm complete and precise?

You do not need to guess everything at once. Read, plan, amend, trace and test. Each stage gives you evidence for the next.

MATCH THE CHECK OR AMENDMENT TO ITS PURPOSE

Terminology

Terminology

Amendment

A change to an algorithm to meet revised requirements.

Correction

A change that fixes an error against existing requirements.

Requirement

A behaviour or rule the solution must satisfy.

Change plan

A map from new requirements to necessary algorithm changes.

Initialisation

Assigning a starting value before use.

Loop counter

A value controlling count-based repetition.

Conditional count

A count increased only when a stated condition holds.

Accepted input

An input that passes the checks applied before processing.

Running total

The sum accumulated from values processed so far.

Denominator

The quantity by which another is divided.

Mean

A total divided by the number of values contributing to it.

Zero guard

A condition that prevents an operation such as division by zero.

REAL

A type representing numbers that may have fractional parts.

Dry run

Following algorithm instructions by hand with chosen inputs.

Expected result

The behaviour predicted from the requirements before a test.

Actual result

The behaviour observed when an implementation is tested.

Regression testing

Retesting retained behaviour after a change.

Requirement coverage

Checking that all stated requirements are addressed.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which requirements change in the worked example?
2. For zero, twelve, zero and eighteen, which are correct?
3. Where should the new count update happen?
4. What is the requested mean for zero, twelve, zero and eighteen?
5. What should happen with four zeros?
6. Which inputs test a fractional mean?
7. Which statement preserves the original classification rule?
8. Which checking actions are useful?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Describe a method for amending a complete algorithm.

2. Explain why the participating count is different from ClassIndex.

3. Explain why counting must follow validation.

4. Calculate the outputs for inputs zero, twelve, zero and eighteen.

5. Explain why the average must be guarded.

6. Suggest a test that exposes dividing by four.

7. Explain how the old twelve, eighteen, thirty test should be adapted.

8. Describe regression tests for retained behaviour.

AMEND IT | A SHOP SUMMARY

An existing algorithm receives three non-negative whole-number prices and outputs their total. Amend it to receive four prices, retry negative attempts, count prices greater than zero, and output the mean of positive prices. If none are positive, output No positive prices. Keep the total output. Assume whole-number inputs. Plan the changes before revealing the solution, then trace attempts minus two, three, zero, five and zero.

Reveal one possible complete solution
DECLARE Price : INTEGER
DECLARE ItemIndex : INTEGER
DECLARE Total : INTEGER
DECLARE PositiveCount : INTEGER
DECLARE Average : REAL
Total ← 0
PositiveCount ← 0
FOR ItemIndex ← 1 TO 4
    REPEAT
        OUTPUT "Enter a non-negative price"
        INPUT Price
    UNTIL Price >= 0
    Total ← Total + Price
    IF Price > 0
      THEN
        PositiveCount ← PositiveCount + 1
    ENDIF
NEXT ItemIndex
OUTPUT "Total: ", Total
OUTPUT "Positive prices: ", PositiveCount
IF PositiveCount > 0
  THEN
    Average ← Total / PositiveCount
    OUTPUT "Mean positive price: ", Average
  ELSE
    OUTPUT "No positive prices"
ENDIF

Minus two is retried for the first item. Accepted values are three, zero, five and zero. Total is eight, positive count two and mean four. Test four zeros for the alternative, and one, two, zero, zero for a fractional mean of one point five. In a different scenario allowing fractional prices, Price and Total would need an appropriate numeric type.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

    Selections are kept while this page is open.

    Workbook

    Workbook

    COMING SOON

    The workbook for 7.9.2 Amend and Check a Complete Algorithm is coming soon. Complete the matching task and written questions in your exercise book.