Skip to content

9618 · Unit 11 · Paper 2: Problem-solving and programming

Programming.

9618 · Unit 11 · Programming
Revisionbyexamplicity

Variables, constants and data types

§11.1 · Programming basics · declarations and constants

A ticket program has to remember how many tickets someone wants and what each one costs. The number wanted can change while the program runs, so it is a variable, a named memory location. The price never should, so it is a constant, a named value that cannot change during execution.

Declare, initialise, use

Follow Wanted from its DECLARE to the last OUTPUT: it is input, cut down to MaxTickets if it is too big, then used to work out Cost.

Pseudocodeinput 9 → 6 tickets cost $43.5
CONSTANT MaxTickets = 6
CONSTANT Price = 7.25
DECLARE Wanted : INTEGER
DECLARE Cost : REAL
OUTPUT "How many tickets?"
INPUT Wanted
IF Wanted > MaxTickets THEN
Wanted ← MaxTickets
ENDIF
Cost ← Wanted * Price
OUTPUT Wanted, " tickets cost $", Cost

Two kinds of declaration

DECLARE <identifier> : <data type>

  • Several of one type: DECLARE Total, Count : INTEGER.
  • A declaration gives no value: initialise the variable before it is read.

CONSTANT <identifier> = <value>

  • Uses =, not ←.
  • The value is a literal, never a variable, constant or expression: CONSTANT Rate = 0.2 is valid, CONSTANT Rate = Price / 5 is not.

Data types and their literals

The way a value is written shows its type: quotes for text, a point for a REAL. Choose the type, then write the literal.

INTEGERREALCHARSTRINGBOOLEANDATE
Holdsa whole numbera number with a fractional partexactly one characterzero or more charactersa logical valuea calendar date
Literals25 -34.7 0.0'x' ' '"Hall 2" ""TRUE FALSE02/01/2025
TypeHoldsLiterals
INTEGERa whole number25 -3
REALa number with a fractional part4.7 0.0
CHARexactly one character'x' ' '
STRINGzero or more characters"Hall 2" ""
BOOLEANa logical valueTRUE FALSE
DATEa calendar date02/01/2025

A REAL literal has a digit on each side of the point (0.5, not .5); "" is the empty STRING.

Two habits that make a program easier to read and to change later:

Why use a constant?

  • The value cannot be changed by mistake while the program runs.
  • It is written once, so it cannot differ between two places. A change needs one statement only.
  • The name shows what the value means: easier to understand.

Identifiers

  • Letters, digits and _, starting with a letter: NumberOfSeats. Spell it the same way each time; never use a keyword.
  • Meaningful: A or X2 hide the purpose, so the program is harder to understand, debug and maintain.
Your turn

1 Write a statement that makes MaxSeats a constant with the value 40.

2 Choose a data type for: the price of a ticket; one grade letter; whether a seat is booked.

3 The program above is run and 4 is input. What is output?

  1. 1
    CONSTANT MaxSeats = 40
  2. 2
    REAL; CHAR; BOOLEAN
  3. 3
    How many tickets?, then 4 tickets cost $29.0
Tick what you can do now
Exam focusWhen declarations are required, give each variable a suitable type. Initialise counters and totals before the loop that changes them. A constant takes = and a literal: CONSTANT MaxTickets = 6.
Practise with s24/21 Q1(a), (c)(i), (c)(ii), (c)(iii); s25/21 Q2(b)(i), (b)(ii); w24/23 Q2(a)
1 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Assignment, input and output

§11.1 · Programming basics · assignment, input and output

In maths, X = X + 1 is impossible. In a program, X ← X + 1 is one of the commonest lines, because assignment (←) evaluates the right-hand side first, then stores the result on the left.

Follow the three steps: the right-hand side is worked out from the stored values first, and only then is Total replaced.

Total ← Total + Price1Read the stored valuesTotal40Price152Evaluate the right-hand side40 + 15 = 553Store it in the variable on the leftTotal5540replaced
Total ← Total + Price1 Read the old valuesTotal = 40Price = 152 Evaluate: 40 + 15 = 553 Store: Total = 55Old Total 40 is replaced; Price stays 15.

Trace a sequence of assignments

A variable holds only its latest value, so the order of the statements matters. Give the value of each variable after every statement.

Pseudocode
X ← 4
Y ← X * 3
X ← Y - X
Y ← Y + X
OUTPUT X, " ", Y
Swap two valuesFirst "Ann", Second "Bo"
Temp ← First
First ← Second
Second ← Temp
StatementXYOutput
X ← 44
Y ← X * 312
X ← Y - X8
Y ← Y + X20
OUTPUT X, " ", Y8 20

Temp keeps the old value of First. Without it, First ← Second overwrites "Ann" and both variables end as "Bo".

Pseudocode
X ← 4
Y ← X * 3
X ← Y - X
Y ← Y + X
OUTPUT X, " ", Y
Swap two valuesFirst "Ann", Second "Bo"
Temp ← First
First ← Second
Second ← Temp
  • Temp keeps the old value of First.
  • Without it, First ← Second overwrites "Ann" and both variables end as "Bo".
Run it line by line
Each statement is a row. Its value goes in the column of the variable it changes.
LineStatement that runsXYOutputWritesWhat happens
1X ← 44X 4store 4 in X
store 4 in X
2Y ← X * 312Y 124 × 3 = 12: X is read, not changed
4 × 3 = 12: X is read, not changed
3X ← Y - X8X 812 − 4 = 8: the old X is used, then replaced
12 − 4 = 8: the old X is used, then replaced
4Y ← Y + X20Y 2012 + 8 = 20: the new X is used
12 + 8 = 20: the new X is used
5OUTPUT X, " ", Y8 20Output 8 20X, a space, then Y
X, a space, then Y

Keyboard input and console output

Run it with 6 and 4 typed in: each prompt appears just before the INPUT that waits for it.

Pseudocode
DECLARE RoomLength, RoomWidth : INTEGER
DECLARE Area, Fence : INTEGER
OUTPUT "Enter the length in metres"
INPUT RoomLength
OUTPUT "Enter the width in metres"
INPUT RoomWidth
Area ← RoomLength * RoomWidth
Fence ← 2 * (RoomLength + RoomWidth)
OUTPUT "Area: ", Area, " square metres"
OUTPUT "Fence: " & NUM_TO_STR(Fence) & " m"
Outputinputs 6, 4
Enter the length in metres
Enter the width in metres
Area: 24 square metres
Fence: 20 m
  • When a prompt is requested, OUTPUT its message before INPUT.
  • Commas separate the values in one OUTPUT. & joins strings only: "Fence: " & Fence is a type error, so use NUM_TO_STR(Fence).
Your turn

1 A ← 5, then B ← A + 2, then A ← B * A. What are A and B now?

2 Write three statements that swap the values of Left and Right, using Temp.

3 Why is Total + Price ← Total not a valid assignment?

  1. 1
    A = 35, B = 7
  2. 2
    Temp ← Left, Left ← Right, Right ← Temp
  3. 3
    the left-hand side must be one variable: the value is stored there
Tick what you can do now
Exam focus← assigns and = compares: IF Reply ← "Y" THEN is an error. When a prompt is required, use an OUTPUT message before INPUT into the variable.
Practise with s26/21 Q5(b); w22/21 Q1(c) (older paper: assignment/type errors)
2 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Arithmetic expressions

§11.1 · Programming basics · arithmetic operators

7 / 2 gives 3.5, but 7 DIV 2 gives 3: the operator matters as much as the numbers. An expression evaluates to a single value, and its operators decide that value's data type.

Arithmetic operators

Read across each row. The dots show 17 DIV 5 and 17 MOD 5 at once: three full rows of five, two left over.

OperatorMeaningExample
+ - *add, subtract, multiply17 * 5 → 85
/divide: always gives a REAL17 / 5 → 3.4; 10 / 5 → 2.0
DIVwhole-number quotient17 DIV 5 → 3
MODremainder after division17 MOD 5 → 2

* and / come before + and -: 4 + 3 * 2 is 10, (4 + 3) * 2 is 14. Use brackets when in doubt, for example with DIV and MOD.

17 DIV 5 = 33 full rows of 517 MOD 5 = 22 left overcheck: 5 × 3 + 2 = 17

Patterns built with DIV and MOD

DIV and MOD can take a number apart, for example into whole weeks and spare days. Write each expression and work out its value for a given number.

TaskExpressionExample
is N even?N MOD 2 = 064 → TRUE
last digit; the restN MOD 10; N DIV 104721 → 1; 472
hours and minutesT DIV 60; T MOD 60135 → 2 h 15 min
containers needed(Items + Size - 1) DIV Size130, 52 → 3

Is N even?

Test N MOD 2 = 0.

Working
64 MOD 2 = 0 → TRUE

Last digit and the rest

Use N MOD 10 and N DIV 10.

Working
4721 MOD 10 = 1
4721 DIV 10 = 472

Hours and minutes

Use T DIV 60 and T MOD 60.

Working
135 DIV 60 = 2 hours
135 MOD 60 = 15 minutes

Containers needed

For non-negative whole items and a positive capacity, round up with (Items + Size - 1) DIV Size.

Working
(130 + 52 - 1) DIV 52 = 3

The data type of an expression

Total is INTEGER 12, Name is a STRING and Done is BOOLEAN. Look at the operator or function first: it decides the type.

ExpressionData typeWhy
Total * 2INTEGERinteger × integer (REAL if Total is REAL)
Total / 4REAL/ always gives a REAL: 3.0
LEFT(Name, 1)STRINGLEFT returns a STRING (CHAR accepted for one character)
"FALSE"STRINGanything in double quotes is text
Total > 10 AND NOT DoneBOOLEANcomparisons and logic operators give TRUE or FALSE
Your turn

1 Give the values of 23 DIV 4 and 23 MOD 4.

2 Days is an INTEGER. Write an expression for the number of whole weeks in Days.

3 Count is INTEGER 9. Give the value and data type of Count / 2.

  1. 1
    5 and 3
  2. 2
    Days DIV 7 (for 23 days: 3)
  3. 3
    4.5, REAL: / always gives a REAL
Tick what you can do now
Exam focusFor a data type, look at what the expression returns: / always gives a REAL, a comparison gives a BOOLEAN, anything in double quotes is a STRING. Use DIV and MOD for whole numbers and remainders.
Practise with s24/21 Q1(a); s25/22 Q1(c); s26/21 Q5(a); w25/22 Q1(c)
3 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Boolean expressions

§11.1 · Programming basics · relational and logical operators

Behind every decision a program makes is a test that is either passed or failed. A condition evaluates to TRUE or FALSE, and it controls IF, CASE and conditional loops.

Relational and logical operators

= <> < > <= >= compare two values of the same type and give a BOOLEAN.

ABA AND BA OR BNOT A
FALSEFALSEFALSEFALSETRUE
FALSETRUEFALSETRUETRUE
TRUEFALSEFALSETRUEFALSE
TRUETRUETRUETRUEFALSE

With Score ← 64, Member ← TRUE and Late ← FALSE:

ExpressionValue
(Score > 50) AND NOT LateTRUE
(Score MOD 2 = 0) OR LateTRUE
Member AND (Score >= 70 OR Late)FALSE
NOT (Member OR Late)FALSE
NOT Member OR (Score < 70 AND NOT Late)TRUE

Inside a range use AND; outside it use OR

Run four ages through both conditions. On every row the two columns disagree: each condition is the NOT of the other.

Age(Age >= 13) AND (Age <= 19)(Age < 13) OR (Age > 19)
12FALSETRUE
13TRUEFALSE
19TRUEFALSE
20FALSETRUE
Inside 13–19
(Age >= 13) AND (Age <= 19)
Outside 13–19
(Age < 13) OR (Age > 19)
AgeInsideOutside
12FALSETRUE
13TRUEFALSE
19TRUEFALSE
20FALSETRUE

Write it precisely

IF X = 3 OR 4 THEN is an error: 4 is not a Boolean. Write each comparison in full: IF (X = 3) OR (X = 4) THEN.

Simplify, and store, conditions

A shorter condition is easier to read and harder to get wrong. Rewrite it so it gives the same result for every value.

Written asSimpler, same resultReason
NOT ((Ch < 'a') OR (Ch > 'z'))(Ch >= 'a') AND (Ch <= 'z')NOT of an OR: AND the opposites
NOT (Dots >= 1 AND Ats = 1)(Dots < 1) OR (Ats <> 1)NOT of an AND: OR the opposites
(Ready OR NOT Ready) AND NOT LockedNOT LockedReady OR NOT Ready is always TRUE
CanBook is TRUE only when SeatsFree and Paid are both TRUECanBook ← SeatsFree AND Paida condition is a value: assign it

Equivalent condition

Original
NOT ((Ch < 'a') OR (Ch > 'z'))
Same result
(Ch >= 'a') AND (Ch <= 'z')

NOT of an OR: AND the opposites

Equivalent condition

Original
NOT (Dots >= 1 AND Ats = 1)
Same result
(Dots < 1) OR (Ats <> 1)

NOT of an AND: OR the opposites

Equivalent condition

Original
(Ready OR NOT Ready) AND NOT Locked
Same result
NOT Locked

Ready OR NOT Ready is always TRUE

Store the condition

CanBook is TRUE only when SeatsFree and Paid are both TRUE

Same result
CanBook ← SeatsFree AND Paid

a condition is a value: assign it

Your turn

1 Score ← 45, Member ← FALSE, Late ← TRUE. Evaluate (Score > 50) OR Late.

2 With the same values, evaluate NOT Member AND (Score >= 40).

3 Write a condition that is TRUE when Age is outside 18 to 65.

  1. 1
    TRUE
  2. 2
    TRUE
  3. 3
    (Age < 18) OR (Age > 65)
Tick what you can do now
Exam focusEvery operand of AND, OR and NOT must itself be a Boolean, and each value is TRUE or FALSE. String comparisons are case sensitive: "Yes" = "YES" is FALSE.
Practise with s24/21 Q1(b); s26/21 Q2(a)(ii), (a)(iii); s26/23 Q2(b); s23/21 Q1(c)(ii) (older paper: Boolean simplification)
4 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

String functions

§11.1 · Programming basics · built-in string functions

Programs often need part of a piece of text: the month from a booking code, or the initials from a name. String functions are always given in the insert: use each exactly as defined, with its parameters in order. Positions start at 1. The examples use Code ← "MAR-2026-X7".

Count the positions from 1, then read each bracket: LEFT takes from the start, RIGHT from the end and MID from a chosen position. The table gives each call with its value.

1M2A3R4-526072869-10X117positionLEFT(Code, 3)"MAR"MID(Code, 5, 4)"2026"RIGHT(Code, 2)"X7"LENGTH(Code) = 11
Code: positions start at 11M2A3R4-526072869-10X117LEFT(Code, 3)M1A2R3→ "MAR"MID(Code, 5, 4)25062768→ "2026"RIGHT(Code, 2)X10711→ "X7"LENGTH(Code) = 11
Insert functionReturnsExampleValue
LEFT(ThisString, x)STRING: leftmost x charactersLEFT(Code, 3)"MAR"
RIGHT(ThisString, x)STRING: rightmost x charactersRIGHT(Code, 2)"X7"
MID(ThisString, x, y)STRING: y characters from xMID(Code, 5, 4)"2026"
LENGTH(ThisString)INTEGER: number of charactersLENGTH(Code)11
TO_UPPER(x) TO_LOWER(x)the type of x: CHAR or STRINGTO_LOWER(LEFT(Code, 3))"mar"
& (operator)STRING: joins two strings"Ref " & RIGHT(Code, 2)"Ref X7"

LEFT(ThisString, x)

STRING: leftmost x characters

LEFT(Code, 3)

Result: "MAR"

RIGHT(ThisString, x)

STRING: rightmost x characters

RIGHT(Code, 2)

Result: "X7"

MID(ThisString, x, y)

STRING: y characters from x

MID(Code, 5, 4)

Result: "2026"

LENGTH(ThisString)

INTEGER: number of characters

LENGTH(Code)

Result: 11

TO_UPPER(x) TO_LOWER(x)

the type of x: CHAR or STRING

TO_LOWER(LEFT(Code, 3))

Result: "mar"

& (operator)

STRING: joins two strings

"Ref " & RIGHT(Code, 2)

Result: "Ref X7"

Work through a string one character at a time

Run it with "ada byron lovelace": a letter is added only where the character before it is a space.

Initials from a nameoutputs ABL
DECLARE Text, Initials : STRING
DECLARE Index : INTEGER
DECLARE Letter : CHAR
Text ← "ada byron lovelace"
Initials ← TO_UPPER(LEFT(Text, 1))
FOR Index ← 2 TO LENGTH(Text)
IF MID(Text, Index - 1, 1) = ' ' THEN
Letter ← MID(Text, Index, 1)
Initials ← Initials & TO_UPPER(Letter)
ENDIF
NEXT Index
OUTPUT Initials

MID(Text, Index, 1) picks out one character. A new word starts where the character before it is a space: positions 5 and 11 here. This example uses non-empty words separated by single spaces.

  1. 1
    MID(Text, Index, 1) picks out one character.
  2. 2
    A new word starts where the character before it is a space: positions 5 and 11.
  3. 3
    Words are non-empty and separated by single spaces.

Write it precisely

  • "37" + "5" is an error: + is arithmetic. "37" & "5" gives "375".
  • MID(Code, 10, 4) is an error: only 2 characters start at position 10.
  • Check the supplied case-conversion interface: some routines accept one CHAR. TO_UPPER() and TO_LOWER() here accept a CHAR or STRING.

Trace the loop

The loop looks at one character per pass. Write one row each time it runs.

Index 5, line by line
The pass where a letter is added: the blue row of the whole run below.
LineStatement that runsIndexLetterInitialsWritesWhat happens
6FOR Index ← 2 TO LENGTH(Text)5Index 5the next position
the next position
7IF MID(Text, Index - 1, 1) = ' ' THENtest MID(Text, 4, 1) is ' ': TRUE
test MID(Text, 4, 1) is ' ': TRUE
8Letter ← MID(Text, Index, 1)'b'Letter 'b'the character at position 5
the character at position 5
9Initials ← Initials & TO_UPPER(Letter)"AB"Initials "AB""A" & 'B'
"A" & 'B'

The whole run

IndexLetterInitialsWhat decided it
start"A"line 5: the first letter, in capitals
line 5: the first letter, in capitals
Index 2–42–4the character before is not a space: nothing added
the character before is not a space: nothing added
Index 55'b'"AB"position 4 is a space: add B
position 4 is a space: add B
Index 6–106–10the character before is not a space: nothing added
the character before is not a space: nothing added
Index 1111'l'"ABL"position 10 is a space: add L
position 10 is a space: add L
Index 12–1812–18the character before is not a space: nothing added
the character before is not a space: nothing added
endthe loop ends after Index 18: output ABL
the loop ends after Index 18: output ABL
Your turn

1 Ref ← "KL-0451-B". Give LEFT(Ref, 2), MID(Ref, 4, 4) and LENGTH(Ref).

2 The initials program runs with Text ← "sam lee". What is output?

3 Why is MID(Ref, 8, 3) an error?

  1. 1
    "KL", "0451", 9
  2. 2
    SL
  3. 3
    only 2 characters start at position 8, so there are not 3 to return
Tick what you can do now
Exam focusWrite a string result in double quotes with its exact case: LEFT(Code, 3) gives "MAR". Spell function names exactly as the insert does: TO_UPPER, not UPPER.
Practise with s24/21 Q1(b); s24/22 Q1(b); w25/21 Q1(a); s26/21 Q6(a)
5 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Conversion, numeric and random functions

§11.1 · Programming basics · built-in functions

A number typed in or read from a file arrives as text, and you cannot do sums with text. Conversion functions change a value's type; numeric functions work on numbers. All are in the insert.

Read each example across to its value, and note the type that comes back: it decides what you can do with the value next.

Insert functionReturnsExampleValue
NUM_TO_STR(x)STRING; x is INTEGER or REALNUM_TO_STR(87.5)"87.5"
STR_TO_NUM(x)INTEGER or REAL; x is a stringSTR_TO_NUM("2026") + 12027
IS_NUM(ThisString)BOOLEAN: is it a valid number?IS_NUM("-12.5"), IS_NUM("X7")TRUE, FALSE
ASC(ThisChar)INTEGER: the ASCII valueASC('A'), ASC('7')65, 55
CHR(x)CHAR with ASCII value xCHR(ASC('A') + 2)'C'
INT(x : REAL)INTEGER part, not roundedINT(9.99), INT(7 / 2)9, 3
RAND(x : INTEGER)REAL, 0 to x, not including xRAND(6)e.g. 4.307

NUM_TO_STR(x)

STRING; x is INTEGER or REAL

NUM_TO_STR(87.5)

Result: "87.5"

STR_TO_NUM(x)

INTEGER or REAL; x is a string

STR_TO_NUM("2026") + 1

Result: 2027

IS_NUM(ThisString)

BOOLEAN: is it a valid number?

IS_NUM("-12.5"), IS_NUM("X7")

Result: TRUE, FALSE

ASC(ThisChar)

INTEGER: the ASCII value

ASC('A'), ASC('7')

Result: 65, 55

CHR(x)

CHAR with ASCII value x

CHR(ASC('A') + 2)

Result: 'C'

INT(x : REAL)

INTEGER part, not rounded

INT(9.99), INT(7 / 2)

Result: 9, 3

RAND(x : INTEGER)

REAL, 0 to x, not including x

RAND(6)

Result: e.g. 4.307

A quoted digit is text: '7' + 1 is an error, but STR_TO_NUM("7") + 1 is 8.

Random whole numbers from RAND and INT

Games and simulations need whole numbers nobody can predict, such as a dice roll from 1 to 6. Follow r = 4.307 down the figure: INT drops the fraction to 4, then + 1 makes 5.

RAND(6)01234566 is neverreturnedINT → 0+1 → 1INT → 1+1 → 2INT → 2+1 → 3INT → 3+1 → 4INT → 4+1 → 5INT → 5+1 → 6r = 4.307INT(r)+ 1
RAND(6): 0 included, 6 excluded0123456r = 4.307INT(r): remove the fractional part011223344556Add 1: integers 1–6; this r gives 5.

Random whole numbers

INT(RAND(6)) + 11 to 6, like a diceLow + INT(RAND(High - Low + 1))Low to High inclusive10 + INT(RAND(11))10 to 20CHR(65 + INT(RAND(26)))a letter from 'A' to 'Z'INT(X + 0.5)X rounded to the nearest whole number (X ≥ 0)
Ten dice throws
DECLARE i, Roll, Sixes : INTEGER
Sixes ← 0
FOR i ← 1 TO 10
Roll ← INT(RAND(6)) + 1
IF Roll = 6 THEN
Sixes ← Sixes + 1
ENDIF
NEXT i
OUTPUT "Sixes thrown: ", Sixes
Your turn

1 Give the values of INT(7.8) and STR_TO_NUM("40") + 2.

2 What is the smallest and the largest value INT(RAND(10)) + 5 can give?

3 Write an expression for a random whole number from 1 to 50.

  1. 1
    7 and 42
  2. 2
    5 and 14: RAND(10) never reaches 10
  3. 3
    INT(RAND(50)) + 1
Tick what you can do now
Exam focusFor a random integer, combine both functions: INT(RAND(100)) + 1 gives 1 to 100 inclusive. RAND alone gives a REAL that never reaches its parameter, and INT truncates: it does not round.
Practise with s25/21 Q3; w24/23 Q1(c); s25/23 Q1(b); w25/22 Q1(c); w25/23 Q1(c)
6 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Library routines

§11.1 · Programming basics · library routines and the insert

Nobody needs to write their own code to cut up a string or round a number: someone already has, and tested it. A library routine is that kind of pre-written, pre-tested subroutine, and the insert describes each one.

A library routine is a pre-written, pre-tested subroutine; the insert describes each one.

Read an interface in order: the name, each parameter with its type, then the type it returns.

MID(ThisString : STRING, x : INTEGER, y : INTEGER) RETURNS STRINGnameparameters: identifiers, data types and orderreturn typereturns a string of length y starting at position x from ThisStringExample: MID("ABCDEFGH", 2, 3) returns "BCD"
Read the routine's interface
MID(ThisString : STRING,
x : INTEGER, y : INTEGER)
RETURNS STRING
PartMeaning
MIDroutine identifier
ThisString : STRINGfirst parameter: source text
x : INTEGERsecond: starting position
y : INTEGERthird: character count
RETURNS STRINGtype sent back to caller
Arguments follow that order
MID("ABCDEFGH", 2, 3) → "BCD"

Benefits, and the limits of the interface

Two sides to weigh: what a routine saves you, and what goes wrong when a call breaks its interface.

Why use library routines?

  • Tried and tested, so far less likely to contain errors.
  • Provides functionality that may be difficult to code.
  • Readily available, so development is faster.
  • An automatically updated library can supply improvements without rewriting the routine; check that its interface remains compatible.

Calls that cause errors

A call that is not properly formed, or a parameter of the wrong type or value, generates an error:

  • INT(100 / N) when N is 0: division by zero.
  • RIGHT(Label, 9) when Label has fewer than 9 characters.
  • STR_TO_NUM(Entry) when Entry is "ten".

Use and combine routines

A routine works only if it gets what it expects, in the order it expects. Call each with its parameters in the right order, and use what it returns.

Check before you convert"ten", "12 kg", "12" → 24
DECLARE Entry : STRING
DECLARE Quantity : REAL
REPEAT
OUTPUT "Enter a quantity"
INPUT Entry
UNTIL IS_NUM(Entry)
Quantity ← STR_TO_NUM(Entry)
OUTPUT Quantity * 2

IS_NUM() is checked first, so STR_TO_NUM() never receives "ten".

MID built from LEFT and RIGHT
1FUNCTION MyMid(Str : STRING, x : INTEGER,
2y : INTEGER) RETURNS STRING
3DECLARE Front : STRING
4Front ← LEFT(Str, x + y - 1)
5RETURN RIGHT(Front, y)
6ENDFUNCTION
7
8OUTPUT MyMid("MAR-2026-X7", 5, 4)

LEFT(Str, 5 + 4 - 1) keeps the first 8 characters, "MAR-2026". RIGHT(Front, 4) keeps the last 4 of those, "2026": the same as MID(Str, 5, 4). MyMid assumes 1 ≤ x and x + y − 1 ≤ LENGTH(Str).

  1. 1
    LEFT keeps the first 8 characters; RIGHT keeps the last 4 of those.
  2. 2
    MyMid assumes a valid start and count: 1 ≤ x and x + y − 1 ≤ LENGTH(Str).
Run the call line by line
LineStatement that runsStr, x, yFrontReturnsOutputWritesWhat happens
8OUTPUT MyMid("MAR-2026-X7", 5, 4)"MAR-2026-X7", 5, 4Str, x, y "MAR-2026-X7", 5, 4the call: the values are copied into the parameters, in order
the call: the values are copied into the parameters, in order
4Front ← LEFT(Str, x + y - 1)"MAR-2026"Front "MAR-2026"LEFT(Str, 5 + 4 − 1): the first 8 characters
LEFT(Str, 5 + 4 − 1): the first 8 characters
5RETURN RIGHT(Front, y)"2026"Returns "2026"the last 4 of those
the last 4 of those
8OUTPUT MyMid("MAR-2026-X7", 5, 4)2026Output 2026the returned value replaces the call
the returned value replaces the call
The insert also gives date routines: MONTH(04/03/2025) is 3, and DAYINDEX(04/03/2025) is 3 because that date is a Tuesday (Sunday is 1).
Your turn

1 MID(S, 3, 2) gives the same result as RIGHT(LEFT(S, n), 2). What is n?

2 What does MyMid("WINTER", 2, 3) return?

3 Give two reasons for using a library routine.

  1. 1
    4: for S ← "PLANET" both give "AN"
  2. 2
    "INT"
  3. 3
    it is tried and tested, so less likely to contain errors; it is readily available, so development is faster
Tick what you can do now
Exam focus“How do library routines reduce errors?”: the code is tried and tested, or it provides functionality that would be difficult to write. When you call one, match the number, order and types of its parameters exactly.
Practise with s25/21 Q2(b)(iii); w25/23 Q1(a); w24/22 Q5(a); s24/23 Q1(b); s25/23 Q1(b); s22/22 Q7(a) (older paper: implement MID)
7 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

From a design to pseudocode

§11.1 · Programming basics · implementing a flowchart or structured English

A design shows what a program should do; the pseudocode says exactly how. Each symbol of a program flowchart, or step of structured English, becomes a statement or construct.

Flowchart → pseudocode

Follow the badges: each numbered symbol is the line with the same number in the pseudocode.

STARTSet Count to 01INPUT Value2Is Value = −1 ?3YesNoIs Value > 100 ?4YesAdd 1 to Count5NoINPUT Value7OUTPUT Count9END
START1 Set Count to 02 INPUT Value3 Value = −1?YesNo4 Value > 100?Yes5 Add 1 to CountNo7 INPUT Value9 OUTPUT CountEND
Each badge is a line number150, 80, 101, 100, −1 → 2
1Count ← 0
2INPUT Value
3WHILE Value <> -1
4IF Value > 100 THEN
5Count ← Count + 1
6ENDIF
7INPUT Value
8ENDWHILE
9OUTPUT Count
FlowchartPseudocode
decision, paths join belowIF … ELSE … ENDIF
decision, a path back upWHILE or REPEAT … UNTIL
a counter loopFOR … NEXT

Trace the flowchart's program

Running the finished program by hand checks it against the design. Write the values after each time round the loop.

Pass 3, line by line
Line numbers match the badges on the flowchart.
LineStatement that runsValueCountOutputWritesWhat happens
3WHILE Value <> -1test 101 <> −1 is TRUE: go into the loop
test 101 <> −1 is TRUE: go into the loop
4IF Value > 100 THENtest 101 > 100 is TRUE
test 101 > 100 is TRUE
5Count ← Count + 12Count 21 + 1
1 + 1
7INPUT Value100Value 100the next value
the next value

The whole run

ValueCountOutputWhat decided it
start1500line 1 sets Count; line 2 inputs the first value
line 1 sets Count; line 2 inputs the first value
pass 1801150 > 100: add 1; line 7 inputs 80
150 > 100: add 1; line 7 inputs 80
pass 210180 > 100 is false: Count unchanged; line 7 inputs 101
80 > 100 is false: Count unchanged; line 7 inputs 101
pass 31002101 > 100: add 1; line 7 inputs 100
101 > 100: add 1; line 7 inputs 100
pass 4-1100 > 100 is false: Count unchanged; line 7 inputs -1
100 > 100 is false: Count unchanged; line 7 inputs -1
end2Value is -1: the loop ends and line 9 outputs Count
Value is -1: the loop ends and line 9 outputs Count

Structured English → pseudocode

Each numbered step becomes a line or two. Step 4 sends the program back only after steps 2 and 3 have run, so the loop becomes REPEAT … UNTIL.

Structured English

1
Set the attempt count to zero.
2
Prompt for and input a PIN.
3
Add one to the attempt count.
4
If the PIN is wrong and the count is below 3, repeat from step 2.
5
Output "Accepted" if the PIN is correct, otherwise "Locked".

“Repeat from step 2”, tested after steps 2 and 3, is a post-condition loop. UNTIL takes the opposite of “repeat if”: NOT (wrong AND count < 3) is (correct OR count = 3).

  • “Repeat from step 2”, tested after steps 2 and 3: a post-condition loop.
  • UNTIL takes the opposite of “repeat if”: NOT (wrong AND count < 3) is (correct OR count = 3).
Pseudocode
CONSTANT CorrectPIN = 4071
DECLARE PIN, Attempts : INTEGER
Attempts ← 0
REPEAT
OUTPUT "Enter your PIN"
INPUT PIN
Attempts ← Attempts + 1
UNTIL PIN = CorrectPIN OR Attempts = 3
IF PIN = CorrectPIN THEN
OUTPUT "Accepted"
ELSE
OUTPUT "Locked"
ENDIF
Your turn

1 The flowchart's program is given 120, 99, 300, −1. What is output?

2 Which pseudocode construct does a decision with a path back up become?

3 In the PIN program, why is UNTIL PIN = CorrectPIN OR Attempts = 3 and not AND?

  1. 1
    2: only 120 and 300 are over 100
  2. 2
    a loop: WHILE or REPEAT … UNTIL
  3. 3
    the loop stops when either is true: the PIN is right, or the third try is used
Tick what you can do now
Exam focusA decision that leads back up is iteration, not IF. Decision 3 leaves the loop on Yes, so the loop continues while that test is false: WHILE Value <> -1.
Practise with s24/22 Q2(b); s25/21 Q3; w24/23 Q2(b)
8 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Selection with IF

§11.2 · Constructs · IF, ELSE and nested IF

A program that turns marks into grades must make a choice for every mark. That choice is selection, one of three basic constructs. Naming a construct is half the job; the other half is saying what it does in the task.

A program that turns marks into grades must make a choice for every mark. Selection is one of three basic constructs. To identify one, name it and describe its use in the task.

ConstructIn pseudocodeIts use, described for the task
Sequencestatements run one after another“so Wanted is input before Cost is calculated”
SelectionIF … ENDIF, CASE … ENDCASE“to test Mark against 50 and set Pass or Fail”
IterationFOR, WHILE, REPEAT … UNTIL“to loop through the ten random trials”

IF, IF … ELSE and nested IF

Three shapes, from a single test to a chain of them. Run the nested IF with Mark 54 and see where each FALSE test sends you.

IF without ELSE
IF Temperature > 30 THEN
OUTPUT "Warning: hot"
ENDIF
IF with ELSE
IF Mark >= 50 THEN
Result ← "Pass"
ELSE
Result ← "Fail"
ENDIF

IF … THEN goes on one line; ELSE and ENDIF line up with IF; the statements inside are indented three spaces. Every IF, nested ones too, has its own ENDIF.

  • IF … THEN on one line; ELSE and ENDIF line up with IF.
  • Indent the statements inside three spaces.
  • Every IF, nested ones too, has its own ENDIF.
Nested IF
 1IF Mark >= 70 THEN
 2Grade ← 'A'
 3ELSE
 4IF Mark >= 55 THEN
 5Grade ← 'B'
 6ELSE
 7IF Mark >= 40 THEN
 8Grade ← 'C'
 9ELSE
10Grade ← 'U'
11ENDIF
12ENDIF
13ENDIF
Mark is 54: the lines that run
Three tests run; only the third is true.
LineStatement that runsGradeWritesWhat happens
1IF Mark >= 70 THENtest 54 >= 70 is FALSE: go to its ELSE
test 54 >= 70 is FALSE: go to its ELSE
4IF Mark >= 55 THENtest 54 >= 55 is FALSE: go to its ELSE
test 54 >= 55 is FALSE: go to its ELSE
7IF Mark >= 40 THENtest 54 >= 40 is TRUE: go into THEN
test 54 >= 40 is TRUE: go into THEN
8Grade ← 'C''C'Grade 'C'the branch taken; every other test is skipped
the branch taken; every other test is skipped

Order matters

  • When conditions overlap, testing Mark >= 40 first catches every mark from 40 up: 85 would get grade C.
  • The A and B branches would never run.
  • Test the most restrictive condition first.

Separate IFs or IF … ELSE?

  • Separate IF statements are all tested, so more than one can run.
  • IF … ELSE runs exactly one of its two branches.
grade Ugrade Cgrade Bgrade A0405570100Test each side of every boundary:39 → U, 40 → C, 54 → C, 55 → B, 69 → B, 70 → AThe tests run in the order ≥ 70, ≥ 55, ≥ 40, so each branch only needs a lower bound.
UCBA0405570100Integer marks: test both sides of each boundary39 → U40 → C54 → C55 → B69 → B70 → ATest ≥70, then ≥55, then ≥40.Each later branch has failed the earlier tests.
Your turn

1 What does the nested IF set Grade to when Mark is 70? When Mark is 39?

2 The tests are written in the order >= 40, >= 55, >= 70. What grade does a mark of 85 get?

3 Name the construct and describe its use: IF Mark >= 50 THEN Result ← "Pass".

  1. 1
    'A' (70 >= 70 is TRUE); 'U' (every test is FALSE)
  2. 2
    'C': 85 >= 40 is TRUE first, so the other tests never run
  3. 3
    selection: to test the mark against 50 and set Pass
Tick what you can do now
Exam focusClose every IF with ENDIF and line ELSE up with its IF. When conditions overlap, test the most restrictive first, or later branches are never reached.
Practise with s24/22 Q4; s25/21 Q2(a)(i), (a)(ii); w24/23 Q2(b)
9 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Selection with CASE

§11.2 · Constructs · CASE structure

A menu written with IFs asks about the same variable again and again. CASE asks once: it takes the value of a single expression and runs the one branch that matches.

Instead of many IFs, CASE selects one of several branches from the value of a single expression.

Values and OTHERWISE

Run the menu with Choice 3: the clauses are tested in order, and only the first match runs.

A menu
1CASE OF Choice
21 : OUTPUT "New booking"
32 : OUTPUT "Cancel a booking"
43 : OUTPUT "Print a receipt"
5Copies ← Copies + 1
6OTHERWISE : OUTPUT "Choose 1, 2 or 3"
7ENDCASE

How CASE runs

  • The clauses are tested in order. The first that matches runs, then control passes to the statement after ENDCASE: no other clause is tested.
  • A clause is a value (3 :) or a range (40 TO 54 :, 'a' TO 'z' :). Exam papers also write comparisons (<= 10 :). Characters take single quotes.
  • A clause may hold several statements: line them up under the first.
  • OTHERWISE : must be the last clause; it runs when no other clause matches.
Choice is 3: the lines that run
OTHERWISE is never tested: a clause has already matched.
LineStatement that runsCopiesOutputWritesWhat happens
1CASE OF Choicetest Choice is 3
test Choice is 3
21 : OUTPUT "New booking"test 3 = 1 is FALSE: test the next clause
test 3 = 1 is FALSE: test the next clause
32 : OUTPUT "Cancel a booking"test 3 = 2 is FALSE: test the next clause
test 3 = 2 is FALSE: test the next clause
43 : OUTPUT "Print a receipt"Print a receiptOutput Print a receipt3 = 3: match
3 = 3: match
5Copies ← Copies + 11Copies 1the same clause's second statement; then to the line after ENDCASE
the same clause's second statement; then to the line after ENDCASE

The same selection with IF

Nested IF version
IF Choice = 1 THEN
OUTPUT "New booking"
ELSE
IF Choice = 2 THEN
OUTPUT "Cancel a booking"
ELSE
IF Choice = 3 THEN
OUTPUT "Print a receipt"
Copies ← Copies + 1
ELSE
OUTPUT "Choose 1, 2 or 3"
ENDIF
ENDIF
ENDIF

Comparisons, and a clause never reached

Comparison clausesWeight 1 → 8, not 3
CASE OF Weight
<= 10 : Postage ← 8
<= 2 : Postage ← 3
> 10 : Postage ← 15
ENDCASE

A clause never reached

  • Any weight up to 2 already matches <= 10, so Postage ← 3 never runs: put <= 2 first.
  • The last clause, > 10, can be replaced by OTHERWISE.
  • After CASE OF (N MOD 2) with clauses 0 and 1, an OTHERWISE can never run.
Use CASE when one evaluated value is compared with several separate values or ranges. Use IF when a condition combines different variables or needs AND, OR or NOT.
Your turn

1 What does the menu output when Choice is 2?

2 In the comparison CASE, what is Postage when Weight is 2?

3 Swap the first two clauses. What is Postage for a weight of 2 now?

  1. 1
    Cancel a booking
  2. 2
    8: <= 10 matches first
  3. 3
    3: <= 2 is now tested first
Tick what you can do now
Exam focusPut OTHERWISE : last, for every other value. Why does a clause never run? The clauses are checked in sequence, and an earlier clause already matches those values.
Practise with w24/22 Q5(c); w23/21 Q1(b) (older paper: unreachable CASE clause)
10 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Count-controlled loops

§11.2 · Constructs · FOR … NEXT

When you know how many times something must happen, let the loop do the counting. A count-controlled loop repeats a set number of times. The loop variable goes from the start value towards the end value, changing by STEP (1 if none is given).

Follow the jumps of 3 from 2. The next jump would land on 11, past the end value, so 8 is the last value of i.

0123456789101112end value 10+3+311 > 10: stopFOR i ← 2 TO 10 STEP 3i takes 2, 5, 8: 3 iterations
FOR i ← 2 TO 10 STEP 32+35+38+311Body runs at 2, 5 and 8: three iterations.Next value 11 exceeds 10: stop before the body.

How many iterations?

The end value runs only if a step lands on it, so list the values before you count them.

LoopValues of iCount
FOR i ← 1 TO 51, 2, 3, 4, 55
FOR i ← 2 TO 11 STEP 32, 5, 8, 114
FOR i ← 10 TO 1 STEP -410, 6, 23
FOR i ← 4 TO 441
FOR i ← 5 TO 4none0

Testing IF Num MOD 7 = 0 for every Num from 1 to 60 is also correct, but makes 60 tests for 8 outputs. STEP 7 goes straight to each one.

Multiples of 7 up to 607, 14 … 56, then 8
DECLARE Num, Count : INTEGER
Count ← 0
FOR Num ← 7 TO 60 STEP 7
OUTPUT Num
Count ← Count + 1
NEXT Num
OUTPUT Count

Nested loops

Run one pass of the outer loop, Row 3: the inner loop adds a star each time round, Row times, before OUTPUT.

Nested FOR loops
DECLARE Row, Col : INTEGER
DECLARE Stars : STRING
FOR Row ← 1 TO 4
Stars ← ""
FOR Col ← 1 TO Row
Stars ← Stars & '*'
NEXT Col
OUTPUT Stars
NEXT Row
Output
*
**
***
****

The inner loop restarts on every pass of the outer loop and runs Row times: 1 + 2 + 3 + 4 = 10 iterations in all. Stars is reset inside the outer loop, so each row starts empty.

  • The inner loop restarts on every pass of the outer loop and runs Row times: 1 + 2 + 3 + 4 = 10 iterations in all.
  • Stars is reset inside the outer loop, so each row starts empty.

Trace the nested loops

The inner loop runs all the way through on every pass of the outer loop. Follow Row 3 through all three of its inner passes.

Row 3, line by line
One pass of the outer loop: the blue row of the whole run below.
LineStatement that runsRowColStarsOutputWritesWhat happens
3FOR Row ← 1 TO 43Row 3the outer loop's next value
the outer loop's next value
4Stars ← """"Stars ""Stars starts empty for this row
Stars starts empty for this row
5FOR Col ← 1 TO Row1Col 1the inner loop starts again at 1
the inner loop starts again at 1
6Stars ← Stars & '*'"*"Stars "*"add one star: 1 now
add one star: 1 now
5FOR Col ← 1 TO Row2Col 2Col 2 of 3
Col 2 of 3
6Stars ← Stars & '*'"**"Stars "**"add one star: 2 now
add one star: 2 now
5FOR Col ← 1 TO Row3Col 3Col 3 of 3
Col 3 of 3
6Stars ← Stars & '*'"***"Stars "***"add one star: 3 now
add one star: 3 now
5FOR Col ← 1 TO Rowtest Col has reached Row (3): the inner loop ends
test Col has reached Row (3): the inner loop ends
8OUTPUT Stars***Output ***one line of output
one line of output

The whole run

RowColStarsOutputWhat decided it
Row 111"*"*the inner loop runs 1 time: Col takes 1
the inner loop runs 1 time: Col takes 1
Row 2212"**"**the inner loop runs 2 times: Col takes 1, 2
the inner loop runs 2 times: Col takes 1, 2
Row 33123"***"***the inner loop runs 3 times: Col takes 1, 2, 3
the inner loop runs 3 times: Col takes 1, 2, 3
Row 441234"****"****the inner loop runs 4 times: Col takes 1, 2, 3, 4
the inner loop runs 4 times: Col takes 1, 2, 3, 4
endRow has reached 4: the outer loop ends
Row has reached 4: the outer loop ends
Your turn

1 List the values of i for FOR i ← 3 TO 15 STEP 4. How many iterations?

2 List the values of i for FOR i ← 20 TO 2 STEP -6.

3 An outer loop FOR Row ← 1 TO 3 holds FOR Col ← 1 TO 2. How many times does the inner body run?

  1. 1
    3, 7, 11, 15: 4 iterations
  2. 2
    20, 14, 8, 2
  3. 3
    6: 3 × 2
Tick what you can do now
Exam focusList the loop values that stay within the bound: FOR i ← 4 TO 20 STEP 4 runs 5 times. Do not change the loop variable inside the loop; repeat it after NEXT.
Practise with s26/21 Q1(a), (b); w24/23 Q2(a); w25/22 Q4(b)
11 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Pre-condition and post-condition loops

§11.2 · Constructs · WHILE and REPEAT … UNTIL

Often a program cannot know how many times to repeat: it carries on until the user enters 0, or types a sensible quantity. A conditional loop is used when the number of iterations is not known in advance. Where the condition is tested sets the minimum number of passes.

Follow the arrows in each: WHILE meets its test before the body, REPEAT only after it.

WHILE: pre-conditioncondition TRUE?Yesloop bodyNo: exittested before the body: may run 0 timesREPEAT … UNTIL: post-conditionloop bodycondition TRUE?NoYes: exittested after the body: runs at least once
WHILE: test before bodyCondition TRUE?Loop bodyYesNo: exitMay run zero times.REPEAT: test after bodyLoop bodyCondition TRUE?Yes: exitNoRuns at least once.

WHILE … ENDWHILE

Run it with 12, 7, 5, 0: the 0 is the signal to stop, so it is never added.

Pre-condition: stop at 012, 7, 5, 0
 1DECLARE Value, Total, Count : INTEGER
 2Total ← 0
 3Count ← 0
 4INPUT Value
 5WHILE Value <> 0
 6Total ← Total + Value
 7Count ← Count + 1
 8INPUT Value
 9ENDWHILE
10OUTPUT Count, " values, total ", Total
PassValueTotalCountOutput
start1200
17121
25192
30243
end3 values, total 24

Rows are after INPUT: Value is the next item; Total and Count cover values already processed. If the first input is 0, the body runs zero times.

If Value is non-zero and the inner INPUT Value is removed, Value never changes: the terminating condition is never satisfied, so the loop is infinite.
Pre-condition: stop at 012, 7, 5, 0
 1DECLARE Value, Total, Count : INTEGER
 2Total ← 0
 3Count ← 0
 4INPUT Value
 5WHILE Value <> 0
 6Total ← Total + Value
 7Count ← Count + 1
 8INPUT Value
 9ENDWHILE
10OUTPUT Count, " values, total ", Total
  • Each row is after line 8: Value is the next item; Total and Count cover the values already added.
  • If the first input is 0, the body runs zero times.
If Value is non-zero and the inner INPUT Value is removed, Value never changes: the terminating condition is never satisfied, so the loop is infinite.

Trace the WHILE loop

The condition is tested before every pass, so a row is written only when it is TRUE.

Pass 2, line by line
The blue row of the whole run below.
LineStatement that runsValueTotalCountOutputWritesWhat happens
5WHILE Value <> 0test 7 <> 0 is TRUE: run the body
test 7 <> 0 is TRUE: run the body
6Total ← Total + Value19Total 1912 + 7
12 + 7
7Count ← Count + 12Count 21 + 1
1 + 1
8INPUT Value5Value 5the next value; then back to line 5
the next value; then back to line 5

The whole run

ValueTotalCountOutputWhat decided it
start1200lines 2–4: Total and Count start at 0; the first value is input
lines 2–4: Total and Count start at 0; the first value is input
pass 1712112 <> 0: add 12 to Total; line 8 inputs 7
12 <> 0: add 12 to Total; line 8 inputs 7
pass 251927 <> 0: add 7 to Total; line 8 inputs 5
7 <> 0: add 7 to Total; line 8 inputs 5
pass 302435 <> 0: add 5 to Total; line 8 inputs 0
5 <> 0: add 5 to Total; line 8 inputs 0
end3 values, total 240 <> 0 is FALSE: the loop ends; line 10 outputs
0 <> 0 is FALSE: the loop ends; line 10 outputs

REPEAT … UNTIL

Post-condition: validate an input0, 9, 5
DECLARE Quantity : INTEGER
REPEAT
OUTPUT "Enter a quantity from 1 to 8"
INPUT Quantity
UNTIL Quantity >= 1 AND Quantity <= 8
QuantityUNTIL conditionThen
0FALSErepeat
9FALSErepeat
5TRUEstop
WHILE repeats while its condition is TRUE; REPEAT stops when its condition becomes TRUE. The same rule is WHILE Value <> 0 or UNTIL Value = 0.
Post-condition: validate an input0, 9, 5
DECLARE Quantity : INTEGER
REPEAT
OUTPUT "Enter a quantity from 1 to 8"
INPUT Quantity
UNTIL Quantity >= 1 AND Quantity <= 8
WHILE repeats while its condition is TRUE; REPEAT stops when its condition becomes TRUE. The same rule is WHILE Value <> 0 or UNTIL Value = 0.

Run it with 0, 9, 5: the prompt repeats until a quantity from 1 to 8 arrives.

QuantityUNTIL testThen
pass 10FALSE0 is out of range: back to REPEAT
0 is out of range: back to REPEAT
pass 29FALSE9 is out of range: back to REPEAT
9 is out of range: back to REPEAT
pass 35TRUEin range: the loop stops
in range: the loop stops
Your turn

1 The WHILE program is given 4, 9, 0. What is output?

2 It is given 0 first. How many times does the body run, and what is output?

3 The REPEAT program is given 12, then 3. How many times is the prompt output?

  1. 1
    2 values, total 13
  2. 2
    zero times: 0 values, total 0
  3. 3
    2 times: 12 fails the test, 3 passes
Tick what you can do now
Practise with s24/23 Q4(a); s26/23 Q1(a), (b); w24/22 Q5(b)
12 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Choosing the right loop

§11.2 · Constructs · justifying a loop structure

Most tasks could be written with more than one kind of loop, but one fits best, and you should be able to say why. Choose a loop from its stopping rule, then explain how that rule fits the data being processed.

Start at the first question. A known count settles it at once; otherwise ask whether the body must run before the first test.

Is the number of iterationsknown before the loop starts?YesFOR … NEXTcount-controlledNoMust the body run at leastonce, before the test?YesREPEAT … UNTILpost-conditionNoWHILE … ENDWHILEpre-condition
Stopping ruleLoop and reason
Known number of passesFOR: loop variable visits a known range
Unknown count; body must run firstREPEAT: input/process before testing
Unknown count; may need zero passesWHILE: test before entering the body

Justify the choice

Name the loop, then point to the fact in the task that decides it: a known count, or an unknown one.

LoopChoose it when…Reason tied to the task
count-controlledeach character of Code; the ten random trialsthe number of iterations is known (the length of the string)
pre-conditionthe terminator might be the first value inputthe number of iterations is not known; the terminator ends the loop; tested before the first pass
post-conditioninput validation, a menu, a guessing gamethe number of iterations is not known; the body must run at least once
conditional, not FORsearching for the first matchthe loop can stop as soon as the value is found

Replace a conditional loop with a FOR loop

When the count turns out to be known after all, a FOR loop does the same job in fewer lines.

Pre-condition loopCode ← "MAR-2026-X7"
1Digits ← 0
2Index ← 1
3WHILE Index <= LENGTH(Code)
4IF IS_NUM(MID(Code, Index, 1)) THEN
5Digits ← Digits + 1
6ENDIF
7Index ← Index + 1
8ENDWHILE
Count-controlled loop: better
1Digits ← 0
2FOR Index ← 1 TO LENGTH(Code)
3IF IS_NUM(MID(Code, Index, 1)) THEN
4Digits ← Digits + 1
5ENDIF
6NEXT Index

Both count 5 digits. The FOR loop sets and increases Index itself, so lines 2 and 7 of the WHILE version are removed, and lines 3 and 8 change to FOR … TO LENGTH(Code) and NEXT Index.

  • Both count 5 digits.
  • The FOR loop sets and increases Index itself: lines 2 and 7 of the WHILE version are removed.
  • Lines 3 and 8 change to FOR … TO LENGTH(Code) and NEXT Index.
Your turn

1 30 marks are input one at a time and totalled. Which loop? Give the reason.

2 A password is input again and again until it is correct. Which loop? Give the reason.

3 Rewrite as a FOR loop: Index ← 1, WHILE Index <= 10, Total ← Total + Index, Index ← Index + 1, ENDWHILE.

  1. 1
    count-controlled: the number of iterations is known (30)
  2. 2
    post-condition: the number of tries is not known, and the password must be input at least once
  3. 3
    FOR Index ← 1 TO 10, Total ← Total + Index, NEXT Index: both give 55
Tick what you can do now
Exam focusName the loop, then give the reason in the problem: “count-controlled, because the number of iterations is known: the length of the string”. The name alone is not a justification.
Practise with s24/23 Q5(a); s25/21 Q4(a); w25/21 Q5(b)(i), (b)(ii)
13 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Procedures

§11.3 · Structured programming · defining and calling procedures

A program that draws the same kind of line in ten places should not contain that code ten times. Write it once as a procedure, which performs a task, and run it with a CALL wherever it is needed; when it ends, the program continues after the CALL. A subroutine (or module) is a procedure or a function.

Follow the second CALL: 10 and '=' are copied into Size and Symbol, the line is output, then control comes back to the next CALL.

Main programCALL Welcome()CALL ShowLine(10, '=')CALL ShowLine(4, '*')ShowLine(Size : INTEGER, Symbol : CHAR) runs withSize10Symbol'='OUTPUT Line==========1copied in2back to the next statementSize takes 10 and Symbol takes '=': arguments are matched to parameters in order.
Main: CALL ShowLine(10, '=')ShowLine: Size = 10, Symbol = '='Procedure builds and outputs ==========ENDPROCEDURE: return after the CALLMain: CALL ShowLine(4, '*')The next call receives Size 4 and Symbol '*'.

A procedure with parameters, one without

Run the three CALLs in order and match each one to a line of output.

Two procedures and a main program
PROCEDURE ShowLine(Size : INTEGER, Symbol : CHAR)
DECLARE Line : STRING
DECLARE Count : INTEGER
Line ← ""
FOR Count ← 1 TO Size
Line ← Line & Symbol
NEXT Count
OUTPUT Line
ENDPROCEDURE

PROCEDURE Welcome()
OUTPUT "Quiz night"
ENDPROCEDURE

CALL Welcome()
CALL ShowLine(10, '=')
CALL ShowLine(4, '*')
Output
Quiz night
==========
****

Define and call

  • PROCEDURE Name() has no parameters; PROCEDURE Name(P : TYPE, …) has one or more.
  • End the definition with ENDPROCEDURE.
  • CALL Name(Arg, …) is a complete statement. Arguments match the parameters in number, order and data type.

When is a procedure appropriate?

  • A task is repeated or performed in several places: it is written and tested once, which avoids duplicated code and errors caused by differences between copies.
  • A part of the algorithm performs a specific task: an action, rather than one value for an expression.
  • It reduces complexity: the program is simplified, and testing, debugging and maintenance are easier.
Your turn

1 What is output by CALL ShowLine(3, '#')?

2 Write a call that outputs five dashes.

3 Why is ShowLine(10, '=') on its own line, without CALL, not a valid statement?

  1. 1
    ###
  2. 2
    CALL ShowLine(5, '-')
  3. 3
    a procedure is run by a CALL statement; only a function is used without CALL, inside an expression
Tick what you can do now
Exam focusRun a procedure with CALL Name(arguments): a complete statement. To justify a module, link it to the scenario: “the check is needed in several places, so it is written and tested once”.
Practise with s25/23 Q1(a)(i); w24/21 Q4(b); s24/22 Q4
14 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Functions

§11.3 · Structured programming · defining and using functions

Sometimes you want an answer back, not just a job done: how many coaches does this trip need? A function is a subroutine that returns a single value to the point where it is called. The call is used inside an expression, and the return value replaces the call before the expression is evaluated.

Read the three boxes in order: the call is worked out first, and its value takes its place in the expression.

Cost ← Coaches(130) * 450the call is part of an expressionCost ← 3 * 450RETURN sends back 3: it replaces the callCost ← 1350then the expression is evaluated
Cost ← Coaches(130) * 450Cost ← 3 * 450Cost ← 1350RETURN replaces the call; then multiply.

Define and use a function

Run Coaches(130): 130 people do not fill a whole number of 52-seat coaches, so the first RETURN is the one reached.

Define, then use in expressionsoutputs 3 and 1350
 1FUNCTION Coaches(People : INTEGER) RETURNS INTEGER
 2DECLARE Full : INTEGER
 3Full ← People DIV 52
 4IF People MOD 52 > 0 THEN
 5RETURN Full + 1
 6ENDIF
 7RETURN Full
 8ENDFUNCTION
 9
10DECLARE Cost : INTEGER
11OUTPUT "Coaches: ", Coaches(130)
12Cost ← Coaches(130) * 450
13OUTPUT "Cost: ", Cost

Rules for functions

  • The header ends RETURNS <data type>.
  • RETURN sends the value back and ends the function at once: for 130 people the second RETURN is never reached. Every path must reach a RETURN.
  • Call it inside an expression, never with CALL. A BOOLEAN function can be a whole condition: IF IsValid(Code) THEN.
  • OUTPUT inside a function displays a value; it does not return it.
Run Coaches(130) line by line
Line 7, the second RETURN, never runs.
LineStatement that runsPeopleFullReturnsOutputWritesWhat happens
11OUTPUT "Coaches: ", Coaches(130)130People 130the call: 130 is copied into the parameter People
the call: 130 is copied into the parameter People
3Full ← People DIV 522Full 2130 DIV 52
130 DIV 52
4IF People MOD 52 > 0 THENtest 130 MOD 52 = 26, and 26 > 0 is TRUE
test 130 MOD 52 = 26, and 26 > 0 is TRUE
5RETURN Full + 13Returns 32 + 1 is sent back; the function ends here
2 + 1 is sent back; the function ends here
11OUTPUT "Coaches: ", Coaches(130)Coaches: 3Output Coaches: 33 replaces the call
3 replaces the call

Procedure or function?

A module's description gives it away: if it hands back one value, it is a function.

ProcedureFunction
Purposecarries out a taskcalculates and returns a single value
HeaderPROCEDURE Name(…)FUNCTION Name(…) RETURNS <type>
How it is usedCALL Name(…): a statement on its ownin an expression: X ← Name(…)
Passing values backthrough BYREF parametersthe return value; parameters are by value
Choose it when…it outputs or updates, and returns nothingthe description says “returns” (even if it also writes a file), or one value is needed in an expression or condition

Purpose

Procedure

carries out a task

Function

calculates and returns a single value

Header

Procedure

PROCEDURE Name(…)

Function

FUNCTION Name(…) RETURNS <type>

How it is used

Procedure

CALL Name(…): a statement on its own

Function

in an expression: X ← Name(…)

Passing values back

Procedure

through BYREF parameters

Function

the return value; parameters are by value

Choose it when…

Procedure

it outputs or updates, and returns nothing

Function

the description says “returns” (even if it also writes a file), or one value is needed in an expression or condition

Your turn

1 What does Coaches(104) return? And Coaches(53)?

2 Why is CALL Coaches(130) wrong?

3 A module takes a price and returns the price with tax added. Procedure or function? Why?

  1. 1
    2: 104 MOD 52 = 0, so the second RETURN runs; 2: 53 DIV 52 = 1, plus 1
  2. 2
    a function is used inside an expression: X ← Coaches(130)
  3. 3
    a function: it returns a single value
Tick what you can do now
Exam focusA function header needs RETURNS and a type, and every path must RETURN a value of that type. The difference: a function returns a value; a procedure does not.
Practise with s26/21 Q5(a), (b); s25/23 Q6(a); s24/23 Q7(a)(i)
15 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Passing parameters by value and by reference

§11.3 · Structured programming · BYVAL and BYREF

When a procedure changes a parameter, the caller's own variable may or may not change with it. It depends on how the parameter is passed: by value (a copy of the value) or by reference (the caller's variable itself).

Follow Score in each drawing: under BYVAL it is a separate copy; under BYREF it is an arrow into Points itself.

BYVAL: two separate locationsPoints (caller)50Score (copy)copy60Score ← Score + 10On return: Points = 50 (unchanged)BYREF: one shared locationPoints (caller)60ScoreScore ← Score + 10On return: Points = 60
BYVAL: two separate locationsPoints (caller)50Score (copy)copy60Score ← Score + 10On return: Points = 50 (unchanged)BYREF: one shared locationPoints (caller)60ScoreScore ← Score + 10On return: Points = 60

Trace the difference

Run it with Points at 50 and watch which variable line 2 changes.

Passed by value
1PROCEDURE Bonus(BYVAL Score : INTEGER)
2Score ← Score + 10
3OUTPUT "Inside: ", Score
4ENDPROCEDURE
5
6DECLARE Points : INTEGER
7Points ← 50
8CALL Bonus(Points)
9OUTPUT "After: ", Points

Syntax

  • BYVAL or BYREF goes before the parameter in the header.
  • With neither keyword, a parameter is passed by value.
  • A keyword covers the parameters after it: in (BYREF X : INTEGER, Y : INTEGER) both are BYREF.
  • Parameters should not be passed by reference to a function.
By valueBy reference
LineStatementPointsScoreOutputPoints = ScoreOutput
7Points ← 505050
8CALL Bonus(Points)505050
2Score ← Score + 10506060
3OUTPUT "Inside: ", ScoreInside: 60Inside: 60
9OUTPUT "After: ", PointsAfter: 50After: 60

By value

Line / statementPointsScoreOutput
7: Points ← 5050
8: CALL Bonus(Points)5050
2: Score ← Score + 105060
3: OUTPUT "Inside: ", ScoreInside: 60
9: OUTPUT "After: ", PointsAfter: 50

By reference

Line / statementPoints = ScoreOutput
7: Points ← 5050
8: CALL Bonus(Points)50
2: Score ← Score + 1060
3: OUTPUT "Inside: ", ScoreInside: 60
9: OUTPUT "After: ", PointsAfter: 60

By reference is the same program with line 1 as PROCEDURE Bonus(BYREF Score : INTEGER). Score and Points are then one memory location, so line 2 changes Points too.

The same call gives two different results: by value the caller keeps 50; by reference it ends with 60.

Passed by value

PointsScoreOutputWhat happens
line 750the caller's variable
the caller's variable
line 85050a copy of 50 goes into Score
a copy of 50 goes into Score
line 260Score + 10: only the copy changes
Score + 10: only the copy changes
line 3Inside: 60the value inside the procedure
the value inside the procedure
line 9After: 50the copy has gone: Points is still 50
the copy has gone: Points is still 50
  • By reference is the same program with line 1 as PROCEDURE Bonus(BYREF Score : INTEGER).
  • Score and Points are then one memory location, so line 2 changes Points too.

Passed by reference

Points = ScoreOutputWhat happens
line 750the caller's variable
the caller's variable
line 850Score is linked to Points: one location
Score is linked to Points: one location
line 260Score + 10: the shared location changes
Score + 10: the shared location changes
line 3Inside: 60the value inside the procedure
the value inside the procedure
line 9After: 60Points now holds 60
Points now holds 60
Your turn

1 PROCEDURE Double(BYREF N : INTEGER) sets N ← N * 2. Value is 7 before CALL Double(Value). What is Value after the call?

2 The header is changed to BYVAL N. What is Value after the call now?

3 Which keyword is used when there is neither BYVAL nor BYREF?

  1. 1
    14: N and Value are one location
  2. 2
    7: only the copy N doubles
  3. 3
    none is needed: the parameter is passed by value
Tick what you can do now
Exam focusExplain the effect from the caller's side: by reference, a change to the parameter is reflected in the calling module's variable after the call; by value, it is not.
Practise with s24/23 Q7(a)(ii); s25/23 Q6(a); s26/22 Q5(c)(i)
16 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Procedures that change their arguments

§11.3 · Structured programming · parameters passed by reference

Packing 130 items into boxes of 52 gives two answers, the full boxes and the spare items, but a function gives back only one value. A procedure gives values back through BYREF parameters: whatever it assigns to them is stored in the caller's variables.

A swap must use BYREF

Run both with A = 3 and B = 8. The two procedures are the same except for one keyword in the header.

Swap with BYREF: worksA = 3, B = 8 → 8 3
PROCEDURE Swap(BYREF X : INTEGER,
Y : INTEGER)
DECLARE Temp : INTEGER
Temp ← X
X ← Y
Y ← Temp
ENDPROCEDURE

CALL Swap(A, B)
OUTPUT A, " ", B
No keyword: by valueA = 3, B = 8 → 3 8
PROCEDURE Swap(X : INTEGER,
Y : INTEGER)
DECLARE Temp : INTEGER
Temp ← X
X ← Y
Y ← Temp
ENDPROCEDURE

CALL Swap(A, B)
OUTPUT A, " ", B

Without BYREF, X and Y are copies. Swap exchanges the copies, the copies are discarded when it ends, and A and B are unchanged. Make the change in the header: PROCEDURE Swap(BYREF X : INTEGER, Y : INTEGER).

  • Without BYREF, X and Y are copies: Swap exchanges the copies, which are discarded when it ends.
  • A and B are unchanged. Make the change in the header: PROCEDURE Swap(BYREF X : INTEGER, Y : INTEGER).

See the call: copies in, links back

Some parameters arrive as copies; others are links back to the caller's variables. Follow each argument across: a single arrow is a copy, a double line is BYREF.

CallerCALL Split(130, 52, Boxes, Spare)Split runsthe value130130Itemscopied inthe value5252Sizecopied inBoxes22FullFull ← Items DIV SizeBYREF: one locationSpare2626RestRest ← Items MOD SizeBYREF: one locationSplit stores 2 in Full and 26 in Rest, so after the call the caller has Boxes = 2 and Spare = 26.
Statement runFull = BoxesRest = Spare
Full ← Items DIV Size2
Rest ← Items MOD Size26
back in the callerBoxes = 2Spare = 26

Pass back more than one result

Run it with 130 and 52, then follow Full and Rest back into Boxes and Spare.

Two results passed backoutputs 2 full, 26 left over
PROCEDURE Split(Items : INTEGER, Size : INTEGER,
BYREF Full : INTEGER,
BYREF Rest : INTEGER)
Full ← Items DIV Size
Rest ← Items MOD Size
ENDPROCEDURE

DECLARE Boxes, Spare : INTEGER
CALL Split(130, 52, Boxes, Spare)
OUTPUT Boxes, " full, ", Spare, " left over"
Statement runFull = BoxesRest = Spare
Full ← Items DIV Size2
Rest ← Items MOD Size26
back in the callerBoxes = 2Spare = 26

Function, or procedure with BYREF?

  • One return value: a function, used in an expression. That value can be a record with several fields.
  • Several values, or a variable (or an array) to update in place: a procedure with BYREF parameters.
  • The argument for a BYREF parameter must be a variable: Split(130, 52, Boxes, Spare) can pass 130 by value, but Boxes must be a variable.
Two results passed backoutputs 2 full, 26 left over
PROCEDURE Split(Items : INTEGER, Size : INTEGER,
BYREF Full : INTEGER,
BYREF Rest : INTEGER)
Full ← Items DIV Size
Rest ← Items MOD Size
ENDPROCEDURE

DECLARE Boxes, Spare : INTEGER
CALL Split(130, 52, Boxes, Spare)
OUTPUT Boxes, " full, ", Spare, " left over"

Function, or procedure with BYREF?

  • One return value: a function, used in an expression. That value can be a record with several fields.
  • Several values, or a variable (or an array) to update in place: a procedure with BYREF parameters.
  • The argument for a BYREF parameter must be a variable: Split(130, 52, Boxes, Spare) can pass 130 by value, but Boxes must be a variable.
Your turn

1 What does the program output when the call is CALL Split(75, 20, Boxes, Spare)?

2 A is 5 and B is 1. What does the swap without BYREF output?

3 Why can the call not be CALL Split(130, 52, 0, Spare)?

  1. 1
    3 full, 15 left over
  2. 2
    5 1: only the copies were swapped
  3. 3
    Full is BYREF, so its argument must be a variable that can store the result
Tick what you can do now
Exam focusWhen a procedure must change the caller's variables (a swap, an updated array), the header needs BYREF. A procedure that only uses the values it is given takes them by value.
Practise with s26/22 Q5(c)(i), (c)(ii); w24/22 Q2(b)(ii); s25/23 Q6(b); s24/21 Q7(b)(ii)
17 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Headers, interfaces and scope

§11.3 · Structured programming · terminology

To use someone else's module you need only its first line, which says what goes in and what comes out. That line is the header, and what it lets in and out is the interface. Inside the program, each variable has a scope: the part of the program where it can be used.

Read the header from its name to its return type, then the call under it: each argument lines up with one parameter.

FUNCTION CheckNum(Number : INTEGER, Total : INTEGER) RETURNS BOOLEANidentifierparameters, each with its data typereturn typeinterface: parameters (number, order, types) and return typeValid ← CheckNum(142, 6)argumentsthe return value (TRUE or FALSE) replaces the call
Definition: parameters and return type
FUNCTION CheckNum(Number : INTEGER,
Total : INTEGER)
RETURNS BOOLEAN
PartValue
IdentifierCheckNum
ParametersNumber : INTEGER; Total : INTEGER
ReturnsBOOLEAN
Call: arguments 142 and 6, in order
Valid ← CheckNum(142, 6)
The Boolean result replaces CheckNum(142, 6) and is assigned to Valid.

Each term names one part of that drawing.

TermMeaning
Headerfirst line of the definition: identifier, parameters with types, and (functions only) return type
Interfacehow data passes in and out: the parameters (number, order, types, passing method) and return type
Parameteran identifier in the header that receives a value passed in; used like a variable inside
Argumentthe actual value or variable passed in the call: 142 and 6
Return valuethe single value a function sends back; it replaces the call in the expression

Write a header from a description

A header can be written from a description of the module alone. It needs the keyword, identifier, each parameter with its type, and RETURNS for a function.

Module descriptionHeader
takes a student ID; returns the number of loansFUNCTION CountLoans(StudentID : STRING) RETURNS INTEGER
takes a mark; outputs the gradePROCEDURE ShowGrade(Mark : INTEGER)
takes a price; sets a flag the caller usesPROCEDURE CheckPrice(Price : REAL, BYREF High : BOOLEAN)
no parameters; returns TRUE when readyFUNCTION Ready() RETURNS BOOLEAN

takes a student ID; returns the number of loans

Header
FUNCTION CountLoans(StudentID : STRING) RETURNS INTEGER

takes a mark; outputs the grade

Header
PROCEDURE ShowGrade(Mark : INTEGER)

takes a price; sets a flag the caller uses

Header
PROCEDURE CheckPrice(Price : REAL, BYREF High : BOOLEAN)

no parameters; returns TRUE when ready

Header
FUNCTION Ready() RETURNS BOOLEAN

Local and global variables

Where a variable is declared decides which modules can see it, and how long its value lasts.

Local variable

  • Declared inside a module and accessible only there. A new instance is created on each call, so earlier contents are lost; its memory is reused when the module is not running.
  • Names can be reused and it aids modularisation: reusing a local name cannot change data outside the module. Globals and BYREF arguments can still be changed deliberately.

Global variable

  • Declared in the main program; accessible to all parts of the program.
  • Uses memory for the whole time the program runs.
  • Any module can change it, so errors are harder to trace.
Your turn

1 Write the header for a module that takes a name and an age and returns TRUE if the person is old enough.

2 In Valid ← CheckNum(142, 6), name the arguments. Where are the parameters?

3 The main program sets a global Total ← 1. CALL Reset() runs Total ← 5 on a local Total. What does OUTPUT Total then show?

  1. 1
    FUNCTION OldEnough(Name : STRING, Age : INTEGER) RETURNS BOOLEAN
  2. 2
    142 and 6; the parameters Number and Total are in the header
  3. 3
    1: Reset changed its own local Total, not the global one
Tick what you can do now
Exam focusThe parameter is in the header; the argument is in the call. A header needs the keyword, the identifier, each parameter with its type in order, BYREF where needed and, for a function only, RETURNS <type>.
Practise with s25/23 Q6(b); s24/21 Q7(b)(ii); w25/22 Q7(b); w25/23 Q1(b)(ii); s25/23 Q1(a)(ii), (a)(iii)
18 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Writing efficient pseudocode

§11.3 · Structured programming · efficient pseudocode

Two programs can give the same answer while one does far more work to get there. Efficient pseudocode does all the task requires and no unnecessary work.

Each row names a kind of wasted work and how to avoid it. The first two are worked through in code.

TechniqueWhat it avoids
Work out an unchanging value once, before the looprepeating a calculation or call every time
Stop once the answer is known: a conditional loop (or flag), or RETURN from inside the loopiterations after the item is found
Use ELSE or CASE for conditions that exclude each othertesting conditions that cannot be true
Remove statements that can never rune.g. OTHERWISE after CASE OF (N MOD 2)
Replace several statements with one expressione.g. N ← (N MOD 3) + 1 for an add and an IF
Write a repeated task once as a moduleduplicated code, where copies can differ

Move a repeated calculation out of the loop

Count the a's in "BANANA SPLIT": the first version converts Ch on all 12 passes, the second only once.

Before: TO_UPPER runs 12 times
Count ← 0
FOR i ← 1 TO LENGTH(Word)
IF MID(Word, i, 1) = TO_UPPER(Ch) THEN
Count ← Count + 1
ENDIF
NEXT i
After: TO_UPPER runs once"BANANA SPLIT", 'a' → 3
Count ← 0
Target ← TO_UPPER(Ch)
FOR i ← 1 TO LENGTH(Word)
IF MID(Word, i, 1) = Target THEN
Count ← Count + 1
ENDIF
NEXT i

Stop as soon as the answer is known

Stop at the first digitCode ← "Room 7B, level 3"
Found ← FALSE
i ← 1
WHILE i <= LENGTH(Code) AND NOT Found
IF IS_NUM(MID(Code, i, 1)) THEN
Found ← TRUE
ENDIF
i ← i + 1
ENDWHILE

The first digit is at position 6, so the loop makes 6 tests. A FOR loop over the whole string would make all 16, even after the answer is known.

Preserve the stopping rule

Counting every matching character still requires all 12 character tests, even after TO_UPPER moves outside the loop. The separate first-digit search stops after 6 tests because its result is then known. Stop early only when the task allows it.

Preserve the stopping rule

  • Counting every match still needs all 12 character tests, even with TO_UPPER outside the loop.
  • The first-digit search can stop after 6 tests: its result is then known.
  • Stop early only when the task allows it.

Trace the search

One row for each character tested: the loop stops as soon as Found is TRUE.

iMID(Code, i, 1)FoundWhat decided it
test 11'R'not a digit
not a digit
test 22'o'not a digit
not a digit
test 33'o'not a digit
not a digit
test 44'm'not a digit
not a digit
test 55' 'a space: not a digit
a space: not a digit
test 66'7'TRUEa digit: Found ← TRUE
a digit: Found ← TRUE
endNOT Found is FALSE: the loop stops after 6 tests, not 16
NOT Found is FALSE: the loop stops after 6 tests, not 16
Your turn

1 How many tests does the first-digit search make when Code is "AB12"?

2 In FOR i ← 1 TO 100 the loop body contains Rate ← Price * 0.2, and Price never changes. What would you change, and why?

3 Why can a count of matching characters not stop early?

  1. 1
    3: the first digit is at position 3
  2. 2
    move Rate ← Price * 0.2 before the loop: it is worked out once, not 100 times
  3. 3
    every character must be tested to know the count
Tick what you can do now
Exam focusFor a search, stop when its result is known. For repeated calculations, identify what remains unchanged and move that work outside the loop. Explain which work is avoided.
Practise with s24/23 Q5(b); s25/22 Q7(a); s24/22 Q5(a)(ii)
19 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Writing a module from its description

§11.3 · Structured programming · putting it together

Real tasks are often two modules working together: one answers a small question, the other uses the answer. IsValid decides whether one product code is valid; CheckCodes counts the valid codes as they are typed in, and stops before it processes END.

IsValid()

  • takes a string representing a product code
  • returns TRUE if the code is 5 characters long and its last 3 characters represent a number, otherwise returns FALSE

CheckCodes()

  • repeatedly inputs a code until "END" is input
  • uses IsValid() to check each code
  • outputs the number of valid codes, with a message

The code is built from these two descriptions, phrase by phrase: "5 characters long" becomes line 2, and the stop at "END" becomes line 14.

Function and caller
 1FUNCTION IsValid(Code : STRING) RETURNS BOOLEAN
 2IF LENGTH(Code) <> 5 THEN
 3RETURN FALSE
 4ENDIF
 5RETURN IS_NUM(RIGHT(Code, 3))
 6ENDFUNCTION
 7
 8PROCEDURE CheckCodes()
 9DECLARE NextCode : STRING
10DECLARE Count : INTEGER
11Count ← 0
12OUTPUT "Enter a code, or END to finish"
13INPUT NextCode
14WHILE NextCode <> "END"
15IF IsValid(NextCode) THEN
16Count ← Count + 1
17ENDIF
18INPUT NextCode
19ENDWHILE
20OUTPUT Count, " valid codes"
21ENDPROCEDURE
22
23CALL CheckCodes()

Follow the actual rejection paths

1
XY9 has length 3: IsValid returns FALSE before RIGHT is called.
2
CD45E has length 5, but its final three characters are not numeric: FALSE.
3
AB123 and ZZ007 pass both checks, so the caller increments Count twice.
4
END ends the caller's loop. It is never sent to IsValid.
NextCodeIsValid()Count
"AB123"TRUE1
"XY9"FALSE1
"CD45E"FALSE1
"ZZ007"TRUE2
"END"–2

Follow the actual rejection paths

  1. 1
    XY9 has length 3: IsValid returns FALSE before RIGHT is called.
  2. 2
    CD45E has length 5, but its last three characters are not a number: FALSE.
  3. 3
    AB123 and ZZ007 pass both checks: the caller adds 1 to Count twice.
  4. 4
    END ends the caller's loop. It is never sent to IsValid.

Trace the module and its caller

For each code the trace jumps into the function and comes back with TRUE or FALSE. Follow each call there and back.

The pass for "CD45E", line by line
The call goes into IsValid and comes back with FALSE.
LineStatement that runsNextCodeIsValid()CountOutputWritesWhat happens
14WHILE NextCode <> "END"test "CD45E" is not "END": go into the loop
test "CD45E" is not "END": go into the loop
15IF IsValid(NextCode) THENtest calls IsValid with Code ← "CD45E"
test calls IsValid with Code ← "CD45E"
2IF LENGTH(Code) <> 5 THENtest LENGTH is 5: FALSE, so carry on to line 5
test LENGTH is 5: FALSE, so carry on to line 5
5RETURN IS_NUM(RIGHT(Code, 3))FALSEIsValid() FALSERIGHT gives "45E", which is not a number
RIGHT gives "45E", which is not a number
18INPUT NextCode"ZZ007"NextCode "ZZ007"line 16 was skipped: Count stays the same
line 16 was skipped: Count stays the same

The whole run

NextCodeIsValid()CountOutputWhat decided it
start"AB123"0lines 11–13: Count starts at 0; the first code is input
lines 11–13: Count starts at 0; the first code is input
"AB123""XY9"TRUE1length 5; "123" is a number: TRUE, so Count + 1; line 18 inputs "XY9"
length 5; "123" is a number: TRUE, so Count + 1; line 18 inputs "XY9"
"XY9""CD45E"FALSElength 3, not 5: line 3 returns FALSE; line 18 inputs "CD45E"
length 3, not 5: line 3 returns FALSE; line 18 inputs "CD45E"
"CD45E""ZZ007"FALSElength 5, but "45E" is not a number: FALSE; line 18 inputs "ZZ007"
length 5, but "45E" is not a number: FALSE; line 18 inputs "ZZ007"
"ZZ007""END"TRUE2length 5; "007" is a number: TRUE, so Count + 1; line 18 inputs "END"
length 5; "007" is a number: TRUE, so Count + 1; line 18 inputs "END"
end2 valid codesNextCode is "END": the loop ends, and END is never sent to IsValid
NextCode is "END": the loop ends, and END is never sent to IsValid
Use the returned Boolean in IF, without CALL. Stop before processing END, and make every path through IsValid return a Boolean.
Your turn

1 The inputs are QR500, QR5, Q1234, END. What is output last?

2 The first input is END. What is output last, and is IsValid ever called?

3 Why is the result of IsValid used inside IF, and never with CALL?

  1. 1
    2 valid codes: QR500 and Q1234 are valid; QR5 is too short
  2. 2
    0 valid codes; no, the loop never runs
  3. 3
    IsValid is a function: its returned Boolean is a value used in the condition
Tick what you can do now
Practise with s24/23 Q8(a); w24/22 Q2(a); s25/23 Q6(a)
20 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

A function that outputs samples and returns a mean

§11.3 · Structured programming · parameters, random values and RETURN

A test rig might try several random loads, show each one, and report the average. A function can output values as it runs and return one value: each random load from 10 to 20 is output, and the mean of the loads is returned.

Trials is a positive INTEGER supplied by the caller.

Output each sample; return the mean
FUNCTION SampleLoads(Trials : INTEGER) RETURNS REAL
DECLARE Index, Load, Total : INTEGER
Total ← 0
FOR Index ← 1 TO Trials
Load ← 10 + INT(RAND(11))
OUTPUT Load
Total ← Total + Load
NEXT Index
RETURN Total / Trials
ENDFUNCTION

DECLARE MeanLoad : REAL
MeanLoad ← SampleLoads(4)
OUTPUT "Mean: ", MeanLoad

One possible run

IndexLoadTotal
11010
21424
32044
41256
Output
10
14
20
12
Mean: 14.0

Same contract, varying data

RAND(11) can return 0 but never 11. INT therefore gives 0–10; adding 10 gives 10–20 inclusive. These four loads are one possible run, not a fixed random sequence.

Output each sample; return the mean
FUNCTION SampleLoads(Trials : INTEGER) RETURNS REAL
DECLARE Index, Load, Total : INTEGER
Total ← 0
FOR Index ← 1 TO Trials
Load ← 10 + INT(RAND(11))
OUTPUT Load
Total ← Total + Load
NEXT Index
RETURN Total / Trials
ENDFUNCTION

DECLARE MeanLoad : REAL
MeanLoad ← SampleLoads(4)
OUTPUT "Mean: ", MeanLoad

Same contract, varying data

  • RAND(11) can return 0 but never 11, so INT gives 0–10; adding 10 gives 10–20 inclusive.
  • These four loads are one possible run, not a fixed random sequence.

Trace one possible run

Follow Total down its column: each load is added in, and RETURN divides the total by Trials.

LoadTotalOutputWhat decided it
Index 1101010INT(RAND(11)) gave 0: 10 + 0 = 10
INT(RAND(11)) gave 0: 10 + 0 = 10
Index 2142414INT(RAND(11)) gave 4: 10 + 4 = 14
INT(RAND(11)) gave 4: 10 + 4 = 14
Index 3204420INT(RAND(11)) gave 10: 10 + 10 = 20
INT(RAND(11)) gave 10: 10 + 10 = 20
Index 4125612INT(RAND(11)) gave 2: 10 + 2 = 12
INT(RAND(11)) gave 2: 10 + 2 = 12
returnRETURN 56 / 4 = 14.0: the value goes back to MeanLoad
RETURN 56 / 4 = 14.0: the value goes back to MeanLoad
endMean: 14.0the main program outputs the returned mean
the main program outputs the returned mean
OUTPUT Load runs inside the loop. RETURN Total / Trials runs after all trials and sends a value back to MeanLoad. Trials > 0 prevents division by zero.
Your turn

1 SampleLoads(3) gives loads of 15, 11 and 19. What is output?

2 What are the smallest and largest loads 10 + INT(RAND(11)) can give?

3 Which statement sends the mean back, and where does it go?

  1. 1
    15, 11, 19, then Mean: 15.0
  2. 2
    10 and 20
  3. 3
    RETURN Total / Trials; it goes to MeanLoad, where the call was
Tick what you can do now
Practise with s25/23 Q3
21 / 22
9618 · Unit 11 · Programming
Revisionbyexamplicity

Returning a record from a function

§11.3 · Structured programming · one return value, several fields

Popping an empty stack leaves nothing to give back, so the caller needs two answers: whether a value exists and, if it does, the value. A record is one return value with several fields, so Pop returns a record holding both.

The stack has eight slots: Top is the last live index, 0 means empty. Initially Stack[1..3] holds 31, 12, 47 and Top = 3; all other slots are unused.

Record type and global stack
TYPE PopResult
DECLARE Data : INTEGER
DECLARE Exists : BOOLEAN
ENDTYPE
DECLARE Stack : ARRAY[1:8] OF INTEGER
DECLARE Top : INTEGER
Assign fields of the Result variable
FUNCTION Pop() RETURNS PopResult
DECLARE Result : PopResult
IF Top = 0 THEN
Result.Exists ← FALSE
ELSE
Result.Data ← Stack[Top]
Result.Exists ← TRUE
Top ← Top - 1
ENDIF
RETURN Result
ENDFUNCTION
Caller checks Exists before Data
DECLARE Taken : PopResult
DECLARE Count : INTEGER
FOR Count ← 1 TO 4
Taken ← Pop()
IF Taken.Exists THEN
OUTPUT Taken.Data
ELSE
OUTPUT "Empty"
ENDIF
NEXT Count
CallDataExistsTop after
147TRUE2
212TRUE1
331TRUE0
4not usedFALSE0
Record type and global stack
TYPE PopResult
DECLARE Data : INTEGER
DECLARE Exists : BOOLEAN
ENDTYPE
DECLARE Stack : ARRAY[1:8] OF INTEGER
DECLARE Top : INTEGER
Assign fields of the Result variable
FUNCTION Pop() RETURNS PopResult
DECLARE Result : PopResult
IF Top = 0 THEN
Result.Exists ← FALSE
ELSE
Result.Data ← Stack[Top]
Result.Exists ← TRUE
Top ← Top - 1
ENDIF
RETURN Result
ENDFUNCTION
Caller checks Exists before Data
DECLARE Taken : PopResult
DECLARE Count : INTEGER
FOR Count ← 1 TO 4
Taken ← Pop()
IF Taken.Exists THEN
OUTPUT Taken.Data
ELSE
OUTPUT "Empty"
ENDIF
NEXT Count
  • PopResult names the type. Result is the local record variable that RETURN sends back.
  • If Exists is FALSE, Data is not assigned: the caller must not read it.
  • Popped array cells may keep stale values above Top.

Trace the four calls

Each call takes the value at Top and moves Top down one. Follow Top to 0: the fourth call has nothing to give back.

DataExistsTop afterOutputWhat decided it
call 147TRUE247Top was 3: Data ← Stack[3]; Top − 1
Top was 3: Data ← Stack[3]; Top − 1
call 212TRUE112Top was 2: Data ← Stack[2]; Top − 1
Top was 2: Data ← Stack[2]; Top − 1
call 331TRUE031Top was 1: Data ← Stack[1]; Top − 1
Top was 1: Data ← Stack[1]; Top − 1
call 4not usedFALSE0EmptyTop is 0: only Exists is set; the caller outputs Empty
Top is 0: only Exists is set; the caller outputs Empty
PopResult names the type. Result is the local record variable whose fields are assigned and which RETURN sends back. If Exists is FALSE, Data is not assigned and the caller must not read it. Popped array cells may retain stale values above Top.
Your turn

1 Stack[1] holds 8 and Top is 1. The caller's loop runs twice. What is output?

2 Why does the caller test Taken.Exists before it outputs Taken.Data?

3 A function can return only one value. How does Pop return two things?

  1. 1
    8, then Empty
  2. 2
    when Exists is FALSE, Data was never assigned
  3. 3
    it returns one record whose two fields hold them
Tick what you can do now
Practise with w25/23 Q3; w24/21 Q4(c)
22 / 22