Choose loops and validate input
Match the loop to the requirement
Use FOR for a known number of accepted items, WHILE when zero iterations are possible, and REPEAT when reading at least once is required. A sentinel marks the end of input; it is not ordinary data.
Separate attempts from accepted items
To read three valid scores: the outer loop counts accepted scores; the inner REPEAT handles attempts for one score. Add to Total only after validation succeeds.
DECLARE Score, Total, I : INTEGER
Total ← 0
FOR I ← 1 TO 3
Score ← I * 2
Total ← Total + Score
NEXT I
OUTPUT Total
This fixed-data version gives 12. Replacing the assignment with a validation loop should not change where the total is updated.
Test the decisions
For the inclusive interval 0 to 20 use -1, 0, 20 and 21 as boundary tests. An invalid attempt must neither increase the accepted-item count nor contribute to the total. Explain why UNTIL uses the valid condition, rather than the invalid condition.
A system must read at least one value and repeat until it is valid. Which loop most directly expresses this: FOR, WHILE or REPEAT?
Read integers until one is 1 to 9 inclusive. Output only the accepted value.
Haz clic en Ejecutar para ver la salida aquí.
Read N (1 to 5). For EACH score, read repeatedly until it is 0 to 20 inclusive. Output the total of the N accepted scores. Do not count invalid attempts.
Haz clic en Ejecutar para ver la salida aquí.
Explain your choice of data structure and loop. Identify one boundary case and predict its result. For a subroutine, explain what is returned or changed in the caller.
Saved for this sitting on this browser. Review this yourself or with your teacher; these explanations are not automatically marked.
Review your explanation against these criteria
- My types and data structure match the data and the question.
- I justified the loop and checked its first and last iterations.
- Initial values and rejected operations preserve the intended state.
- My test includes input, purpose and expected result.
- I distinguished returning a value from printing and changing caller state.