Variables, constants and data types
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.
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.2is valid,CONSTANT Rate = Price / 5is 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.
| INTEGER | REAL | CHAR | STRING | BOOLEAN | DATE | |
|---|---|---|---|---|---|---|
| Holds | a whole number | a number with a fractional part | exactly one character | zero or more characters | a logical value | a calendar date |
| Literals | 25 -3 | 4.7 0.0 | 'x' ' ' | "Hall 2" "" | TRUE FALSE | 02/01/2025 |
| Type | Holds | Literals |
|---|---|---|
| INTEGER | a whole number | 25 -3 |
| REAL | a number with a fractional part | 4.7 0.0 |
| CHAR | exactly one character | 'x' ' ' |
| STRING | zero or more characters | "Hall 2" "" |
| BOOLEAN | a logical value | TRUE FALSE |
| DATE | a calendar date | 02/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:
AorX2hide the purpose, so the program is harder to understand, debug and maintain.
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
CONSTANT MaxSeats = 40 - 2REAL; CHAR; BOOLEAN
- 3
How many tickets?, then4 tickets cost $29.0
= and a literal: CONSTANT MaxTickets = 6.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.
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.
X ← 4 Y ← X * 3 X ← Y - X Y ← Y + X OUTPUT X, " ", Y
Temp ← First First ← Second Second ← Temp
| Statement | X | Y | Output |
|---|---|---|---|
| X ← 4 | 4 | ||
| Y ← X * 3 | 12 | ||
| X ← Y - X | 8 | ||
| Y ← Y + X | 20 | ||
| OUTPUT X, " ", Y | 8 20 |
Temp keeps the old value of First. Without it, First ← Second overwrites "Ann" and both variables end as "Bo".
X ← 4 Y ← X * 3 X ← Y - X Y ← Y + X OUTPUT X, " ", Y
Temp ← First First ← Second Second ← Temp
Tempkeeps the old value ofFirst.- Without it,
First ← Secondoverwrites "Ann" and both variables end as "Bo".
| Line | Statement that runs | X | Y | Output | Writes | What happens |
|---|---|---|---|---|---|---|
| 1 | X ← 4 | 4 | X 4 | store 4 in X | ||
| store 4 in X | ||||||
| 2 | Y ← X * 3 | 12 | Y 12 | 4 × 3 = 12: X is read, not changed | ||
| 4 × 3 = 12: X is read, not changed | ||||||
| 3 | X ← Y - X | 8 | X 8 | 12 − 4 = 8: the old X is used, then replaced | ||
| 12 − 4 = 8: the old X is used, then replaced | ||||||
| 4 | Y ← Y + X | 20 | Y 20 | 12 + 8 = 20: the new X is used | ||
| 12 + 8 = 20: the new X is used | ||||||
| 5 | OUTPUT X, " ", Y | 8 20 | Output 8 20 | X, 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.
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"
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: " & Fenceis a type error, so useNUM_TO_STR(Fence).
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?
- 1A = 35, B = 7
- 2
Temp ← Left,Left ← Right,Right ← Temp - 3the left-hand side must be one variable: the value is stored there
← assigns and = compares: IF Reply ← "Y" THEN is an error. When a prompt is required, use an OUTPUT message before INPUT into the variable.Arithmetic expressions
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.
| Operator | Meaning | Example |
|---|---|---|
+ - * | add, subtract, multiply | 17 * 5 → 85 |
/ | divide: always gives a REAL | 17 / 5 → 3.4; 10 / 5 → 2.0 |
DIV | whole-number quotient | 17 DIV 5 → 3 |
MOD | remainder after division | 17 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.
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.
| Task | Expression | Example |
|---|---|---|
| is N even? | N MOD 2 = 0 | 64 → TRUE |
| last digit; the rest | N MOD 10; N DIV 10 | 4721 → 1; 472 |
| hours and minutes | T DIV 60; T MOD 60 | 135 → 2 h 15 min |
| containers needed | (Items + Size - 1) DIV Size | 130, 52 → 3 |
Is N even?
Test N MOD 2 = 0.
64 MOD 2 = 0 → TRUE
Last digit and the rest
Use N MOD 10 and N DIV 10.
4721 MOD 10 = 1 4721 DIV 10 = 472
Hours and minutes
Use T DIV 60 and T MOD 60.
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.
(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.
| Expression | Data type | Why |
|---|---|---|
Total * 2 | INTEGER | integer × integer (REAL if Total is REAL) |
Total / 4 | REAL | / always gives a REAL: 3.0 |
LEFT(Name, 1) | STRING | LEFT returns a STRING (CHAR accepted for one character) |
"FALSE" | STRING | anything in double quotes is text |
Total > 10 AND NOT Done | BOOLEAN | comparisons and logic operators give TRUE or FALSE |
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.
- 15 and 3
- 2
Days DIV 7(for 23 days: 3) - 34.5, REAL:
/always gives a REAL
/ 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.Boolean expressions
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.
| A | B | A AND B | A OR B | NOT A |
|---|---|---|---|---|
| FALSE | FALSE | FALSE | FALSE | TRUE |
| FALSE | TRUE | FALSE | TRUE | TRUE |
| TRUE | FALSE | FALSE | TRUE | FALSE |
| TRUE | TRUE | TRUE | TRUE | FALSE |
With Score ← 64, Member ← TRUE and Late ← FALSE:
| Expression | Value |
|---|---|
(Score > 50) AND NOT Late | TRUE |
(Score MOD 2 = 0) OR Late | TRUE |
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) |
|---|---|---|
| 12 | FALSE | TRUE |
| 13 | TRUE | FALSE |
| 19 | TRUE | FALSE |
| 20 | FALSE | TRUE |
(Age >= 13) AND (Age <= 19)
(Age < 13) OR (Age > 19)
| Age | Inside | Outside |
|---|---|---|
| 12 | FALSE | TRUE |
| 13 | TRUE | FALSE |
| 19 | TRUE | FALSE |
| 20 | FALSE | TRUE |
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 as | Simpler, same result | Reason |
|---|---|---|
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 Locked | NOT Locked | Ready OR NOT Ready is always TRUE |
| CanBook is TRUE only when SeatsFree and Paid are both TRUE | CanBook ← SeatsFree AND Paid | a condition is a value: assign it |
Equivalent condition
NOT ((Ch < 'a') OR (Ch > 'z'))
(Ch >= 'a') AND (Ch <= 'z')
NOT of an OR: AND the opposites
Equivalent condition
NOT (Dots >= 1 AND Ats = 1)
(Dots < 1) OR (Ats <> 1)
NOT of an AND: OR the opposites
Equivalent condition
(Ready OR NOT Ready) AND NOT Locked
NOT Locked
Ready OR NOT Ready is always TRUE
Store the condition
CanBook is TRUE only when SeatsFree and Paid are both TRUE
CanBook ← SeatsFree AND Paid
a condition is a value: assign it
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.
- 1TRUE
- 2TRUE
- 3
(Age < 18) OR (Age > 65)
"Yes" = "YES" is FALSE.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.
| Insert function | Returns | Example | Value |
|---|---|---|---|
| LEFT(ThisString, x) | STRING: leftmost x characters | LEFT(Code, 3) | "MAR" |
| RIGHT(ThisString, x) | STRING: rightmost x characters | RIGHT(Code, 2) | "X7" |
| MID(ThisString, x, y) | STRING: y characters from x | MID(Code, 5, 4) | "2026" |
| LENGTH(ThisString) | INTEGER: number of characters | LENGTH(Code) | 11 |
| TO_UPPER(x) TO_LOWER(x) | the type of x: CHAR or STRING | TO_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.
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
MID(Text, Index, 1)picks out one character. - 2A new word starts where the character before it is a space: positions 5 and 11.
- 3Words 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()andTO_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.
| Line | Statement that runs | Index | Letter | Initials | Writes | What happens |
|---|---|---|---|---|---|---|
| 6 | FOR Index ← 2 TO LENGTH(Text) | 5 | Index 5 | the next position | ||
| the next position | ||||||
| 7 | IF MID(Text, Index - 1, 1) = ' ' THEN | test MID(Text, 4, 1) is ' ': TRUE | ||||
| test MID(Text, 4, 1) is ' ': TRUE | ||||||
| 8 | Letter ← MID(Text, Index, 1) | 'b' | Letter 'b' | the character at position 5 | ||
| the character at position 5 | ||||||
| 9 | Initials ← Initials & TO_UPPER(Letter) | "AB" | Initials "AB" | "A" & 'B' | ||
| "A" & 'B' | ||||||
The whole run
| Index | Letter | Initials | What decided it | |
|---|---|---|---|---|
| start | "A" | line 5: the first letter, in capitals | ||
| line 5: the first letter, in capitals | ||||
| Index 2–4 | 2–4 | the character before is not a space: nothing added | ||
| the character before is not a space: nothing added | ||||
| Index 5 | 5 | 'b' | "AB" | position 4 is a space: add B |
position 4 is a space: add B | ||||
| Index 6–10 | 6–10 | the character before is not a space: nothing added | ||
| the character before is not a space: nothing added | ||||
| Index 11 | 11 | 'l' | "ABL" | position 10 is a space: add L |
position 10 is a space: add L | ||||
| Index 12–18 | 12–18 | the character before is not a space: nothing added | ||
| the character before is not a space: nothing added | ||||
| end | the loop ends after Index 18: output ABL | |||
the loop ends after Index 18: output ABL | ||||
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"KL", "0451", 9
- 2SL
- 3only 2 characters start at position 8, so there are not 3 to return
LEFT(Code, 3) gives "MAR". Spell function names exactly as the insert does: TO_UPPER, not UPPER.Conversion, numeric and random 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 function | Returns | Example | Value |
|---|---|---|---|
| NUM_TO_STR(x) | STRING; x is INTEGER or REAL | NUM_TO_STR(87.5) | "87.5" |
| STR_TO_NUM(x) | INTEGER or REAL; x is a string | STR_TO_NUM("2026") + 1 | 2027 |
| IS_NUM(ThisString) | BOOLEAN: is it a valid number? | IS_NUM("-12.5"), IS_NUM("X7") | TRUE, FALSE |
| ASC(ThisChar) | INTEGER: the ASCII value | ASC('A'), ASC('7') | 65, 55 |
| CHR(x) | CHAR with ASCII value x | CHR(ASC('A') + 2) | 'C' |
| INT(x : REAL) | INTEGER part, not rounded | INT(9.99), INT(7 / 2) | 9, 3 |
| RAND(x : INTEGER) | REAL, 0 to x, not including x | RAND(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
'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.
Random whole numbers
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
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.
- 17 and 42
- 25 and 14: RAND(10) never reaches 10
- 3
INT(RAND(50)) + 1
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.Library routines
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 STRING
| Part | Meaning |
|---|---|
| MID | routine identifier |
| ThisString : STRING | first parameter: source text |
| x : INTEGER | second: starting position |
| y : INTEGER | third: character count |
| RETURNS STRING | type sent back to caller |
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)whenNis 0: division by zero.RIGHT(Label, 9)whenLabelhas fewer than 9 characters.STR_TO_NUM(Entry)whenEntryis "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.
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".
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
LEFTkeeps the first 8 characters;RIGHTkeeps the last 4 of those. - 2MyMid assumes a valid start and count: 1 ≤ x and x + y − 1 ≤ LENGTH(Str).
| Line | Statement that runs | Str, x, y | Front | Returns | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 8 | OUTPUT MyMid("MAR-2026-X7", 5, 4) | "MAR-2026-X7", 5, 4 | Str, x, y "MAR-2026-X7", 5, 4 | the call: the values are copied into the parameters, in order | |||
| the call: the values are copied into the parameters, in order | |||||||
| 4 | Front ← 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 | |||||||
| 5 | RETURN RIGHT(Front, y) | "2026" | Returns "2026" | the last 4 of those | |||
| the last 4 of those | |||||||
| 8 | OUTPUT MyMid("MAR-2026-X7", 5, 4) | 2026 | Output 2026 | the returned value replaces the call | |||
| the returned value replaces the call | |||||||
MONTH(04/03/2025) is 3, and DAYINDEX(04/03/2025) is 3 because that date is a Tuesday (Sunday is 1).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.
- 14: for
S ← "PLANET"both give "AN" - 2"INT"
- 3it is tried and tested, so less likely to contain errors; it is readily available, so development is faster
From a design to pseudocode
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.
1Count ← 0 2INPUT Value 3WHILE Value <> -1 4IF Value > 100 THEN 5Count ← Count + 1 6ENDIF 7INPUT Value 8ENDWHILE 9OUTPUT Count
| Flowchart | Pseudocode |
|---|---|
| decision, paths join below | IF … ELSE … ENDIF |
| decision, a path back up | WHILE or REPEAT … UNTIL |
| a counter loop | FOR … 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.
| Line | Statement that runs | Value | Count | Output | Writes | What happens |
|---|---|---|---|---|---|---|
| 3 | WHILE Value <> -1 | test 101 <> −1 is TRUE: go into the loop | ||||
| test 101 <> −1 is TRUE: go into the loop | ||||||
| 4 | IF Value > 100 THEN | test 101 > 100 is TRUE | ||||
| test 101 > 100 is TRUE | ||||||
| 5 | Count ← Count + 1 | 2 | Count 2 | 1 + 1 | ||
| 1 + 1 | ||||||
| 7 | INPUT Value | 100 | Value 100 | the next value | ||
| the next value | ||||||
The whole run
| Value | Count | Output | What decided it | |
|---|---|---|---|---|
| start | 150 | 0 | line 1 sets Count; line 2 inputs the first value | |
| line 1 sets Count; line 2 inputs the first value | ||||
| pass 1 | 80 | 1 | 150 > 100: add 1; line 7 inputs 80 | |
| 150 > 100: add 1; line 7 inputs 80 | ||||
| pass 2 | 101 | 80 > 100 is false: Count unchanged; line 7 inputs 101 | ||
| 80 > 100 is false: Count unchanged; line 7 inputs 101 | ||||
| pass 3 | 100 | 2 | 101 > 100: add 1; line 7 inputs 100 | |
| 101 > 100: add 1; line 7 inputs 100 | ||||
| pass 4 | -1 | 100 > 100 is false: Count unchanged; line 7 inputs -1 | ||
| 100 > 100 is false: Count unchanged; line 7 inputs -1 | ||||
| end | 2 | Value 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
“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).
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
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?
- 12: only 120 and 300 are over 100
- 2a loop:
WHILEorREPEAT … UNTIL - 3the loop stops when either is true: the PIN is right, or the third try is used
WHILE Value <> -1.Selection with 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.
| Construct | In pseudocode | Its use, described for the task |
|---|---|---|
| Sequence | statements run one after another | “so Wanted is input before Cost is calculated” |
| Selection | IF … ENDIF, CASE … ENDCASE | “to test Mark against 50 and set Pass or Fail” |
| Iteration | FOR, 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 Temperature > 30 THEN OUTPUT "Warning: hot" ENDIF
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 … THENon one line;ELSEandENDIFline up withIF.- Indent the statements inside three spaces.
- Every IF, nested ones too, has its own ENDIF.
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
| Line | Statement that runs | Grade | Writes | What happens |
|---|---|---|---|---|
| 1 | IF Mark >= 70 THEN | test 54 >= 70 is FALSE: go to its ELSE | ||
| test 54 >= 70 is FALSE: go to its ELSE | ||||
| 4 | IF Mark >= 55 THEN | test 54 >= 55 is FALSE: go to its ELSE | ||
| test 54 >= 55 is FALSE: go to its ELSE | ||||
| 7 | IF Mark >= 40 THEN | test 54 >= 40 is TRUE: go into THEN | ||
| test 54 >= 40 is TRUE: go into THEN | ||||
| 8 | Grade ← '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 >= 40first 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.
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'A' (70 >= 70 is TRUE); 'U' (every test is FALSE)
- 2'C': 85 >= 40 is TRUE first, so the other tests never run
- 3selection: to test the mark against 50 and set Pass
Selection with CASE
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.
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.
| Line | Statement that runs | Copies | Output | Writes | What happens |
|---|---|---|---|---|---|
| 1 | CASE OF Choice | test Choice is 3 | |||
| test Choice is 3 | |||||
| 2 | 1 : OUTPUT "New booking" | test 3 = 1 is FALSE: test the next clause | |||
| test 3 = 1 is FALSE: test the next clause | |||||
| 3 | 2 : OUTPUT "Cancel a booking" | test 3 = 2 is FALSE: test the next clause | |||
| test 3 = 2 is FALSE: test the next clause | |||||
| 4 | 3 : OUTPUT "Print a receipt" | Print a receipt | Output Print a receipt | 3 = 3: match | |
| 3 = 3: match | |||||
| 5 | Copies ← Copies + 1 | 1 | Copies 1 | the 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
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
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, soPostage ← 3never runs: put<= 2first. - The last clause,
> 10, can be replaced byOTHERWISE. - After
CASE OF (N MOD 2)with clauses0and1, an OTHERWISE can never run.
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?
- 1Cancel a booking
- 28:
<= 10matches first - 33:
<= 2is now tested first
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.Count-controlled loops
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.
How many iterations?
The end value runs only if a step lands on it, so list the values before you count them.
| Loop | Values of i | Count |
|---|---|---|
| FOR i ← 1 TO 5 | 1, 2, 3, 4, 5 | 5 |
| FOR i ← 2 TO 11 STEP 3 | 2, 5, 8, 11 | 4 |
| FOR i ← 10 TO 1 STEP -4 | 10, 6, 2 | 3 |
| FOR i ← 4 TO 4 | 4 | 1 |
| FOR i ← 5 TO 4 | none | 0 |
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.
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.
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
* ** *** ****
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
Rowtimes: 1 + 2 + 3 + 4 = 10 iterations in all. Starsis 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.
| Line | Statement that runs | Row | Col | Stars | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 3 | FOR Row ← 1 TO 4 | 3 | Row 3 | the outer loop's next value | |||
| the outer loop's next value | |||||||
| 4 | Stars ← "" | "" | Stars "" | Stars starts empty for this row | |||
| Stars starts empty for this row | |||||||
| 5 | FOR Col ← 1 TO Row | 1 | Col 1 | the inner loop starts again at 1 | |||
| the inner loop starts again at 1 | |||||||
| 6 | Stars ← Stars & '*' | "*" | Stars "*" | add one star: 1 now | |||
| add one star: 1 now | |||||||
| 5 | FOR Col ← 1 TO Row | 2 | Col 2 | Col 2 of 3 | |||
| Col 2 of 3 | |||||||
| 6 | Stars ← Stars & '*' | "**" | Stars "**" | add one star: 2 now | |||
| add one star: 2 now | |||||||
| 5 | FOR Col ← 1 TO Row | 3 | Col 3 | Col 3 of 3 | |||
| Col 3 of 3 | |||||||
| 6 | Stars ← Stars & '*' | "***" | Stars "***" | add one star: 3 now | |||
| add one star: 3 now | |||||||
| 5 | FOR Col ← 1 TO Row | test Col has reached Row (3): the inner loop ends | |||||
| test Col has reached Row (3): the inner loop ends | |||||||
| 8 | OUTPUT Stars | *** | Output *** | one line of output | |||
| one line of output | |||||||
The whole run
| Row | Col | Stars | Output | What decided it | |
|---|---|---|---|---|---|
| Row 1 | 1 | 1 | "*" | * | the inner loop runs 1 time: Col takes 1 |
| the inner loop runs 1 time: Col takes 1 | |||||
| Row 2 | 2 | 12 | "**" | ** | the inner loop runs 2 times: Col takes 1, 2 |
| the inner loop runs 2 times: Col takes 1, 2 | |||||
| Row 3 | 3 | 123 | "***" | *** | the inner loop runs 3 times: Col takes 1, 2, 3 |
| the inner loop runs 3 times: Col takes 1, 2, 3 | |||||
| Row 4 | 4 | 1234 | "****" | **** | the inner loop runs 4 times: Col takes 1, 2, 3, 4 |
| the inner loop runs 4 times: Col takes 1, 2, 3, 4 | |||||
| end | Row has reached 4: the outer loop ends | ||||
| Row has reached 4: the outer loop ends | |||||
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?
- 13, 7, 11, 15: 4 iterations
- 220, 14, 8, 2
- 36: 3 × 2
FOR i ← 4 TO 20 STEP 4 runs 5 times. Do not change the loop variable inside the loop; repeat it after NEXT.Pre-condition and post-condition loops
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 … ENDWHILE
Run it with 12, 7, 5, 0: the 0 is the signal to stop, so it is never added.
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
| Pass | Value | Total | Count | Output |
|---|---|---|---|---|
| start | 12 | 0 | 0 | |
| 1 | 7 | 12 | 1 | |
| 2 | 5 | 19 | 2 | |
| 3 | 0 | 24 | 3 | |
| end | 3 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.
INPUT Value is removed, Value never changes: the terminating condition is never satisfied, so the loop is infinite.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.
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.
| Line | Statement that runs | Value | Total | Count | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 5 | WHILE Value <> 0 | test 7 <> 0 is TRUE: run the body | |||||
| test 7 <> 0 is TRUE: run the body | |||||||
| 6 | Total ← Total + Value | 19 | Total 19 | 12 + 7 | |||
| 12 + 7 | |||||||
| 7 | Count ← Count + 1 | 2 | Count 2 | 1 + 1 | |||
| 1 + 1 | |||||||
| 8 | INPUT Value | 5 | Value 5 | the next value; then back to line 5 | |||
| the next value; then back to line 5 | |||||||
The whole run
| Value | Total | Count | Output | What decided it | |
|---|---|---|---|---|---|
| start | 12 | 0 | 0 | lines 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 1 | 7 | 12 | 1 | 12 <> 0: add 12 to Total; line 8 inputs 7 | |
| 12 <> 0: add 12 to Total; line 8 inputs 7 | |||||
| pass 2 | 5 | 19 | 2 | 7 <> 0: add 7 to Total; line 8 inputs 5 | |
| 7 <> 0: add 7 to Total; line 8 inputs 5 | |||||
| pass 3 | 0 | 24 | 3 | 5 <> 0: add 5 to Total; line 8 inputs 0 | |
| 5 <> 0: add 5 to Total; line 8 inputs 0 | |||||
| end | 3 values, total 24 | 0 <> 0 is FALSE: the loop ends; line 10 outputs | |||
| 0 <> 0 is FALSE: the loop ends; line 10 outputs | |||||
REPEAT … UNTIL
DECLARE Quantity : INTEGER REPEAT OUTPUT "Enter a quantity from 1 to 8" INPUT Quantity UNTIL Quantity >= 1 AND Quantity <= 8
| Quantity | UNTIL condition | Then |
|---|---|---|
| 0 | FALSE | repeat |
| 9 | FALSE | repeat |
| 5 | TRUE | stop |
WHILE Value <> 0 or UNTIL Value = 0.DECLARE Quantity : INTEGER REPEAT OUTPUT "Enter a quantity from 1 to 8" INPUT Quantity UNTIL Quantity >= 1 AND Quantity <= 8
WHILE Value <> 0 or UNTIL Value = 0.Run it with 0, 9, 5: the prompt repeats until a quantity from 1 to 8 arrives.
| Quantity | UNTIL test | Then | |
|---|---|---|---|
| pass 1 | 0 | FALSE | 0 is out of range: back to REPEAT |
| 0 is out of range: back to REPEAT | |||
| pass 2 | 9 | FALSE | 9 is out of range: back to REPEAT |
| 9 is out of range: back to REPEAT | |||
| pass 3 | 5 | TRUE | in range: the loop stops |
| in range: the loop stops | |||
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?
- 12 values, total 13
- 2zero times: 0 values, total 0
- 32 times: 12 fails the test, 3 passes
Choosing the right loop
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.
| Stopping rule | Loop and reason |
|---|---|
| Known number of passes | FOR: loop variable visits a known range |
| Unknown count; body must run first | REPEAT: input/process before testing |
| Unknown count; may need zero passes | WHILE: 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.
| Loop | Choose it when… | Reason tied to the task |
|---|---|---|
| count-controlled | each character of Code; the ten random trials | the number of iterations is known (the length of the string) |
| pre-condition | the terminator might be the first value input | the number of iterations is not known; the terminator ends the loop; tested before the first pass |
| post-condition | input validation, a menu, a guessing game | the number of iterations is not known; the body must run at least once |
| conditional, not FOR | searching for the first match | the 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.
1Digits ← 0 2Index ← 1 3WHILE Index <= LENGTH(Code) 4IF IS_NUM(MID(Code, Index, 1)) THEN 5Digits ← Digits + 1 6ENDIF 7Index ← Index + 1 8ENDWHILE
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
Indexitself: lines 2 and 7 of the WHILE version are removed. - Lines 3 and 8 change to
FOR … TO LENGTH(Code)andNEXT Index.
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.
- 1count-controlled: the number of iterations is known (30)
- 2post-condition: the number of tries is not known, and the password must be input at least once
- 3
FOR Index ← 1 TO 10,Total ← Total + Index,NEXT Index: both give 55
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.
A procedure with parameters, one without
Run the three CALLs in order and match each one to a line of output.
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, '*')
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.
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###
- 2
CALL ShowLine(5, '-') - 3a procedure is run by a CALL statement; only a function is used without CALL, inside an expression
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”.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.
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.
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>. RETURNsends 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.
| Line | Statement that runs | People | Full | Returns | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 11 | OUTPUT "Coaches: ", Coaches(130) | 130 | People 130 | the call: 130 is copied into the parameter People | |||
| the call: 130 is copied into the parameter People | |||||||
| 3 | Full ← People DIV 52 | 2 | Full 2 | 130 DIV 52 | |||
| 130 DIV 52 | |||||||
| 4 | IF People MOD 52 > 0 THEN | test 130 MOD 52 = 26, and 26 > 0 is TRUE | |||||
| test 130 MOD 52 = 26, and 26 > 0 is TRUE | |||||||
| 5 | RETURN Full + 1 | 3 | Returns 3 | 2 + 1 is sent back; the function ends here | |||
| 2 + 1 is sent back; the function ends here | |||||||
| 11 | OUTPUT "Coaches: ", Coaches(130) | Coaches: 3 | Output Coaches: 3 | 3 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.
| Procedure | Function | |
|---|---|---|
| Purpose | carries out a task | calculates and returns a single value |
| Header | PROCEDURE Name(…) | FUNCTION Name(…) RETURNS <type> |
| How it is used | CALL Name(…): a statement on its own | in an expression: X ← Name(…) |
| Passing values back | through BYREF parameters | the return value; parameters are by value |
| Choose it when… | it outputs or updates, and returns nothing | the 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
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?
- 12: 104 MOD 52 = 0, so the second RETURN runs; 2: 53 DIV 52 = 1, plus 1
- 2a function is used inside an expression:
X ← Coaches(130) - 3a function: it returns a single value
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.Passing parameters by value and by reference
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.
Trace the difference
Run it with Points at 50 and watch which variable line 2 changes.
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
BYVALorBYREFgoes 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 value | By reference | |||||
|---|---|---|---|---|---|---|
| Line | Statement | Points | Score | Output | Points = Score | Output |
| 7 | Points ← 50 | 50 | 50 | |||
| 8 | CALL Bonus(Points) | 50 | 50 | 50 | ||
| 2 | Score ← Score + 10 | 50 | 60 | 60 | ||
| 3 | OUTPUT "Inside: ", Score | Inside: 60 | Inside: 60 | |||
| 9 | OUTPUT "After: ", Points | After: 50 | After: 60 | |||
By value
| Line / statement | Points | Score | Output |
|---|---|---|---|
| 7: Points ← 50 | 50 | ||
| 8: CALL Bonus(Points) | 50 | 50 | |
| 2: Score ← Score + 10 | 50 | 60 | |
| 3: OUTPUT "Inside: ", Score | Inside: 60 | ||
| 9: OUTPUT "After: ", Points | After: 50 |
By reference
| Line / statement | Points = Score | Output |
|---|---|---|
| 7: Points ← 50 | 50 | |
| 8: CALL Bonus(Points) | 50 | |
| 2: Score ← Score + 10 | 60 | |
| 3: OUTPUT "Inside: ", Score | Inside: 60 | |
| 9: OUTPUT "After: ", Points | After: 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
| Points | Score | Output | What happens | |
|---|---|---|---|---|
| line 7 | 50 | the caller's variable | ||
| the caller's variable | ||||
| line 8 | 50 | 50 | a copy of 50 goes into Score | |
| a copy of 50 goes into Score | ||||
| line 2 | 60 | Score + 10: only the copy changes | ||
| Score + 10: only the copy changes | ||||
| line 3 | Inside: 60 | the value inside the procedure | ||
| the value inside the procedure | ||||
| line 9 | After: 50 | the 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). ScoreandPointsare then one memory location, so line 2 changesPointstoo.
Passed by reference
| Points = Score | Output | What happens | |
|---|---|---|---|
| line 7 | 50 | the caller's variable | |
| the caller's variable | |||
| line 8 | 50 | Score is linked to Points: one location | |
| Score is linked to Points: one location | |||
| line 2 | 60 | Score + 10: the shared location changes | |
| Score + 10: the shared location changes | |||
| line 3 | Inside: 60 | the value inside the procedure | |
| the value inside the procedure | |||
| line 9 | After: 60 | Points now holds 60 | |
| Points now holds 60 | |||
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?
- 114: N and Value are one location
- 27: only the copy N doubles
- 3none is needed: the parameter is passed by value
Procedures that change their arguments
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.
PROCEDURE Swap(BYREF X : INTEGER, Y : INTEGER) DECLARE Temp : INTEGER Temp ← X X ← Y Y ← Temp ENDPROCEDURE CALL Swap(A, B) OUTPUT A, " ", B
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,
XandYare copies: Swap exchanges the copies, which are discarded when it ends. AandBare 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.
| Statement run | Full = Boxes | Rest = Spare |
|---|---|---|
| Full ← Items DIV Size | 2 | |
| Rest ← Items MOD Size | 26 | |
| back in the caller | Boxes = 2 | Spare = 26 |
Pass back more than one result
Run it with 130 and 52, then follow Full and Rest back into Boxes and Spare.
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 run | Full = Boxes | Rest = Spare |
|---|---|---|
| Full ← Items DIV Size | 2 | |
| Rest ← Items MOD Size | 26 | |
| back in the caller | Boxes = 2 | Spare = 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, butBoxesmust be a variable.
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, butBoxesmust be a variable.
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)?
- 13 full, 15 left over
- 25 1: only the copies were swapped
- 3Full is BYREF, so its argument must be a variable that can store the result
BYREF. A procedure that only uses the values it is given takes them by value.Headers, interfaces and scope
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 BOOLEAN
| Part | Value |
|---|---|
| Identifier | CheckNum |
| Parameters | Number : INTEGER; Total : INTEGER |
| Returns | BOOLEAN |
Valid ← CheckNum(142, 6)
Each term names one part of that drawing.
| Term | Meaning |
|---|---|
| Header | first line of the definition: identifier, parameters with types, and (functions only) return type |
| Interface | how data passes in and out: the parameters (number, order, types, passing method) and return type |
| Parameter | an identifier in the header that receives a value passed in; used like a variable inside |
| Argument | the actual value or variable passed in the call: 142 and 6 |
| Return value | the 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 description | Header |
|---|---|
| takes a student ID; returns the number of loans | FUNCTION CountLoans(StudentID : STRING) RETURNS INTEGER |
| takes a mark; outputs the grade | PROCEDURE ShowGrade(Mark : INTEGER) |
| takes a price; sets a flag the caller uses | PROCEDURE CheckPrice(Price : REAL, BYREF High : BOOLEAN) |
| no parameters; returns TRUE when ready | FUNCTION Ready() RETURNS BOOLEAN |
takes a student ID; returns the number of loans
FUNCTION CountLoans(StudentID : STRING) RETURNS INTEGER
takes a mark; outputs the grade
PROCEDURE ShowGrade(Mark : INTEGER)
takes a price; sets a flag the caller uses
PROCEDURE CheckPrice(Price : REAL, BYREF High : BOOLEAN)
no parameters; returns TRUE when ready
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.
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
FUNCTION OldEnough(Name : STRING, Age : INTEGER) RETURNS BOOLEAN - 2142 and 6; the parameters Number and Total are in the header
- 31: Reset changed its own local Total, not the global one
RETURNS <type>.Writing 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.
| Technique | What it avoids |
|---|---|
| Work out an unchanging value once, before the loop | repeating a calculation or call every time |
| Stop once the answer is known: a conditional loop (or flag), or RETURN from inside the loop | iterations after the item is found |
Use ELSE or CASE for conditions that exclude each other | testing conditions that cannot be true |
| Remove statements that can never run | e.g. OTHERWISE after CASE OF (N MOD 2) |
| Replace several statements with one expression | e.g. N ← (N MOD 3) + 1 for an add and an IF |
| Write a repeated task once as a module | duplicated 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.
Count ← 0 FOR i ← 1 TO LENGTH(Word) IF MID(Word, i, 1) = TO_UPPER(Ch) THEN Count ← Count + 1 ENDIF NEXT i
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
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.
| i | MID(Code, i, 1) | Found | What decided it | |
|---|---|---|---|---|
| test 1 | 1 | 'R' | not a digit | |
| not a digit | ||||
| test 2 | 2 | 'o' | not a digit | |
| not a digit | ||||
| test 3 | 3 | 'o' | not a digit | |
| not a digit | ||||
| test 4 | 4 | 'm' | not a digit | |
| not a digit | ||||
| test 5 | 5 | ' ' | a space: not a digit | |
| a space: not a digit | ||||
| test 6 | 6 | '7' | TRUE | a digit: Found ← TRUE |
| a digit: Found ← TRUE | ||||
| end | NOT Found is FALSE: the loop stops after 6 tests, not 16 | |||
| NOT Found is FALSE: the loop stops after 6 tests, not 16 | ||||
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?
- 13: the first digit is at position 3
- 2move
Rate ← Price * 0.2before the loop: it is worked out once, not 100 times - 3every character must be tested to know the count
Writing a module from its description
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.
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
NextCode | IsValid() | Count |
|---|---|---|
| "AB123" | TRUE | 1 |
| "XY9" | FALSE | 1 |
| "CD45E" | FALSE | 1 |
| "ZZ007" | TRUE | 2 |
| "END" | – | 2 |
Follow the actual rejection paths
- 1XY9 has length 3: IsValid returns FALSE before RIGHT is called.
- 2CD45E has length 5, but its last three characters are not a number: FALSE.
- 3AB123 and ZZ007 pass both checks: the caller adds 1 to Count twice.
- 4END 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.
| Line | Statement that runs | NextCode | IsValid() | Count | Output | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 14 | WHILE NextCode <> "END" | test "CD45E" is not "END": go into the loop | |||||
| test "CD45E" is not "END": go into the loop | |||||||
| 15 | IF IsValid(NextCode) THEN | test calls IsValid with Code ← "CD45E" | |||||
| test calls IsValid with Code ← "CD45E" | |||||||
| 2 | IF LENGTH(Code) <> 5 THEN | test LENGTH is 5: FALSE, so carry on to line 5 | |||||
| test LENGTH is 5: FALSE, so carry on to line 5 | |||||||
| 5 | RETURN IS_NUM(RIGHT(Code, 3)) | FALSE | IsValid() FALSE | RIGHT gives "45E", which is not a number | |||
| RIGHT gives "45E", which is not a number | |||||||
| 18 | INPUT NextCode | "ZZ007" | NextCode "ZZ007" | line 16 was skipped: Count stays the same | |||
| line 16 was skipped: Count stays the same | |||||||
The whole run
| NextCode | IsValid() | Count | Output | What decided it | |
|---|---|---|---|---|---|
| start | "AB123" | 0 | lines 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" | TRUE | 1 | length 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" | FALSE | length 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" | FALSE | length 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" | TRUE | 2 | length 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" | |||||
| end | 2 valid codes | NextCode 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 | |||||
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?
- 12 valid codes: QR500 and Q1234 are valid; QR5 is too short
- 20 valid codes; no, the loop never runs
- 3IsValid is a function: its returned Boolean is a value used in the condition
A function that outputs samples and returns a mean
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.
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
| Index | Load | Total |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 14 | 24 |
| 3 | 20 | 44 |
| 4 | 12 | 56 |
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.
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.
| Load | Total | Output | What decided it | |
|---|---|---|---|---|
| Index 1 | 10 | 10 | 10 | INT(RAND(11)) gave 0: 10 + 0 = 10 |
| INT(RAND(11)) gave 0: 10 + 0 = 10 | ||||
| Index 2 | 14 | 24 | 14 | INT(RAND(11)) gave 4: 10 + 4 = 14 |
| INT(RAND(11)) gave 4: 10 + 4 = 14 | ||||
| Index 3 | 20 | 44 | 20 | INT(RAND(11)) gave 10: 10 + 10 = 20 |
| INT(RAND(11)) gave 10: 10 + 10 = 20 | ||||
| Index 4 | 12 | 56 | 12 | INT(RAND(11)) gave 2: 10 + 2 = 12 |
| INT(RAND(11)) gave 2: 10 + 2 = 12 | ||||
| return | RETURN 56 / 4 = 14.0: the value goes back to MeanLoad | |||
| RETURN 56 / 4 = 14.0: the value goes back to MeanLoad | ||||
| end | Mean: 14.0 | the main program outputs the returned mean | ||
| the main program outputs the returned mean | ||||
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?
- 115, 11, 19, then Mean: 15.0
- 210 and 20
- 3
RETURN Total / Trials; it goes to MeanLoad, where the call was
Returning a record from a function
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.
TYPE PopResult DECLARE Data : INTEGER DECLARE Exists : BOOLEAN ENDTYPE DECLARE Stack : ARRAY[1:8] OF INTEGER DECLARE Top : INTEGER
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
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
| Call | Data | Exists | Top after |
|---|---|---|---|
| 1 | 47 | TRUE | 2 |
| 2 | 12 | TRUE | 1 |
| 3 | 31 | TRUE | 0 |
| 4 | not used | FALSE | 0 |
TYPE PopResult DECLARE Data : INTEGER DECLARE Exists : BOOLEAN ENDTYPE DECLARE Stack : ARRAY[1:8] OF INTEGER DECLARE Top : INTEGER
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
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.
| Data | Exists | Top after | Output | What decided it | |
|---|---|---|---|---|---|
| call 1 | 47 | TRUE | 2 | 47 | Top was 3: Data ← Stack[3]; Top − 1 |
| Top was 3: Data ← Stack[3]; Top − 1 | |||||
| call 2 | 12 | TRUE | 1 | 12 | Top was 2: Data ← Stack[2]; Top − 1 |
| Top was 2: Data ← Stack[2]; Top − 1 | |||||
| call 3 | 31 | TRUE | 0 | 31 | Top was 1: Data ← Stack[1]; Top − 1 |
| Top was 1: Data ← Stack[1]; Top − 1 | |||||
| call 4 | not used | FALSE | 0 | Empty | Top is 0: only Exists is set; the caller outputs Empty |
| Top is 0: only Exists is set; the caller outputs Empty | |||||
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?
- 18, then Empty
- 2when Exists is FALSE, Data was never assigned
- 3it returns one record whose two fields hold them