YOUR TOPIC 8 REVISION ROUTE
This topic connects many ideas. Work through one group at a time, then practise using them together. Understanding individual keywords is useful, but you must also explain what changes, which instructions execute and why the final result follows.
Use Revise for explanations and worked examples. In Flashcards, answer before revealing, filter a section and select uncertain cards. Copy your revision list to plan the lessons to revisit. The workbook is coming soon.
8.1 | VARIABLES, CONSTANTS AND ASSIGNMENT
A variable is a named storage location whose value can change during execution. A constant names a value fixed during that run. Its definition can be edited before a later run when a rule changes.
Declaration introduces a variable and its type; initialisation gives it a starting value. Do not assume a numeric declaration automatically stores zero.
CONSTANT PointsPerAnswer ← 5 DECLARE Score : INTEGER Score ← 0 Score ← Score + PointsPerAnswer OUTPUT Score
The output is five. Assignment evaluates the right-hand side using current values, then stores the result on the left. It is an action, not a mathematical equality.
A value copy is not a live link. After SavedScore ← Score followed by Score ← Score + 5, SavedScore keeps the earlier value. Changing an input variable does not recalculate a previously assigned total unless another calculation executes.
8.1 | CHOOSE TYPES AND DISTINGUISH INPUT FROM OUTPUT
The type should suit the information’s role, not just how it looks. A student code “0072” should usually be STRING so leading zeros remain part of its identity. A count is INTEGER; a fractional average is REAL.
| Type | Suitable value | Important distinction |
|---|---|---|
| INTEGER | -3, 0, 12 | Whole numbers; not only positive values |
| REAL | 2.5, -1.0 | Numeric values that can be fractional |
| CHAR | 'Y' | One character |
| STRING | "Maya", "", "0072" | Zero or more characters; one-character text may still be STRING |
| BOOLEAN | TRUE, FALSE | Not the quoted strings "TRUE" and "FALSE" |
INPUT receives a value into a destination. OUTPUT displays an expression. OUTPUT "Score" prints the word; OUTPUT Score prints its current value. A prompt is output, and the response is input. Neither input nor a declared type automatically proves all application checks have passed.
8.1 | SELECTION AND NESTED SELECTION
IF evaluates a BOOLEAN condition. TRUE chooses THEN; FALSE chooses ELSE when present. After ENDIF, execution continues with the common following instructions.
CASE compares one selector with listed values and chooses the matching branch; OTHERWISE supplies a default. Use it for discrete alternatives such as menu values. IF is usually clearer for ranges or combined conditions.
IF Score >= 80
THEN
OUTPUT "Distinction"
ELSE
IF Score >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Not a pass"
ENDIF
ENDIFAssume a valid INTEGER score from zero to one hundred. Eighty takes the outer TRUE route and skips the inner test. Seventy-nine takes outer FALSE then inner TRUE. Two separate independent IFs could both run at eighty; nesting here selects one category.
| Score | Outer test | Inner test | Output |
|---|---|---|---|
| 49 | FALSE | FALSE | Not a pass |
| 50 | FALSE | TRUE | Pass |
| 79 | FALSE | TRUE | Pass |
| 80 | TRUE | Not tested | Distinction |
Match each ELSE and ENDIF to its own IF. An inner FALSE result does not change the already chosen outer branch.
8.1 | CHOOSE THE LOOP BY ITS CONTROL
A loop body is the instruction group repeated. One body execution is an iteration. Choose a loop from what determines the repetitions, not from a memorised keyword.
| Loop | Condition behaviour | Minimum body executions | Good fit |
|---|---|---|---|
| FOR | Counter follows a specified sequence | Can be zero for incompatible bounds | A known number of readings |
| WHILE | Check before body; TRUE continues | Zero | Process items while any remain |
| REPEAT UNTIL | Check after body; TRUE stops | One | Request an input at least once, retry if invalid |
FOR Number ← 1 TO 5 STEP 2 OUTPUT Number NEXT Number
The outputs are one, three and five. A default ascending FOR from five to three executes no body iterations. Do not rely on an unspecified post-loop counter value.
WHILE needs a valid starting state before its first check and a route that can make its continuation condition FALSE. REPEAT needs a route that makes its stopping condition TRUE. Without progress, either can loop indefinitely.
8.1 | COMPARE WHILE AND REPEAT TRACES
Assume Count is declared INTEGER. Compare these two bodies starting with Count equal to four. The WHILE condition is already FALSE, so it outputs nothing. REPEAT outputs four once, increases Count to five and then stops.
Count ← 4 WHILE Count <= 3 DO OUTPUT Count Count ← Count + 1 ENDWHILE Count ← 4 REPEAT OUTPUT Count Count ← Count + 1 UNTIL Count > 3
For range validation, WHILE usually repeats while invalid: (Value < 0) OR (Value > 10). REPEAT stops when valid: (Value >= 0) AND (Value <= 10). The check position and condition meaning must both match the task.
8.1 | TOTALS, COUNTS AND CONDITIONAL MEANS
Use Total ← Total + Value because you want to keep the total so far and add the new value. Assigning only Value would replace the total and lose earlier contributions. Initialise Total once before the repeated additions.
A count adds one per relevant item; a total adds its amount. For scores four, five, eight, two and five, scores at least five have total eighteen and count three. Their mean is six.
Total ← 0
Count ← 0
FOR Position ← 1 TO 5
IF Scores[Position] >= 5
THEN
Total ← Total + Scores[Position]
Count ← Count + 1
ENDIF
NEXT Position
IF Count > 0
THEN
Average ← Total / Count
ELSE
OUTPUT "No qualifying scores"
ENDIFThis fragment assumes an assigned INTEGER array, INTEGER counters and totals, and REAL Average. The guard prevents division by zero. Do not read Average on the no-qualifying-values route, where no average has been calculated.
8.1 | NESTED ITERATION AND RETRIES
Two rows each containing three seats give six inner-body executions. The inner counter runs through all three values for each outer iteration, then starts at its lower bound again when reached for the next row.
| Visit | Row | Seat |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 3 |
Multiplication works when each outer iteration has the same known inner count. An input retry may take a different number of attempts each time. Three accepted scores could require five INPUT executions.
Place a per-player total reset inside the outer player loop, before the inner attempts. Place a grand-total reset before the outer loop. Use distinct active counters; do not let an inner loop overwrite the outer counter’s control.
8.1 | ARITHMETIC, DIV AND MOD
Multiplication and division have higher precedence than addition and subtraction. Two plus three times four gives fourteen; (two plus three) times four gives twenty. Use parentheses to show the intended grouping.
Cambridge DIV and MOD use function notation with INTEGER arguments. For the grouping examples below, Amount is non-negative and Size positive. DIV counts complete groups; MOD finds leftovers. Ordinary / may give a fractional value.
| Expression | Result | Meaning |
|---|---|---|
| 17 / 5 | 3.4 | Ordinary division |
| DIV(17, 5) | 3 | Complete groups |
| MOD(17, 5) | 2 | Leftover amount |
| DIV(19, 5) | 3 | Discard fractional part; do not round up |
Seventeen capacity-five items need four boxes: three full groups plus one for leftovers. Twenty need four, not five. Check the remainder before adding the extra box. Guard against a zero divisor before calling either routine.
8.1 | RELATIONAL AND LOGICAL CONDITIONS
Relational operators compare values and return BOOLEAN: =, <>, <, <=, > and >=. Assignment ← changes a value; equality = tests one.
AND needs both Boolean operands TRUE. OR needs at least one, including both. NOT reverses one Boolean result without automatically changing the stored operand.
| A | B | A AND B | A OR B |
|---|---|---|---|
| FALSE | FALSE | FALSE | FALSE |
| FALSE | TRUE | FALSE | TRUE |
| TRUE | FALSE | FALSE | TRUE |
| TRUE | TRUE | TRUE | TRUE |
Inside range zero to one hundred: (Score >= 0) AND (Score <= 100). Outside: (Score < 0) OR (Score > 100). Check endpoints explicitly.
(Paid OR FreeEntry) AND SpaceAvailable requires space for either entry route. Paid OR (FreeEntry AND SpaceAvailable) permits payment alone. Parentheses can change the rule, not just the appearance.
8.1 | STRING LENGTH, SUBSTRINGS AND CASE
STRING is ordered character data. LENGTH returns its character count, including spaces. Quote marks delimit the value and are not part of it. An empty STRING has length zero; one space has length one.
| Expression using "Happy Days" | Result |
|---|---|
| LENGTH("Happy Days") | 10 |
| SUBSTRING("Happy Days", 7, 4) | "Days" |
| SUBSTRING("Happy Days", 5, 3) | "y D" |
| UCASE("Happy Days") | "HAPPY DAYS" |
| LCASE("Happy Days") | "happy days" |
SUBSTRING(Text, Start, Length) uses a starting position and number of characters, not an ending position. A positive extraction must stay within the source: last position is Start + Length - 1.
UCASE and LCASE return converted values. OUTPUT UCASE(Text) does not replace Text; Text ← UCASE(Text) does. Case-insensitive data comparison can normalise both operands. Removing case differences does not remove unwanted spaces or validate a code.
8.1 | ROUND AND RANDOM LIBRARY ROUTINES
Library routines are predefined tasks. ROUND(Value, Places) returns a REAL value or expression rounded to an INTEGER number of decimal places. ROUND(3.456, 2) gives 3.46; rounding does not guarantee displayed trailing zeros.
Cambridge RANDOM() returns a random number between zero and one inclusive. Its empty parentheses are part of the specified notation. Store one draw when several instructions need the same value.
| Hypothetical Draw | Draw * 6 | ROUND(Draw * 6, 0) |
|---|---|---|
| 0 | 0 | 0 |
| 0.23 | 1.38 | 1 |
| 0.81 | 4.86 | 5 |
| 1 | 6 | 6 |
ROUND(RANDOM() * 6, 0) has possible whole-number values zero through six. It is not a fair six-sided die: zero is possible, and under a uniform real draw the endpoint rounding regions are narrower than the interior ones. The syllabus does not specify exact-half ROUND tie behaviour; avoid assuming all languages use the same convention.
8.1 | PROCEDURES, FUNCTIONS AND PARAMETERS
A procedure performs a task without returning a value to replace its call in an expression. A function returns one value to its caller. Both may have parameters; the syllabus allows up to three.
A definition describes the routine. A call executes its body. Parameters are named items in the definition; arguments are the values or expressions supplied at the call. Match count, position and type.
PROCEDURE ShowResult(Points : INTEGER) OUTPUT "Points: ", Points ENDPROCEDURE FUNCTION AddBonus(Score : INTEGER, Bonus : INTEGER) RETURNS INTEGER RETURN Score + Bonus ENDFUNCTION DECLARE FinalScore : INTEGER FinalScore ← AddBonus(12, 5) CALL ShowResult(FinalScore)
AddBonus returns seventeen; the caller stores it and supplies it to ShowResult, which displays it. RETURN and OUTPUT are different. RETURNS states the result type in the header; RETURN supplies the actual value and ends that function execution.
Use CALL for a procedure. A function belongs in an expression without CALL. Ensure every possible function route returns a suitable value. RETURN inside a loop leaves the function early, so a full total usually returns after the loop finishes.
8.1 | SCOPE AND MAINTAINABLE CODE
Scope is where a declared name can refer to its variable. A local variable is declared inside a routine; its name belongs to that routine. A global variable is declared at program level and is available across the program.
Returning a local Total sends its value to the caller, not its local name. Local variables still need explicit starting values. Shared global state can be useful but creates dependencies and possible unexpected updates. Explicit parameters and results make data flow easier to inspect.
Use meaningful identifiers for variables, constants, arrays and routines. Cambridge uses Pascal case, letters and digits, a capital-letter start and no underscores or reserved keywords. Case differences do not create separate identifiers.
Comments begin with // and continue to line end; each multi-line comment line needs its own marker. Explain a relevant assumption or reason, keep the note accurate, and remember comments do not execute checks. Clear tasks in procedures and functions reduce duplicated logic. A tidy rewrite still needs behaviour checks.
8.2 | ARRAY DECLARATIONS, INDICES AND VALUES
An array has a fixed number of same-type elements selected by consecutive indices. The index identifies a position; the element value is the data stored there.
DECLARE Scores : ARRAY[1:5] OF INTEGER DECLARE Grid : ARRAY[1:3, 1:4] OF INTEGER
Scores has five elements. Grid has three times four, or twelve. A dimension’s length is upper minus lower plus one, so [3:7] also contains five positions. Read the actual lower bound; zero-based arrays are permitted.
Declaration does not initialise every cell. Scores[3] ← 12 assigns twelve to one element. If Position is two, Scores[Position + 1] reads index three; Scores[Position] + 1 reads index two then adds one to its value.
Check the evaluated index before access, not just part of its expression. In 2D, both indices must meet their own bounds. ScoresGrid[Student, Test] and ScoresGrid[Test, Student] do not have interchangeable meanings.
8.2 | ONE-DIMENSIONAL LOOP PROCESSING
A FOR counter can supply each valid index. INPUT writes an element; OUTPUT reads it; an assignment targeting the element updates it. A copied numeric value does not follow later changes to its source.
DECLARE Scores : ARRAY[1:5] OF INTEGER DECLARE Position : INTEGER DECLARE Total : INTEGER FOR Position ← 1 TO 5 INPUT Scores[Position] NEXT Position Total ← 0 FOR Position ← 1 TO 5 Total ← Total + Scores[Position] NEXT Position OUTPUT Total
Assume valid INTEGER inputs. For eight, five, twelve, seven and nine, Total becomes eight, thirteen, twenty-five, thirty-two and forty-one. Keep the total so far and add the next score. The second loop reads the array without changing its elements.
A loop ending at four misses the final element; ending at six exceeds the bounds. Input retries may use an inner REPEAT so the outer counter advances only after acceptance.
8.2 | TWO-DIMENSIONAL LOOPS AND TOTALS
Let Student select rows one through three and Test select columns one through four. A row-first traversal finishes four columns before advancing the row.
GrandTotal ← 0
FOR Student ← 1 TO 3
StudentTotal ← 0
FOR Test ← 1 TO 4
StudentTotal ← StudentTotal + ScoresGrid[Student, Test]
NEXT Test
OUTPUT StudentTotal
GrandTotal ← GrandTotal + StudentTotal
NEXT Student
OUTPUT GrandTotalThis fragment assumes declared INTEGER counters and totals and a fully initialised grid. For rows (8,6,7,5), (4,10,9,6), (7,5,8,10), row totals are twenty-six, twenty-nine and thirty, with grand total eighty-five.
Reset StudentTotal once per row, before the inner loop. Reset GrandTotal once before the outer loop. Adding every score directly to GrandTotal as well as adding each row total would double-count.
Column-first traversal can use Test as the outer loop while keeping access order [Student, Test]. Different loop order does not redefine the array dimensions.
8.3 | PERSISTENCE AND FILE ACCESS
Working variables belong to the current program run. Data files on non-volatile storage can retain information for later use. Displaying or assigning a value does not save it.
Loading reads saved data into working values. Saving writes working data to storage. A changed variable does not automatically change the file. Files can still be lost, overwritten or corrupted, so persistence is not a backup guarantee.
| Cambridge operation | Purpose | Important condition |
|---|---|---|
| OPENFILE "Names.txt" FOR READ | Prepare existing file for reading | Assume it exists and is accessible |
| READFILE "Names.txt", Name | Read next data item into destination | File opened for READ; next item available |
| OPENFILE "Copy.txt" FOR WRITE | Start replacement output | Existing destination data is lost |
| WRITEFILE "Copy.txt", Name | Write current source value | File opened for WRITE; source assigned |
| CLOSEFILE "Copy.txt" | Finish file access | Close when the intended operations finish |
READFILE assigns; OUTPUT displays. WRITEFILE writes; OUTPUT does not. Closing leaves already-read working values available and does not delete the saved file.
8.3 | TRACE READING AND WRITING
Suppose Names.txt contains Maya, Leo and Aisha, one item per line. Successive reads into Name produce those values in order. Each read advances the read position and replaces the previous Name value, while the source file stays unchanged.
DECLARE Name : STRING DECLARE Position : INTEGER OPENFILE "Names.txt" FOR READ OPENFILE "Copy.txt" FOR WRITE FOR Position ← 1 TO 3 READFILE "Names.txt", Name WRITEFILE "Copy.txt", Name NEXT Position CLOSEFILE "Names.txt" CLOSEFILE "Copy.txt"
This copies exactly three data items into the agreed one-name-per-line format. It assumes exactly three source lines and successful operations. Unknown-length files need an appropriate end-of-file strategy; a fourth read here has no next name.
Open once outside the writing loop. Reopening FOR WRITE on every iteration would replace earlier saved items and leave only the last session’s output. Use different source and destination filenames. A text format must be agreed by writer and reader; a blank line is not automatically end of file.
COMMON MISTAKES | CHECK YOUR THINKING
- Assuming declarations initialise variables or array elements.
- Treating assignment as equality, or copied values as live links.
- Forgetting the loop body’s meaning or reversing WHILE and UNTIL conditions.
- Resetting a total inside the wrong loop or dividing by a zero count.
- Using OR for an inside-range condition or excluding an intended endpoint.
- Confusing substring length with an ending position.
- Using CALL for a function, or OUTPUT instead of RETURN.
- Assuming a local variable becomes global when returned.
- Adding indices instead of stored values or checking the wrong index expression.
- Swapping row and column roles or resetting a grand total per row.
- Assuming WRITE appends, or reopening it inside a saving loop.
- Assuming a displayed value proves a successful save.
PRACTISE EXPLAINING AND CONNECTING
Explain makes reasons and relationships clear: “The total is initialised before the loop because earlier values must remain in the sum, therefore each addition builds on the previous total.” Compare identifies similarities and differences: both routines can have parameters, but only the function returns a value for an expression.
Try a combined problem: receive four valid readings, store them in an array, calculate a mean with a function and save the readings. Identify types, bounds, retry placement, result type and file mode before writing.
Revision plan: session one covers variables and control; session two covers operators, strings and routines; session three covers arrays and files. Recreate worked traces without looking, then select weak flashcards and revisit their linked lessons.
End of topic review