Skip to content

0478 · Unit 8 · Paper 2: Algorithms, programming and logic

Programming.

0478 · Unit 8 · Programming
Revisionbyexamplicity

Data types, variables and constants

§8.1 · Programming concepts

A program has to remember things while it runs: a name, a price, whether a door is locked. It keeps data in variables and constants. Each one has a data type: the kind of value it holds.

Write pseudocode in Paper 2, except in the 15-mark scenario, where Python, Visual Basic or Java is also allowed. Follow the question on which declarations are required.

To choose a type, ask what the value is: a count, a measurement, one key press, some text, or yes or no.

Data typeHoldsLiteral examplesPython
INTEGERa whole number5 · -3int
REALa number that can have a fractional part4.7 · 0.3 · -4.0float
CHARa single character'x' · '@'str (length 1)
STRINGzero or more characters (letters, digits, symbols)"Year 10" · ""str
BOOLEANa logical valueTRUE · FALSETrue · False
A REAL literal has a digit on both sides of the point (4.0, 0.3). CHAR uses single quotes; STRING, double.

Variables, constants, input and output

The ticket program uses both: Price is set once and never changes, while Name, Tickets and Cost get new values on every run.

Variable

A named store whose value can change while the program runs. DECLARE Tickets : INTEGER

Constant

A named value that does not change. It is given a literal, never an expression: CONSTANT Price ← 2.50

Cambridge pseudocode
DECLARE Name : STRING
DECLARE Tickets : INTEGER
DECLARE Cost : REAL
CONSTANT Price ← 2.50
OUTPUT "Your name?"
INPUT Name
OUTPUT "How many tickets?"
INPUT Tickets
Cost ← Tickets * Price
OUTPUT Name, ": ", Cost
Python
Price = 2.50
print("Your name?")
Name = input()
print("How many tickets?")
Tickets = int(input())
Cost = Tickets * Price
print(Name, ": ", Cost, sep="")

Identifiers (names)

Use meaningful names in PascalCase, e.g. TotalScore. Letters and digits only, starting with a capital letter; no spaces or underscores; never a keyword.

Input and output

INPUT stores a value in a variable. OUTPUT displays values; separate several with commas.

Your turn

1 Choose a data type for: a person’s age in whole years; a price of 3.99; whether a door is locked.

2 Is "7" a CHAR, a STRING or an INTEGER?

3 Write two lines that declare a variable PetName and input a value into it.

1 INTEGER · REAL · BOOLEAN · 2 STRING: it has double quotes, so it is text, not a number

Answer 3
DECLARE PetName : STRING
INPUT PetName
Tick what you can do now
Practise with s26/21 Q3; s26/22 Q2; s26/23 Q2; s25/21 Q9(a) (older paper: variable declarations); s24/23 Q3 (older paper: char/string definitions and examples); s24/21 Q3 (older paper: integer/real definitions and examples)
1 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Operators and comments

§8.1 · Programming concepts

Most lines of a program either work something out or ask a question about it. Arithmetic operators calculate, relational operators compare two values, and logical operators join conditions.

Arithmetic operators

Write each operator in pseudocode and Python, and work out its result.

OperationPseudocodePython17 and 5 give
add · subtract · multiply+ - *+ - *22 · 12 · 85
divide17 / 517 / 53.4
raise to the power2 ^ 32 ** 38
integer quotientDIV(17, 5)17 // 53
remainderMOD(17, 5)17 % 52
17 counters put into groups of 5DIV(17, 5) = 3 full groupsMOD(17, 5) = 2 left

DIV and MOD together split one number into two parts. Run the program with 135: DIV gives the full hours and MOD the minutes left over.

Cambridge pseudocodeinput 135 → 2 h 15 min
// split minutes into hours and minutes
DECLARE Minutes : INTEGER
DECLARE Hours : INTEGER
DECLARE Mins : INTEGER
OUTPUT "Enter the minutes"
INPUT Minutes
Hours ← DIV(Minutes, 60)
Mins ← MOD(Minutes, 60)
OUTPUT Hours, " h ", Mins, " min"
Python
# split minutes into hours and minutes
print("Enter the minutes")
Minutes = int(input())
Hours = Minutes // 60
Mins = Minutes % 60
print(Hours, " h ", Mins, " min", sep="")

Relational operators: the result is always BOOLEAN

Each comparison asks a yes-or-no question about two values. Two of them are written differently in Python: equal and not equal.

equalnot equallessless or equalgreatergreater or equal
Pseudocode=<><<=>>=
Python==!=<<=>>=
ComparisonPseudocodePython
equal===
not equal<>!=
less than<<
less than or equal<=<=
greater than>>
greater than or equal>=>=

Logical operators

One comparison is often not enough: a mark may need to be at least 40 and at most 60. Join two conditions, and say when the whole condition is TRUE.

OperatorThe result is TRUE when…Example
ANDboth conditions are trueAge >= 13 AND Age <= 19
ORat least one condition is true (or both)Day = "Sat" OR Day = "Sun"
NOTit reverses a conditionNOT Found is TRUE when Found is FALSE
In pseudocode // starts a comment, so write DIV(17, 5) for integer division. Some mark schemes call AND, OR, NOT “Boolean”: use the question’s words.

Assignment, equality and powers

  • Assignment copies a value using ←; equality compares values using =.
  • Python uses = for assignment and == for equality.
  • In Python, powers use **; ^ has a different meaning.
Your turn

1 Work out DIV(23, 4) and MOD(23, 4).

2 Is 7 > 3 AND 2 = 5 TRUE or FALSE?

3 Write a condition that is TRUE when Mark is from 40 to 60, including 40 and 60.

  1. 1
    23 = 5 × 4 + 3, so DIV gives 5 and MOD gives 3
  2. 2
    TRUE AND FALSE = FALSE: AND needs both
  3. 3
    Mark >= 40 AND Mark <= 60
Tick what you can do now
Practise with s26/21 Q2; s25/21 Q5 (older paper: MOD/DIV purpose and example); w25/22 Q1 (older paper: power evaluation)
2 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Sequence and selection

§8.1 · Programming concepts

Every program, however big, is built from just three structures. Selection is the one that lets it make decisions: a condition chooses which statements run.

Sequence

Statements are carried out one after another, in the order they are written.

Selection

A condition decides which statements run: IF or CASE.

Iteration

The same statements are repeated several times: FOR, WHILE or REPEAT.

IF: nested selection

Follow the input 101: the outer test passes, so the inner IF runs; 101 <= 100 fails, so the output is Too high.

Cambridge pseudocodeinputs 50, 101, −1
DECLARE Score : INTEGER
OUTPUT "Enter the score"
INPUT Score
IF Score >= 0
THEN
IF Score <= 100
THEN
OUTPUT "Valid"
ELSE
OUTPUT "Too high"
ENDIF
ELSE
OUTPUT "Too low"
ENDIF
Python
print("Enter the score")
Score = int(input())
if Score >= 0:
if Score <= 100:
print("Valid")
else:
print("Too high")
else:
print("Too low")

CASE: choose by the value of one variable

Choice is matched against each value in turn. OTHERWISE catches anything that matches none of them.

Cambridge pseudocode7 → Invalid
DECLARE Choice : INTEGER
OUTPUT "1 Add  2 View"
INPUT Choice
CASE OF Choice
1 : OUTPUT "Add"
2 : OUTPUT "View"
OTHERWISE OUTPUT "Invalid"
ENDCASE
Python
print("1 Add  2 View")
Choice = int(input())
if Choice == 1:
print("Add")
elif Choice == 2:
print("View")
else:
print("Invalid")
Indent THEN and ELSE by two spaces and their statements by four; close each IF with its own ENDIF. Write each comparison in full: Score >= 0 AND Score <= 100, never Score >= 0 AND <= 100.
Your turn

1 In the nested IF above, what is output when the score is 0?

2 In the CASE above, what is output when the choice is 3?

3 Write an IF statement that outputs "Pass" when Mark is 50 or more, and "Fail" otherwise.

1 Valid: 0 >= 0 is TRUE and 0 <= 100 is TRUE · 2 Invalid: 3 matches no case, so OTHERWISE runs

Answer 3
IF Mark >= 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Tick what you can do now
Practise with s24/22 Q7(a) (older paper: identify statement types); s24/21 Q5 (older paper: construct CASE branches); s26/21 Q12
3 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Iteration: three kinds of loop

§8.1 · Programming concepts

Nobody wants to write the same line fifty times. A loop writes it once and repeats it. Use FOR when you know how many times; WHILE tests first; REPEAT tests at the end.

Count-controlled: FOR … TO … NEXT

Runs a fixed number of times, known before the loop starts. The end value is included if the step reaches it.

Cambridge pseudocodeoutputs 1, 3, 5, 7, 9
DECLARE Count : INTEGER
FOR Count ← 1 TO 9 STEP 2
OUTPUT Count
NEXT Count
Python
for Count in range(1, 10, 2):
print(Count)

Count goes up by 2 each time. 11 is past the end value 9, so the loop stops before outputting it.

Counteach value is output135791111 > 9: stop
FOR Count ← 1 TO 9 STEP 2 → range(1, 10, 2): Python excludes its stop value, 10. STEP -1 counts down.

Pre-condition: WHILE … DO … ENDWHILE

The condition is tested at the start, so the loop may run zero times.

Cambridge pseudocodeoutputs 3, 2, 1
DECLARE Number : INTEGER
Number ← 3
WHILE Number > 0 DO
OUTPUT Number
Number ← Number - 1
ENDWHILE
Python
Number = 3
while Number > 0:
print(Number)
Number = Number - 1

Trace it: Number starts at 3

OUTPUTNumberWhat decided it
start3line 2 sets Number before the loop
line 2 sets Number before the loop
pass 1323 > 0 is true: output 3, then subtract 1
3 > 0 is true: output 3, then subtract 1
pass 2212 > 0 is true: output 2, then subtract 1
2 > 0 is true: output 2, then subtract 1
pass 3101 > 0 is true: output 1, then subtract 1
1 > 0 is true: output 1, then subtract 1
end0 > 0 is false: the test comes first, so the body does not run again
0 > 0 is false: the test comes first, so the body does not run again

Post-condition: REPEAT … UNTIL

The condition is tested at the end, so the loop always runs at least once. It stops when the condition is TRUE.

Cambridge pseudocodeinputs 25, 12
DECLARE Score : INTEGER
REPEAT
OUTPUT "Enter a score from 0 to 20"
INPUT Score
IF Score < 0 OR Score > 20
THEN
OUTPUT "Out of range - try again"
ENDIF
UNTIL Score >= 0 AND Score <= 20
Python
while True:
print("Enter a score from 0 to 20")
Score = int(input())
if Score < 0 or Score > 20:
print("Out of range - try again")
if Score >= 0 and Score <= 20:
break

Trace it: the inputs are 25, then 12

ScoreMessageWhat decided it
pass 125Out of range - try again25 is out of range, so the message runs; UNTIL is false: go round again
25 is out of range, so the message runs; UNTIL is false: go round again
pass 21212 is in range: no message; UNTIL is true, so the loop stops
12 is in range: no message; UNTIL is true, so the loop stops
Python has no REPEAT … UNTIL: while True: with break gives the same test-at-the-end behaviour.
Your turn

1 What does FOR Count ← 10 TO 0 STEP -5 output?

2 In the WHILE loop above, what is output if Number starts at 0?

3 Write a FOR loop that outputs 2, 4, 6 and 8.

1 10, 5, 0: the end value 0 is reached, so it is included · 2 Nothing: 0 > 0 is FALSE at the start, so the loop runs zero times

Answer 3
DECLARE Number : INTEGER
FOR Number ← 2 TO 8 STEP 2
OUTPUT Number
NEXT Number
Tick what you can do now
Practise with s26/21 Q6; s26/22 Q1; m24/22 Q6 (older paper: pre-condition description); s25/21 Q3 (older paper: convert loop type)
4 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Stopping a loop at a sentinel or a full array

§7–§8 · Iteration and arrays

Someone typing in a list may not know how long it will be, but the array has a fixed size and may end up holding fewer values. So keep going only while there is space and the input is not the sentinel, a special value that means stop.

Read the WHILE line first. Each row of the table takes one part of that condition and says what it does.

Up to three labels; END is not a label
DECLARE Labels : ARRAY[0:2] OF STRING
DECLARE Name : STRING
DECLARE Count : INTEGER
Count ← 0
OUTPUT "Enter a label or END"
INPUT Name
WHILE Name <> "END" AND Count < 3 DO
Labels[Count] ← Name
Count ← Count + 1
IF Count < 3
THEN
OUTPUT "Enter a label or END"
INPUT Name
ENDIF
ENDWHILE
OUTPUT "Stored: ", Count
Continue conditionEffect
Name <> "END"The sentinel is tested before storage, so it is never included
Count < 3Labels[Count] can only use valid indices 0, 1 and 2
Both tests joined by ANDEither a sentinel or a full array stops the loop
Read again only if Count < 3No extra input is requested after the last available position is filled

Test each way the loop can stop

For each test, say what is stored and which inputs are never read.

InputENDstops
LabelsCount = 0012
InputAriBoENDstopsCynot read
LabelsCount = 20Ari1Bo2
InputAriBoCyDeenot read
LabelsCount = 30Ari1Bo2Cy
storedthe sentinel: stops the loopnot read, or empty

Trace the second test: Ari, Bo, END, Cy

StoredCountNameWhat decided it
start0AriCount ← 0, then the first input, Ari, is read before the loop
Count ← 0, then the first input, Ari, is read before the loop
pass 1Labels[0] ← Ari1BoAri <> "END" and 0 < 3: store it in Labels[0], read the next input
Ari <> "END" and 0 < 3: store it in Labels[0], read the next input
pass 2Labels[1] ← Bo2ENDBo <> "END" and 1 < 3: store it in Labels[1], read the next input
Bo <> "END" and 1 < 3: store it in Labels[1], read the next input
endName is END: stop
Name is END: stop

AND, and what Count means

  • Join the two tests with AND. With OR, the loop would go on when only one test holds: it could store END, or write past the end of the array.
  • Count is the number of values accepted.
  • For an average, divide the total by Count, and only when Count > 0; unused positions are not part of the mean.
Your turn

1 The inputs are Ari, then END. What is the last line output?

2 Why is END never stored in Labels?

3 What must change so the program stores up to five labels?

  1. 1
    Stored: 1
  2. 2
    Name <> "END" is tested before Labels[Count] ← Name, so the loop stops first
  3. 3
    declare ARRAY[0:4], and change both Count < 3 tests to Count < 5
Tick what you can do now
Practise with s26/21 Q7; s26/23 Q4(b)(ii)
5 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

String handling

§8.1 · Programming concepts

Names, passwords and messages are all strings, and programs often need to pick them apart: the first letter, the length, one word. A string is a row of characters. Pseudocode counts positions from 1; Python counts indexes from 0.

pseudocode position1C2a3m4b5r6i7d8g9e
Python index012345678
Pseudocode position (one-based)1C02a13m24b35r46i57d68g79e8Python index (zero-based)

SUBSTRING(Text, 2, 3) starts at position 2 and takes 3 characters: “amb”. Python Text[1:4] starts at index 1 and stops before 4. These pseudocode examples start at 1; follow a stated starting position of 0 when one is given.

Cambridge pseudocodeoutputs amb, 9, CAMBRIDGE, c
DECLARE Text : STRING
DECLARE Part : STRING
Text ← "Cambridge"
Part ← SUBSTRING(Text, 2, 3)
OUTPUT Part
OUTPUT LENGTH(Text)
OUTPUT UCASE(Text)
OUTPUT LCASE(SUBSTRING(Text, 1, 1))
Python
Text = "Cambridge"
Part = Text[1:4]
print(Part)
print(len(Text))
print(Text.upper())
print(Text[0:1].lower())

Work through a string character by character

Some tasks need every character checked in turn, such as counting the words in a sentence. This word count assumes the text is not empty, has one space between words and no space at either end. Then the number of words is the number of spaces plus one.

Cambridge pseudocodeinput “I like code” → Words: 3
DECLARE Sentence : STRING
DECLARE Position : INTEGER
DECLARE Spaces : INTEGER
OUTPUT "Enter a sentence"
INPUT Sentence
Spaces ← 0
FOR Position ← 1 TO LENGTH(Sentence)
IF SUBSTRING(Sentence, Position, 1) = " "
THEN
Spaces ← Spaces + 1
ENDIF
NEXT Position
OUTPUT "Words: ", Spaces + 1
Python
print("Enter a sentence")
Sentence = input()
Spaces = 0
for Position in range(len(Sentence)):
if Sentence[Position] == " ":
Spaces = Spaces + 1
print("Words:", Spaces + 1)
Sentencepositions 1 to 111I2␣Spaces = 13l4i5k6e7␣Spaces = 28c9o10d11e
a space: add 1 to Spaces. 2 spaces, so 3 words

Spaces are characters

LENGTH("Year 10") is 7: the space counts.

Copy text exactly

Case matters inside quotes: “Yes” and “yes” are different strings.

Your turn

1 Text ← "Keyboard". What is LENGTH(Text)?

2 What is SUBSTRING(Text, 4, 5)?

3 Write one statement that outputs the first letter of Text in lower case.

1 8 · 2 “board”: start at position 4, take 5 characters

Answer 3outputs k
OUTPUT LCASE(SUBSTRING(Text, 1, 1))
Tick what you can do now
Practise with s26/21 Q5(b); s26/23 Q6(a), Q6(b); s26/22 Q6(a)
6 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Procedures and parameters

§8.1 · Programming concepts

Long programs get hard to follow, and the same job often turns up in several places. A procedure is a named block of code that does one task, written once and used wherever it is needed. You run it with CALL, and can pass values in through its parameters.

Procedure

A named subroutine that carries out a task. It need not return a value. It is run with CALL.

Function

A subroutine that always returns one value. It is used inside an expression, e.g. an assignment or OUTPUT.

Parameter

A variable in the subroutine header that receives a value (the argument) when the subroutine is called. Up to three are used.

Procedure: perform a task

Two parts: the definition says what to do, and nothing happens until the CALL runs it with Score set to 18.

Cambridge pseudocodeoutputs Score: 18
PROCEDURE ShowScore(Score : INTEGER)
OUTPUT "Score: ", Score
ENDPROCEDURE

CALL ShowScore(18)
Python
def ShowScore(Score):
print("Score: ", Score, sep="")

ShowScore(18)

Procedures with and without parameters

ShowMenu needs nothing passed in. For ShowScore, follow the 18 from the CALL into Score.

A procedure with no parameters
PROCEDURE ShowMenu
OUTPUT "1 New game"
OUTPUT "2 Quit"
ENDPROCEDURE

CALL ShowMenu

Parameter or argument?

In PROCEDURE ShowScore(Score : INTEGER), Score is the parameter. In CALL ShowScore(18), 18 is the argument: the value passed in.

CALL ShowScore(18)↓ the argument 18 is copied into the parameterPROCEDURE ShowScore(Score : INTEGER)↓ inside the procedure, Score = 18OUTPUT "Score: ", Score → Score: 18
Subroutines are defined at the start of the program. Arguments are passed in the same order and with the same data types as the parameters. When a procedure ends, the program continues from the line after the CALL.
Your turn

1 In PROCEDURE Greet(Name : STRING) and CALL Greet("Sam"), which is the parameter and which is the argument?

2 What does CALL ShowScore(7) output?

3 Write a procedure Stars, with no parameters, that outputs a row of five stars. Then write the line that runs it.

1 Name is the parameter; "Sam" is the argument · 2 Score: 7

Answer 3
PROCEDURE Stars
OUTPUT "*****"
ENDPROCEDURE

CALL Stars
Tick what you can do now
Practise with s24/21 Q2(a), Q2(b) (older paper: procedure/parameter matching and CALL); w25/23 Q9(b)(i) (older paper: define a file-writing procedure)
7 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Functions and return values

§8.1 · Programming concepts

Sometimes you want a subroutine to work something out and hand the answer back, the way LENGTH hands back the number of characters. A function is a subroutine that returns one value. Its call goes inside an expression, such as an assignment or an OUTPUT.

Function: calculate and return a value

Follow the 7 from the main program into N, then the 49 back out into Answer.

Cambridge pseudocodeoutputs 49, 10
FUNCTION Square(N : INTEGER) RETURNS INTEGER
RETURN N * N
ENDFUNCTION

DECLARE Answer : INTEGER
Answer ← Square(7)
OUTPUT Answer
OUTPUT Square(3) + 1
Python
def Square(N):
return N * N

Answer = Square(7)
print(Answer)
print(Square(3) + 1)
Main programFUNCTION Square(N : INTEGER)Answer ← Square(7)AnswerNparameterRETURN N * Nargument 7 → parameter N7= 7 * 7 = 4949returns 4949
Main programAnswer ← Square(7)AnswerFUNCTION Square(N : INTEGER)NRETURN N * Nargument 7 → N7= 7 * 7 = 4949returns 4949

Procedure or function?

Both are subroutines, so they are easy to mix up. Compare how each is written and called, and choose the right one for a task.

ProcedureFunction
HeaderPROCEDURE Name(Param : TYPE)FUNCTION Name(Param : TYPE) RETURNS TYPE
Ends withENDPROCEDURERETURN value, then ENDFUNCTION
Called byCALL Name(arguments) on its own lineits name inside an expression: X ← Name(arguments)
Returnsnothing has to come backexactly one value, of the type in the header
Use it tocarry out a task, e.g. show a menu or store datacalculate one value, e.g. a square or whether a number is odd

Procedure

AspectForm or purpose
HeaderPROCEDURE Name(Param : TYPE)
Ends withENDPROCEDURE
Called byCALL Name(arguments) on its own line
Returnsnothing has to come back
Use it tocarry out a task, e.g. show a menu or store data

Function

AspectForm or purpose
HeaderFUNCTION Name(Param : TYPE) RETURNS TYPE
Ends withRETURN value, then ENDFUNCTION
Called byits name inside an expression: X ← Name(arguments)
Returnsexactly one value, of the type in the header
Use it tocalculate one value, e.g. a square or whether a number is odd
Two parameters, one return value
FUNCTION Combined(First : INTEGER, Second : INTEGER) RETURNS INTEGER
RETURN First + Second
ENDFUNCTION
OUTPUT Combined(12, 18)
  • Combined receives 12 as First and 18 as Second, then returns 30 to the OUTPUT.
  • The arguments match the parameters in order and in type.
  • Library routines such as ROUND and LENGTH also return values.
Your turn

1 What does OUTPUT Square(4) - 6 output?

2 Why is CALL Square(5) wrong?

3 Write a function Double that returns its integer parameter times 2. Then output Double(9).

1 Square(4) returns 16, and 16 − 6 = 10 · 2 Square is a function: use its returned value in an expression, e.g. Answer ← Square(5). CALL is for procedures

Answer 3outputs 18
FUNCTION Double(N : INTEGER) RETURNS INTEGER
RETURN N * 2
ENDFUNCTION

OUTPUT Double(9)
Tick what you can do now
Practise with s26/21 Q11; s25/21 Q9(b) (older paper: rounding function); s24/21 Q2(c) (older paper: subroutine maintainability)
8 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Scope and maintainable programs

§8.1 · Programming concepts

If every subroutine could change every variable, one slip inside a subroutine could spoil a total somewhere else. So where a variable is declared decides where it can be used: its scope. A maintainable program is easy for another programmer to read and change.

Global variable

Declared in the main program; can be used anywhere, including inside subroutines.

Local variable

Declared inside a subroutine; it exists only while that subroutine runs and cannot be used outside it.

Find where each variable is declared in the code, then check which box it sits in.

Cambridge pseudocodeoutputs 17, 5
DECLARE Bonus : INTEGER

// add the bonus to a mark
FUNCTION Final(Mark : INTEGER) RETURNS INTEGER
DECLARE Result : INTEGER
Result ← Mark + Bonus
RETURN Result
ENDFUNCTION

Bonus ← 5
OUTPUT Final(12)
OUTPUT Bonus
Python
# add the bonus to a mark
def Final(Mark):
Result = Mark + Bonus
return Result

Bonus = 5
print(Final(12))
print(Bonus)
  • Bonus is global. Mark (a parameter) and Result are local to Final.
  • Outside the function, use the returned value, not the local name Result.
  • Python note: a function can read a global variable, but must state global Bonus to change it.

Make a program maintainable

A program is changed far more often than it is written, and often by someone else. Name each technique, give an example, and say how it helps another programmer.

TechniqueExampleWhy it helps
Meaningful identifiersTotalScore, not Tthe name shows what is stored, for variables, constants, arrays and subroutines
Comments// calculate the averageexplain what each section does, so another programmer can follow it
Procedures and functionsCALL ShowMenuavoids repeated code; splits the program into smaller, easier-to-read parts
Indentation and white spacestatements inside a loop indentedshows where each block starts and ends
ConstantsCONSTANT VAT ← 0.2a named fixed value can be updated in one place without finding every repeated literal
Your turn

1 In the program above, which variables are local to Final?

2 If the program sets Bonus ← 8 instead, what does OUTPUT Final(12) give?

3 Give two ways to make a program easier to maintain, with an example of each.

  1. 1
    Mark and Result
  2. 2
    12 + 8 = 20
  3. 3
    any two, e.g. meaningful identifiers (TotalScore, not T); comments (// calculate the average); a constant (CONSTANT VAT ← 0.2)
Tick what you can do now
Practise with s26/23 Q9; m26/22 Q4; m24/22 Q10 (older paper: local/global distinction)
9 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

One-dimensional arrays

§8.2 · Arrays

Five scores in five variables means five INPUT lines. An array keeps a fixed number of values of one data type under a single name; each is an element, found by its index.

01218219311415
Scores[2] holds 19: the third element.

Why use an array?

One name stores many related values, so a loop with an index variable can input, process or output them all. Without an array, you would need a separate variable and a separate line of code for each value.

Cambridge pseudocodeinputs 12, 8, 19, 11, 15
DECLARE Scores : ARRAY[0:4] OF INTEGER
DECLARE Index : INTEGER
FOR Index ← 0 TO 4
OUTPUT "Enter score ", Index + 1
INPUT Scores[Index]
NEXT Index
Scores[2] ← 20
FOR Index ← 0 TO 4
OUTPUT Scores[Index]
NEXT Index
Python
Scores = [0] * 5
for Index in range(5):
print("Enter score ", Index + 1, sep="")
Scores[Index] = int(input())
Scores[2] = 20
for Index in range(5):
print(Scores[Index])
What the program does to Scores
Scoresafter the first loop: INPUT fills 0 to 401218219311415
Scoresafter Scores[2] ← 2001218220was 19311415

Which indexes are valid

Read the two bounds in each declaration: they give the first and last valid index, and so the number of elements.

DeclarationNumber of elementsValid indexes
ARRAY[0:4] OF INTEGER50 to 4
ARRAY[1:5] OF INTEGER51 to 5
ARRAY[1:30] OF STRING301 to 30
Number of elements = upper bound − lower bound + 1. Exam arrays usually start at index 1; Python lists always start at 0. Python lists can grow and mix types: here they model a fixed-size array of one type.
Your turn

1 How many elements are in ARRAY[1:12] OF REAL, and which indexes are valid?

2 The program above is given 12, 8, 19, 11, 15. What is Scores[3] at the end?

3 Temps is declared as ARRAY[1:7] OF REAL. Write a loop that outputs every element.

1 12 − 1 + 1 = 12 elements, indexes 1 to 12 · 2 11: index 3 is the fourth element

Answer 3
DECLARE Day : INTEGER
FOR Day ← 1 TO 7
OUTPUT Temps[Day]
NEXT Day
Tick what you can do now
Practise with s26/22 Q3(c); m26/22 Q2(c); s25/21 Q3 (older paper: input-array loop conversion)
10 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Two-dimensional arrays

§8.2 · Arrays

Some data is naturally a table: each student has several test scores. A 2D array is a table of elements of one type: the first index is the row, the second the column. Three students each have two test scores; their names are in a separate 1D array.

Names[Row]Scores[Row, 0]Test 1Scores[Row, 1]Test 2Totaloutput
Row 0Ari121830
Row 1Bo91423
Row 2Cy151732
Names: a parallel 1D array, same row indexthe total output for that row

Two loops, one inside the other: the outer loop picks a row, and the inner loop visits that row's two columns before the row's total is output.

Cambridge pseudocode
DECLARE Scores : ARRAY[0:2, 0:1] OF INTEGER
DECLARE Row : INTEGER
DECLARE Column : INTEGER
DECLARE Total : INTEGER
FOR Row ← 0 TO 2
Total ← 0
FOR Column ← 0 TO 1
INPUT Scores[Row, Column]
Total ← Total + Scores[Row, Column]
NEXT Column
OUTPUT Names[Row], ": ", Total
NEXT Row
Python
Scores = [[0, 0], [0, 0], [0, 0]]
for Row in range(3):
Total = 0
for Column in range(2):
Scores[Row][Column] = int(input())
Total = Total + Scores[Row][Column]
print(Names[Row], ": ", Total, sep="")

Trace the nested loops: the inner loop runs twice for each row

RowColumnInputTotalOUTPUTWhat decided it
row 000outer loop: Row = 0, so Total ← 0 before the inner loop
outer loop: Row = 0, so Total ← 0 before the inner loop
col 001212INPUT Scores[0, 0]; Total = 0 + 12
INPUT Scores[0, 0]; Total = 0 + 12
col 111830Ari: 30INPUT Scores[0, 1]; Total = 12 + 18; the inner loop ends, so output
INPUT Scores[0, 1]; Total = 12 + 18; the inner loop ends, so output
row 110outer loop: Row = 1, so Total ← 0 before the inner loop
outer loop: Row = 1, so Total ← 0 before the inner loop
col 0099INPUT Scores[1, 0]; Total = 0 + 9
INPUT Scores[1, 0]; Total = 0 + 9
col 111423Bo: 23INPUT Scores[1, 1]; Total = 9 + 14; the inner loop ends, so output
INPUT Scores[1, 1]; Total = 9 + 14; the inner loop ends, so output
row 220outer loop: Row = 2, so Total ← 0 before the inner loop
outer loop: Row = 2, so Total ← 0 before the inner loop
col 001515INPUT Scores[2, 0]; Total = 0 + 15
INPUT Scores[2, 0]; Total = 0 + 15
col 111732Cy: 32INPUT Scores[2, 1]; Total = 15 + 17; the inner loop ends, so output
INPUT Scores[2, 1]; Total = 15 + 17; the inner loop ends, so output

Total one column: fix the column, loop through the rows

Scores[Row, 0]Scores[Row, 1]
Row 01218
Row 1914
Row 21517

Column 1 is fixed; Row goes 0, 1, 2. The highlighted cells are the only ones read: 18 + 14 + 17 = 49.

Cambridge pseudocode18 + 14 + 17 = 49
DECLARE Row : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Row ← 0 TO 2
Total ← Total + Scores[Row, 1]
NEXT Row
OUTPUT "Test 2 total: ", Total
Python
Total = 0
for Row in range(3):
Total = Total + Scores[Row][1]
print("Test 2 total:", Total)
Your turn

1 How many elements does ARRAY[1:4, 1:3] OF INTEGER hold?

2 Using the array above, what is Scores[1, 0]?

3 Write a loop that totals Test 1 (column 0) for all three students and outputs the total.

1 4 rows × 3 columns = 12 · 2 9: row 1 is Bo, column 0 is Test 1

Answer 3outputs 36
DECLARE Row : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Row ← 0 TO 2
Total ← Total + Scores[Row, 0]
NEXT Row
OUTPUT "Test 1 total: ", Total
Tick what you can do now
Practise with m26/22 Q5(b); s26/23 Q10; w25/22 Q2(b)(i) (older paper: row/column declaration)
11 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Parallel arrays, indexing and nested loops

§8.2 · Arrays

A name is text and a mark is a number, so they cannot share one array of one type. Parallel arrays store related data in separate arrays at the same index: Names[2] and Marks[2] belong to the same student.

Parallel arrays: the same index links related data

Index 0Index 1Index 2Index 3
Names[Index]AriBoCyDee
Marks[Index]62455038
Marks[Index] >= 50 is truefalsethe name output at that index
Never sort or change one parallel array on its own: the indexes would stop matching. Swap the elements in both arrays together.

One Index reads both arrays, so the name output always belongs to the mark that was tested.

Cambridge pseudocodeoutputs Ari, Cy
DECLARE Index : INTEGER
FOR Index ← 0 TO 3
IF Marks[Index] >= 50
THEN
OUTPUT Names[Index], " passed"
ENDIF
NEXT Index
Python
for Index in range(4):
if Marks[Index] >= 50:
print(Names[Index], "passed")

Common array mistakes

Out of range

FOR Index ← 1 TO 5 on ARRAY[0:4] misses element 0 and tries to use element 5, which does not exist.

Value, not index

Scores[19] does not mean “the element holding 19”. The index is the position.

Fixed index in a loop

Inside a loop, use the loop variable as the index: Scores[Index], not Scores[1].

Working with 2D arrays

Nested loops over a 2D array need three things: its size, how to name one element, and the order the loops visit them.

Declare

ARRAY[0:2, 0:1]: 3 rows × 2 columns = 6 elements.

Access

Pseudocode Scores[Row, Column]; Python Scores[Row][Column].

Nested loops

The inner loop runs through every column for each row; reset a row total before the inner loop.

Your turn

1 Using the arrays above, what are Names[3] and Marks[3]?

2 Data is ARRAY[1:10] OF INTEGER. Which of Data[0] and Data[10] is out of range?

3 Change the loop above so it outputs the name and “resit” for each student with a mark below 50.

1 Dee and 38: the same index, so the same student · 2 Data[0]: the lower bound is 1

Answer 3outputs Bo resit, Dee resit
DECLARE Index : INTEGER
FOR Index ← 0 TO 3
IF Marks[Index] < 50
THEN
OUTPUT Names[Index], " resit"
ENDIF
NEXT Index
Tick what you can do now
Practise with m26/22 Q5(b), Q5(c); s26/23 Q10
12 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Sorting whole records by one field

§8.2 · Arrays and nested iteration

Sort a class list by family name and each given name must travel with its family name, or people end up with the wrong names. So compare one field, the key, but move every field of the record together. Column 0 is the family name (the key) and column 1 is the given name. Each swap moves both columns.

Before
0: familythe key1: given
Row 0ZedAsha
Row 1KhanMilo
Row 2KhanEva
After
0: familythe key1: given
Row 0KhanMilo
Row 1KhanEva
Row 2ZedAsha

Compare the two pictures: each given name stays beside its family name. Lines 10 to 15 are the swap that makes that happen.

Bubble sort on the family-name key
 1DECLARE Row : INTEGER
 2DECLARE TempFamily : STRING
 3DECLARE TempGiven : STRING
 4DECLARE Swapped : BOOLEAN
 5REPEAT
 6Swapped ← FALSE
 7FOR Row ← 0 TO 1
 8IF People[Row, 0] > People[Row + 1, 0]
 9THEN
10TempFamily ← People[Row, 0]
11TempGiven ← People[Row, 1]
12People[Row, 0] ← People[Row + 1, 0]
13People[Row, 1] ← People[Row + 1, 1]
14People[Row + 1, 0] ← TempFamily
15People[Row + 1, 1] ← TempGiven
16Swapped ← TRUE
17ENDIF
18NEXT Row
19UNTIL NOT Swapped
20FOR Row ← 0 TO 2
21OUTPUT People[Row, 0], " ", People[Row, 1]
22NEXT Row

Preserve the association

  1. 10–11
    Save both cells before you overwrite either.
  2. 12–13
    Copy both cells up from the next row.
  3. 14–15
    Put both saved cells into that row.

Sorting only the family column would wrongly attach Khan to Asha.

A key may leave a tie

  • Both Khan records have the same key. This sort keeps Milo before Eva; it does not sort given names.
  • To order ties, also compare the given names when the family names are equal (line 8), then do the same whole-row swap.

Parallel arrays and output

  • With parallel arrays, swap the same positions in every array.
  • To output a 2D array, the inner column loop finishes before the outer loop moves to the next row.

Trace the sort: one row for each comparison

RowSwappedPeople row 0People row 1People row 2What decided it
startZedAshaKhanMiloKhanEvathe rows before sorting
the rows before sorting
pass 10TRUEKhanMiloZedAshaZed > Khan is true: swap both columns of rows 0 and 1
Zed > Khan is true: swap both columns of rows 0 and 1
pass 11TRUEKhanEvaZedAshaZed > Khan is true: swap both columns of rows 1 and 2
Zed > Khan is true: swap both columns of rows 1 and 2
pass 20FALSEKhan > Khan is false: a tie, so no swap: Milo stays before Eva
Khan > Khan is false: a tie, so no swap: Milo stays before Eva
pass 21Khan > Zed is false: already in order
Khan > Zed is false: already in order
enda whole pass with no swap: Swapped is FALSE, so UNTIL NOT Swapped stops
a whole pass with no swap: Swapped is FALSE, so UNTIL NOT Swapped stops
Your turn

1 People holds the rows (Lee, Ana) and (Diaz, Tom). After one swap on the family-name key, what is in row 0?

2 Why does the code save TempGiven as well as TempFamily?

3 Write the IF condition that also puts tied family names in order of given name.

1 Diaz, Tom: the whole record moves · 2 so the given name moves with its family name; otherwise it is overwritten and the names no longer match

Answer 3sorts Khan Eva before Khan Milo
IF People[Row, 0] > People[Row + 1, 0]
OR (People[Row, 0] = People[Row + 1, 0]
AND People[Row, 1] > People[Row + 1, 1])
Tick what you can do now
Practise with m26/22 Q5(a), Q5(b), Q5(c)
13 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

File handling

§8.3 · File handling

Data in variables and arrays is lost when the program stops. Storing it in a file keeps it permanently (non-volatile), so it can be used the next time the program runs, by another program, backed up or copied to another computer.

Follow the name Ari: saved to the file before the program ends, it is still there to load on the next run.

RAM: variablesSecondary storageRun 1Name“Ari”Names.txtWRITEFILE: save“Ari”lostprogram ends: RAM clearedkeptRun 2NameREADFILE: load“Ari”
RAM: variablesRun 1: Name“Ari”Secondary storageNames.txtWRITEFILEsave“Ari”lostRAM clearedkeptRun 2: NameREADFILEload“Ari”

Write a line: open → write → close

Cambridge pseudocodeWRITE replaces the contents
DECLARE Name : STRING
OUTPUT "Enter a name"
INPUT Name
OPENFILE "Names.txt" FOR WRITE
WRITEFILE "Names.txt", Name
CLOSEFILE "Names.txt"
Python
print("Enter a name")
Name = input()
File = open("Names.txt", "w")
File.write(Name + "\n")
File.close()

Read a line: open → read → close

Cambridge pseudocode
DECLARE Name : STRING
OPENFILE "Names.txt" FOR READ
READFILE "Names.txt", Name
CLOSEFILE "Names.txt"
OUTPUT "Hello ", Name
Python
File = open("Names.txt", "r")
Name = File.readline().rstrip("\n")
File.close()
print("Hello ", Name, sep="")

File modes

FOR READ: read data from an existing file. FOR WRITE: create the file; any existing data is lost. Open a file in one mode at a time.

Python notes

write() does not add a new line, so add "\n". readline() keeps the line ending, so rstrip() can remove the newline without removing other spaces.

Your turn

1 Why save a high score in a file rather than only in a variable?

2 Names.txt already holds data. What happens to it when the file is opened FOR WRITE?

3 Write pseudocode that reads one line from Score.txt into Best and outputs it.

1 A variable is in RAM and is lost when the program ends; the file is kept on secondary storage for the next run · 2 It is lost: WRITE creates the file again

Answer 3
DECLARE Best : STRING
OPENFILE "Score.txt" FOR READ
READFILE "Score.txt", Best
CLOSEFILE "Score.txt"
OUTPUT Best
Tick what you can do now
Practise with s26/22 Q7(a), Q7(b); s26/21 Q5(c); w25/21 Q9 (older paper: READFILE/WRITEFILE comparison)
14 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Library routines: MOD, DIV, ROUND, RANDOM

§8.1 · Programming concepts

Some jobs come up so often that the language already has a routine for them: remainders, rounding, random numbers. Know what each library routine returns and how many arguments it takes.

MOD

The remainder after integer division. MOD(17, 5) → 2

DIV

The whole-number quotient. DIV(17, 5) → 3

ROUND

Rounds to a number of decimal places: two arguments. ROUND(12.346, 2) → 12.35

RANDOM

A random real number from 0 to 1 inclusive; it takes no arguments.

Patterns that come up again and again

For each job, compare the pseudocode with the Python, then check the value it gives.

PurposePseudocodePythonResult
random whole number 1 to 6ROUND(RANDOM() * 5, 0) + 1random.randint(1, 6)1, 2, 3, 4, 5 or 6
random whole number Min to MaxROUND(RANDOM() * (Max - Min), 0) + Minrandom.randint(Min, Max)Min to Max
round to 1 decimal placeROUND(28 / 5, 1)round(28 / 5, 1)5.6
is N even?MOD(N, 2) = 0N % 2 == 0TRUE / FALSE
135 minutes in h and minDIV(135, 60) · MOD(135, 60)135 // 60 · 135 % 602 · 15

random whole number 1 to 6

LanguageExpression
PseudocodeROUND(RANDOM() * 5, 0) + 1
Pythonrandom.randint(1, 6)

Result: 1, 2, 3, 4, 5 or 6

random whole number Min to Max

LanguageExpression
PseudocodeROUND(RANDOM() * (Max - Min), 0) + Min
Pythonrandom.randint(Min, Max)

Result: Min to Max

round to 1 decimal place

LanguageExpression
PseudocodeROUND(28 / 5, 1)
Pythonround(28 / 5, 1)

Result: 5.6

is N even?

LanguageExpression
PseudocodeMOD(N, 2) = 0
PythonN % 2 == 0

Result: TRUE / FALSE

135 minutes in h and min

LanguageExpression
PseudocodeDIV(135, 60) · MOD(135, 60)
Python135 // 60 · 135 % 60

Result: 2 · 15

The first pattern at work: the loop keeps rolling until a 6 comes up, counting the rolls.

Cambridge pseudocodeuses a random whole number
// roll a dice until a 6 appears
DECLARE Roll : INTEGER
DECLARE Rolls : INTEGER
Rolls ← 0
REPEAT
Roll ← ROUND(RANDOM() * 5, 0) + 1
Rolls ← Rolls + 1
UNTIL Roll = 6
OUTPUT "A 6 after ", Rolls, " rolls"
Python
# roll a dice until a 6 appears
import random
Rolls = 0
while True:
Roll = random.randint(1, 6)
Rolls = Rolls + 1
if Roll == 6:
break
print("A 6 after ", Rolls, " rolls", sep="")

How ROUND(RANDOM() * 5, 0) + 1 gives a dice roll

  • RANDOM takes no arguments; each step changes the range.
  • Round to 0 decimal places: rounding to 1 place could leave a fraction.
RANDOM()0 to 1, a real numberRANDOM() * 50 to 5, a real numberROUND(…, 0)0, 1, 2, 3, 4 or 5… + 11, 2, 3, 4, 5 or 6
RANDOM()0 to 1, a real numberRANDOM() * 50 to 5, a real numberROUND(…, 0)0, 1, 2, 3, 4 or 5… + 11, 2, 3, 4, 5 or 6
Your turn

1 Work out MOD(29, 6) and DIV(29, 6).

2 What does ROUND(7.456, 1) give?

3 Write a pseudocode expression for a random whole number from 1 to 10.

  1. 1
    29 = 4 × 6 + 5, so MOD gives 5 and DIV gives 4
  2. 2
    7.5: one decimal place, and the next digit 5 rounds up
  3. 3
    ROUND(RANDOM() * 9, 0) + 1: RANDOM() * 9 is 0 to 9, rounding gives 0 to 9, adding 1 gives 1 to 10
Tick what you can do now

Python’s round() rounds an exact half to the even number, so round(2.5) is 2. random.randint(1, 6) gives a whole number directly, so Python code does not need the rounding step.

Practise with s26/21 Q5(a); s25/21 Q5, Q6(a) (older paper: MOD/DIV purposes and ROUND correction); w25/21 Q10(b) (older paper: library-routine purposes)
15 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Designing a larger program from requirements

§7–§8 · Programming and problem-solving

A long program question can look like a wall of text, but it is built from small parts you already know. Before writing loops, sort the instructions into the data you are given, the processing to do and the results to output.

Translate a requirement into a data operation

For each requirement, decide what the code must do and where in the program it goes.

RequirementDesign decisionWhere it belongs
Data are already in named arraysUse those names and bounds; keep each record's matching indexBefore coding: do not input preloaded data again
Each entered value must satisfy a ruleRepeat that value's input until valid; store only a valid valueInside the loop for that record
Report a statistic for each rowReset its total or count before that row's columnsInside the outer loop, before the inner loop
Report a result for all recordsInitialise once, then update for each recordInitialise before the loop; output after it
Report the name with the highest or lowest resultKeep the index of the winner as well as its valueUpdate both together; read the name at that index

See where each part goes

Find the three comments in the code: each marks where the requirements from the table land.

Before, inside and after the loop
DECLARE Index : INTEGER
DECLARE Passes : INTEGER
DECLARE Total : INTEGER
DECLARE Top : INTEGER
// before the loop: initialise once
Passes ← 0
Total ← 0
Top ← 0
// inside the loop: one student at a time
FOR Index ← 0 TO 3
Total ← Total + Marks[Index]
IF Marks[Index] >= 50
THEN
Passes ← Passes + 1
ENDIF
IF Marks[Index] > Marks[Top]
THEN
Top ← Index
ENDIF
NEXT Index
// after the loop: output the results
OUTPUT "Passed: ", Passes
OUTPUT "Top: ", Names[Top], " ", Marks[Top]
OUTPUT "Average: ", ROUND(Total / 4, 1)
Index0123
NamesAriBoCyDee
Marks62455038
≥ 50: a passbelow 50Names[Top]
  • The same index reads a name and its mark.
  • The highest mark, 62, is at index 0, so the name is Ari: keep Top, the index, not just the mark.
  • 195 ÷ 4 = 48.75, which ROUND(…, 1) gives as 48.8.

Trace it: one row for each student

IndexMarks[Index]TotalPassesTopWhat decided it
start000before the loop: each is set once
before the loop: each is set once
pass 106262162 ≥ 50: Passes + 1; 62 > 62 is false
62 ≥ 50: Passes + 1; 62 > 62 is false
pass 214510745 < 50: no pass; 45 > 62 is false
45 < 50: no pass; 45 > 62 is false
pass 3250157250 ≥ 50: Passes + 1; 50 > 62 is false
50 ≥ 50: Passes + 1; 50 > 62 is false
pass 433819538 < 50: no pass; 38 > 62 is false
38 < 50: no pass; 38 > 62 is false
endafter the loop: output Passed: 2, Top: Ari 62, Average: 48.8 (195 ÷ 4 = 48.75)
after the loop: output Passed: 2, Top: Ari 62, Average: 48.8 (195 ÷ 4 = 48.75)

Make every requirement testable

  • Do what the question says about declarations and initialisation: they are different instructions.
  • Prompt for each input, label outputs and give units, and use meaningful identifiers and comments for each section.
  • Test boundaries (a mark of exactly 50), a top mark at a different index, and any tie or empty case.
  • Trace the whole program to check the parts connect.
  • Marks go to meeting each requirement and to working logic. Choose one permitted language and use it all the way through.
Your turn

1 A requirement says “output the average mark”. Where do Total ← 0 and the OUTPUT go?

2 If Cy’s mark were 70, what would the program above output on its Top line?

3 Give two marks you would test the pass check with, and what each should give.

  1. 1
    Total ← 0 before the loop; the OUTPUT after it
  2. 2
    Top: Cy 70: 70 > 62, so Top becomes index 2
  3. 3
    50 should pass (the boundary) and 49 should fail (just below it)
Tick what you can do now
Practise with m26/22 Q9; s26/21 Q12; s26/22 Q10; s26/23 Q10
16 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Counting how often each value appears

§7–§8 · Arrays, counting and selection

To find how often each face of a dice comes up, you need six counters, one for each face. The value you read picks which counter to add 1 to. Six dice results are 2, 5, 2, 1, 5, 2. Results uses indexes 0–5; Frequency uses face numbers 1–6: two different index ranges.

Follow each arrow: the value in Results picks which counter in Frequency gets 1 added.

Count by value, not by input position
DECLARE Frequency : ARRAY[1:6] OF INTEGER
DECLARE Face : INTEGER
DECLARE Index : INTEGER
FOR Face ← 1 TO 6
Frequency[Face] ← 0
NEXT Face
FOR Index ← 0 TO 5
Face ← Results[Index]
Frequency[Face] ← Frequency[Face] + 1
NEXT Index
FOR Face ← 1 TO 6
OUTPUT Face, ": ", Frequency[Face]
NEXT Face
Results[Index]: indexes 0 to 5012345252152130020123456Frequency[Face]: faces 1 to 6

Trace which element changes

IndexFaceCounter changedWhat decided it
startlines 4 to 6 set Frequency[1] to Frequency[6] to 0
lines 4 to 6 set Frequency[1] to Frequency[6] to 0
pass 102Frequency[2] = 1Results[0] is 2, so add 1 to counter 2: 0 + 1
Results[0] is 2, so add 1 to counter 2: 0 + 1
pass 215Frequency[5] = 1Results[1] is 5, so add 1 to counter 5: 0 + 1
Results[1] is 5, so add 1 to counter 5: 0 + 1
pass 322Frequency[2] = 2Results[2] is 2, so add 1 to counter 2: 1 + 1
Results[2] is 2, so add 1 to counter 2: 1 + 1
pass 431Frequency[1] = 1Results[3] is 1, so add 1 to counter 1: 0 + 1
Results[3] is 1, so add 1 to counter 1: 0 + 1
pass 545Frequency[5] = 2Results[4] is 5, so add 1 to counter 5: 1 + 1
Results[4] is 5, so add 1 to counter 5: 1 + 1
pass 652Frequency[2] = 3Results[5] is 2, so add 1 to counter 2: 2 + 1
Results[5] is 2, so add 1 to counter 2: 2 + 1
endsix results, and the counts add up to 6
six results, and the counts add up to 6

Count by value, not by position

  • Each pass changes the counter picked by the value read, not by Index. Adding 1 to Frequency[Index] instead would count positions, not results.
  • Set every counter to 0 first, even for faces that never appear. The counts add up to 6, one for each result.
  • If results are typed in, check that each is 1–6 before using it as an index.
  • To find the most or least common face, compare the finished counts and keep the face number (the index) as its label.
Your turn

1 The results are 3, 3, 6, 1. What are Frequency[3] and Frequency[6] after counting?

2 Why must every counter be set to 0 before counting?

3 Write a loop that finds the face with the highest count and outputs it.

1 2 and 1 · 2 a counter that is never set may hold any value, and faces that never appear must still show 0

Answer 3outputs Most common: 2 for the page’s data
DECLARE Most : INTEGER
DECLARE Face : INTEGER
Most ← 1
FOR Face ← 2 TO 6
IF Frequency[Face] > Frequency[Most]
THEN
Most ← Face
ENDIF
NEXT Face
OUTPUT "Most common: ", Most
Tick what you can do now
Practise with m26/22 Q9
17 / 18
0478 · Unit 8 · Programming
Revisionbyexamplicity

Finding the longest run of values in a row

§7–§8 · Iteration and state

A library may want two numbers: how many days had no late returns, and the longest stretch of such days in a row. A count answers the first; a run answers the second. Daily late returns are 0, 0, 3, 0, 2, 0, 0, 0, 1. ZeroCount counts every zero day; CurrentRun counts only the zeros in a row so far.

LateReturns00102330425060longest run7081
a zero daynot zero: CurrentRun goes back to 0the longest run of zeros: 3 days

On a zero day both counters go up; any other day sends only CurrentRun back to 0.

Reset the current run, retain the maximum
 1DECLARE Index : INTEGER
 2DECLARE ZeroCount : INTEGER
 3DECLARE CurrentRun : INTEGER
 4DECLARE LongestRun : INTEGER
 5ZeroCount ← 0
 6CurrentRun ← 0
 7LongestRun ← 0
 8FOR Index ← 0 TO 8
 9IF LateReturns[Index] = 0
10THEN
11ZeroCount ← ZeroCount + 1
12CurrentRun ← CurrentRun + 1
13IF CurrentRun > LongestRun
14THEN
15LongestRun ← CurrentRun
16ENDIF
17ELSE
18CurrentRun ← 0
19ENDIF
20NEXT Index
21OUTPUT "Zero days: ", ZeroCount
22OUTPUT "Longest zero run: ", LongestRun

Count, reset, retain

There are 6 zero days in total, in runs of 2, 1 and 3.

  1. 18
    A non-zero input sends CurrentRun back to 0, but LongestRun keeps the best run so far.
  2. 13–15
    Update the maximum inside the loop, so a run that reaches the last element is also counted.

Choose the statistic

  • Use the statistic the question asks for: a test on the longest period with no late returns compares LongestRun, not ZeroCount.
  • If several records each have their own sequence, reset these values inside the outer loop.
One time round the loop: pass 8 (Index 7)
The longest run grows from 2 to 3. Together the lines make the blue row of the trace below.
LineStatement that runsIndexZeroCountCurrentRunLongestRunWritesWhat happens
8FOR Index ← 0 TO 87Index 7
9IF LateReturns[Index] = 0test LateReturns[7] is 0: true, so the THEN lines run
test LateReturns[7] is 0: true, so the THEN lines run
11ZeroCount ← ZeroCount + 16ZeroCount 65 + 1
5 + 1
12CurrentRun ← CurrentRun + 13CurrentRun 32 + 1
2 + 1
13IF CurrentRun > LongestRuntest 3 > 2 is true, so the next line runs
test 3 > 2 is true, so the next line runs
15LongestRun ← CurrentRun3LongestRun 3a new longest run
a new longest run

The whole trace: one row for each index

IndexInputZeroCountCurrentRunLongestRunWhat decided it
start000lines 5 to 7 set all three to 0
lines 5 to 7 set all three to 0
pass 1001110 = 0: ZeroCount and CurrentRun + 1; 1 > 0, so LongestRun ← 1
0 = 0: ZeroCount and CurrentRun + 1; 1 > 0, so LongestRun ← 1
pass 2102220 = 0: ZeroCount and CurrentRun + 1; 2 > 1, so LongestRun ← 2
0 = 0: ZeroCount and CurrentRun + 1; 2 > 1, so LongestRun ← 2
pass 32303 is not 0: CurrentRun ← 0; LongestRun keeps 2
3 is not 0: CurrentRun ← 0; LongestRun keeps 2
pass 430310 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays
0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays
pass 54202 is not 0: CurrentRun ← 0; LongestRun keeps 2
2 is not 0: CurrentRun ← 0; LongestRun keeps 2
pass 650410 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays
0 = 0: ZeroCount and CurrentRun + 1; 1 > 2 is false: LongestRun stays
pass 760520 = 0: ZeroCount and CurrentRun + 1; 2 > 2 is false: LongestRun stays
0 = 0: ZeroCount and CurrentRun + 1; 2 > 2 is false: LongestRun stays
pass 8706330 = 0: ZeroCount and CurrentRun + 1; 3 > 2, so LongestRun ← 3
0 = 0: ZeroCount and CurrentRun + 1; 3 > 2, so LongestRun ← 3
pass 98101 is not 0: CurrentRun ← 0; LongestRun keeps 3
1 is not 0: CurrentRun ← 0; LongestRun keeps 3
endoutput ZeroCount 6 and LongestRun 3
output ZeroCount 6 and LongestRun 3
IndexInputZeroCountCurrentRunLongestRun
00111
10222
23202
30312
42302
50412
60522
70633
81603
Your turn

1 The first four inputs are 0, 1, 0, 0 and the rest are 2. What are ZeroCount and LongestRun?

2 Which variable answers “what was the longest stretch with no late returns?”

3 What must change to find the longest run of days with more than 2 late returns?

  1. 1
    ZeroCount 3, LongestRun 2 (the run 0, 0 at indexes 2 and 3)
  2. 2
    LongestRun
  3. 3
    the condition becomes IF LateReturns[Index] > 2; the counting and reset stay the same (rename the variables and outputs to match)
Tick what you can do now
Practise with s26/22 Q10; s26/23 Q10
18 / 18