Isaac Cs Ocr Book 2022
Isaac Cs Ocr Book 2022
Except where otherwise stated, the teaching material in this book is made
available for you to copy and adapt under the under the terms of the UK
Government’s Open Government Licence v3.0, which can be viewed at www.
nationalarchives.gov.uk/doc/open-government-licence/version/3
Typeset in LATEX
A catalogue record for this publication is available from the British Library
This book of computer science exercises will help you to master the concepts of
computer science typically covered in a sixth form course. It includes:
• Over 300 questions covering all of the A level Computer Science topics
• Space to write and work out answers
Each question has been categorised into one of four levels. The levels are explained
as follows:
To help you navigate the workbook, the questions are numbered according to the
following convention: topic number, level number, question number. For example,
1.1.4 is in the first topic (‘Network fundamentals’), it is level 1, and it is the fourth
question of that level in that topic.
Acknowledgements
The questions in this book have been created by a dedicated team of teach-
ers and members of the Raspberry Pi Foundation team. We would like to
give a huge thank you to the following people:
Mac Bowley, Michael Conterio, Stuart Davison, Diane Dowling, Matt Guest,
Alan Harrison, Sam Isaacs, Michael Jones, Peter Kemp, Eirini Kolaiti, Duncan
Maidens, Martin O’Hanlon, Alex Parry, Laura Sach, Cris Thoseby, Dan
Toms, Jonathan Torbitt, Katie Vanderpere-Brown, Caroline Vaan-Canning
and Eliot Williams
We would like to thank Martyn Colliver, Roger Davies and Steve Rich for
their tireless QA efforts.
We would also like to thank the University of Cambridge and Isaac Phys-
ics team including Alastair Beresford, Andy Rice, Andrea Franceschini, Ben
Hanson, James Sharkey and Meurig Thomas.
Finally, thanks to all those on the operations side, Jan Ander, Sam Alder,
Rosa Brown, Sean Callow, Alex Carter, Dan Fisher, Jenni Fletcher-McGrady,
Faye Magellan, Jenny Laidlaw and Sian Harris for helping pull everything
together.
iv
Year 12
Autumn term
Programming Theory
Procedural programming Representation of numbers
Programming concepts Compression
String handling Encryption
Subroutines
File handling
IDE’s
Spring term
Programming Theory
Object-oriented programming Software
Operating systems
High- and low-level programming lan-
guages
Translators
Boolean logic
Systems architecture
Summer term
Programming Theory
Event-driven programming Memory and storage
Software engineering principles Hardware
Programming project/NEA Database concepts
SQL
v
Year 13
Autumn term
Programming Theory
Recursion Computational thinking
Software project Data structures
Program design Searching
Testing Sorting
Pathfinding
Complexity
Spring term
Programming Theory
Programming project/NEA Network fundamentals
Network hardware
The Internet
Web technologies
Network security
Summer term
Programming Theory
Programming project/NEA Legislation
Impacts of technology
Social engineering
Malicious code
Managing security threats
Contents
Acknowledgements iii
Computer networks 1
1 Network fundamentals . . . . . . . . . . . . . . . . . . . . . 1
2 The internet . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3 Network hardware . . . . . . . . . . . . . . . . . . . . . . . . 19
4 Communication . . . . . . . . . . . . . . . . . . . . . . . . . 22
5 Web technologies . . . . . . . . . . . . . . . . . . . . . . . . 23
Computer systems 34
6 Systems architecture . . . . . . . . . . . . . . . . . . . . . . 34
7 Memory and storage . . . . . . . . . . . . . . . . . . . . . . 47
8 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
9 Software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
10 Operating systems . . . . . . . . . . . . . . . . . . . . . . . 60
11 High- and low-level languages . . . . . . . . . . . . . . . . . 63
12 Translators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
13 Boolean logic . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Cybersecurity 107
14 Malicious code . . . . . . . . . . . . . . . . . . . . . . . . . . 107
15 Network security . . . . . . . . . . . . . . . . . . . . . . . . . 112
16 Managing security threats . . . . . . . . . . . . . . . . . . . 116
vi
CONTENTS vii
1 Network fundamentals
A network is a group of devices connected together to communicate with
each other and share resources. Networks may be structured in different
ways (called topologies), and may also be client–server or peer-to-peer
networks. There are benefits and drawbacks of each network structure,
which must be considered when choosing how to network devices.
▶ Joachim has moved to a new house and wants to set up a wireless network.
He has been told that his wireless access point is dual-band and supports
both 2.4GHz and 5GHz frequency bands. What is the benefit of having
access to the higher frequency band on a wireless network?
⃝ The network should extend over a wider range, because signals on the
higher frequency band have further reach.
1
2 1. NETWORK FUNDAMENTALS
⃝ The more devices are connected to the network, the more collisions can
occur when more than one device attempts to transmit at the same
time.
⃝ In a bus topology, one device can’t eavesdrop on messages for other
machines because only one device can transmit at a time.
⃝ The data sent through the central cable contains a destination address
to identify the recipient, and a source address to identify the sender.
⃝ The topology consists of a central cable that all the devices are con-
nected to.
▶ Below are statements that highlight some of the differences between client–
server and peer-to-peer networking. Pick one statement that is not correct.
▶ What would be a reason for not being able to connect to a specific private
wireless network?
1.1.7 Ethernet
https://isaaccs.org/eq/gcse_net_17
⃝ All Ethernet devices can process the data received from the router,
because they all use the same protocols.
□ It’s cheaper to set up one physical LAN and then divide it into virtual
networks, rather than setting up multiple LANs.
□ Each computer can access all other computers in any virtual networks
installed.
1. NETWORK FUNDAMENTALS 5
▶ Which one of the below statements is correct for the client-server net-
working model?
⃝ There can be different types of server with each type offering a partic-
ular service.
⃝ A server can perform backup of data only if all the clients in the net-
work are switched on.
⃝ Peer-to-peer networks are very secure because every device goes through
an authentication process before it joins the network.
⃝ To join a peer-to-peer network, a device needs to share all of its re-
sources with the other devices in the network.
⃝ In a peer-to-peer network, the most powerful computer in the network
is responsible for backing up data.
⃝ In a peer-to-peer network, a device needs to be switched on in order
to be able to share its resources with the other connected devices.
1.1.13 Collisions
https://isaaccs.org/eq/net_network_10
This is where multiple signals are sent on the network at the same .
This is unavoidable on any network of more than a couple of computers.
Collisions mean that signals cannot reach their destination as they interfere
with one another.
Network devices have to account for this when sending data and will have
to data signals when a collision occurs.
Just like wired network connections, wireless network devices require network
interface controllers (NICs) to convert data to and from the network medium
being used.
▶ In this context, select all the statements that are correct.
□ Many motherboards now include NICs built directly into their cir-
cuitry.
□ The network will not allow two or more computers to transmit at the
same time because it may cause a collision.
□ Terminators will be used at the end of the cables so that the electrical
signal will not bounce back.
When two devices on a wireless network sense the network channel is idle
they could both try and send at the same time causing problems in commu-
nication. To stop this from happening, network devices can use the
A star network topology is where all the nodes are arranged in a star layout
and connected to a device at its centre point.
▶ What is the name of the device at the centre of the star which can direct
the signals to their intended recipients only?
A local hospital has a computer network that uses a bus network topology.
It is finding that the network is slow and is taking too long to retrieve patient
records. They have been advised to create a mesh network.
▶ For which of the following reasons is a mesh network the correct choice?
⃝ Mesh networks are cheap to set up and data is transmitted very quickly.
⃝ All workstations are connected to a central point, like a hub or a switch.
⃝ Mesh networks are the most reliable type of network, because data can
take a number of possible routes to get to the intended recipient.
⃝ Maintenance costs are lower on a mesh network, because they don’t
use terminators.
2 The internet
The internet is a global system of interconnected computer networks. In
order to communicate, computers must agree to use a common set of proto-
cols referred to as the TCP/IP stack. The internet facilitates a wide range
of services, including the World Wide Web, email, internet telephony, and
file sharing.
At a more advanced level, it is important to understand that standards
(as well as protocols) are essential for the internet to function. JSON and
XML are both standards for the interchange of data and provide a standard
for data exchange via the World Wide Web.
⃝ The payload
⃝ The checksum
▶ Which one of these statements about the POP email protocol is true?
⃝ When you retrieve an email, the email remains on the mail server (or
email server) as well as being downloaded to your computer.
⃝ You can use it to send emails to the mail server (or email server) but
not to retrieve them.
⃝ When you retrieve an email, the email is deleted from the mail server
(or email server) once it is downloaded to your computer.
10
2. THE INTERNET 11
When data is sent across a network it is broken into packets, each with their
own control information.
▶ Which of the following pieces of data are not part of a data packet?
⃝ Application layer
⃝ Link or data link layer
⃝ Network or internet layer
⃝ Transport layer
A router is a device that moves packets around the internet from source to
destination.
▶ Which layers of the TCP/IP stack does a router implement?
A TCP packet is generated at the transport layer of the TCP/IP stack. This
packet will be encapsulated by an IP packet for routing across the internet.
▶ What will be included in the header of the TCP packet?
▶ Assuming that no use is made of cached data, what type of domain name
server is responsible for getting the IP address of a web server and returning
it to the client?
2. THE INTERNET 13
A teacher uses her computer on the school local area network to send an
email to a colleague. The email application uses the SMTP protocol.
▶ Which layer of the TCP/IP stack will initiate the process of sending the
email?
⃝ Transport layer
⃝ Application layer
□ The DNS server looks up the IP address of the server that you want.
□ The DNS server sends your computer the relevant IP address.
□ You type the URL into your browser.
□ The web server sends your computer the webpage.
□ Your computer sends a lookup request to the DNS server.
□ Your computer sends a request to the web ’servers IP address.
14 2. THE INTERNET
The TCP/IP networking model is split into four layers. Each of these layers
has a specific purpose and supports different protocols (rules for communic-
ation).
The four layers are:
1. Application layer
2. Transport layer
3. Network layer (internet layer)
4. Link layer (data link layer)
□ Wi-Fi
□ IP
□ UDP
□ HTTP
2.3.3 Neighbourhood watch
https://isaaccs.org/eq/net_internet_09
Protocols are agreed sets of rules that allow devices to communicate with
each other. Some of the protocols used on the Internet are:
□ Retrieves emails from the email server. Deletes the remote copy of
the email once it has been downloaded to a computer.
2.3.5 Send it
https://isaaccs.org/eq/net_internet_05
Computer A
IP address: 192.16.200.123
Subnet mask: 255.255.0.0
Default gateway: 192.16.128.254
Computer B
IP address: 192.12.0.15
Subnet mask: 255.255.0.0
Default gateway: 192.12.0.1
Computer C
IP address: 192.16.200.12
Subnet mask: 255.255.0.0
Default gateway: 192.16.128.254
▶ Select all of the facts from the list below that can be determined by
studying the URL:
□ mail is a subdomain
A developer has developed a website and is now testing her work. She has
three different web browsers open at the same time so that she can compare
how the site looks in each browser.
The packets relating to each browser session will contain a lot of information.
▶ For each item of information listed, decide how each value will differ for
each of the three sessions and write a number in the box.
Information Result
Source IP address
Destination IP address
Source MAC address
Destination MAC address
Source port
Destination port
3 Network hardware
Computer systems need dedicated hardware to be able to communicate
across computer networks. Network hardware is any hardware device that
is used to create a network. This includes a wide range of devices such as
network interface controllers and routers, cables between devices, and
specialist hardware used in wireless networks.
⃝ Fibre-optic cable
⃝ WiFi
⃝ Coaxial cable
⃝ A UTP cable can reliably carry electrical signals for long distances.
19
20 3. NETWORK HARDWARE
4.1.1 Bandwidth
https://isaaccs.org/eq/gcse_net_03
4.1.2 Protocols
https://isaaccs.org/eq/gcse_net_08
22
5 Web technologies
HTML and CSS are markup languages used to create a webpage. It is
possible to combine these with the programming language JavaScript to
process and display data dynamically on a webpage. Search engines index
pages and can be used to locate the information that you need in the vast
array of data on the World Wide Web.
23
24 5. WEB TECHNOLOGIES
□ You can include a schema that provides constraints on the file contents
5. WEB TECHNOLOGIES 25
• Cakes
• Tea
• Toasties
▶ What HTML tag would you use to begin a list which looks like the one
on Dolly’s website?
▶ Dolly has realised she missed coffee off the list. What line of code would
she need to add to the existing list code in order to add an additional bullet
point for ‘Coffee’?
26 5. WEB TECHNOLOGIES
5.1.5 Jumpa C
https://isaaccs.org/eq/prog_gui_06
Rachel is making a website about her favourite rapper, Jumpa C. She has
seen a style on another website which she likes and wants to reproduce for
her own website:
Here is part of the code on Rachel’s page. It is intended to create a box that
looks similar to the one above.
▶ What code should be written in the blank spaces to make Rachel’s page
look like the one in the screenshot above?
1 <style >
2 __________________ {
3 background -color: pink;
4 font -size: 50 px;
5 ____________________ : Courier ;
6 border -width: 5px;
7 border -style: _________________ ;
8 border -color: blue;
9 width : 250 px;
10 }
11 </style >
12
13 <div class='info_box '>
14 Jumpa C
15 </div >
5. WEB TECHNOLOGIES 27
▶ Tim is new to web development and has started some code for a website.
He has written some code for the main heading on his website like this:
1 <h1 style ='color : green; font -size: 40px '>Tim 's website </h1 >
What advice would you give Tim for improving his code?
Heddon has found some JavaScript code in a program that someone else has
written, but she is struggling to understand how it works.
1 var a = 25, b = 5;
2 while ( a >= b ){
3 a = a - b;
4 }
5 document .write (a. toString ());
▶ Number the statements in the correct order to describe the effect of each
line of code. One of the statements is incorrect and should be discarded.
5.3.2 Go Jaguars!
https://isaaccs.org/eq/prog_gui_07
Jianyu has written some HTML and CSS code for his website about his
favourite sports team. Here is Jianyu’s code:
1 <style >
2 # team_facts {
3 font -size: 20px;
4 width : 300 px;
5 height : 200 px;
6 font - family : Comic Sans MS;
7 border - style: solid ;
8 border - color: black ;
9 padding : 10 px;
10 }
11
12 h3 {
13 color : red;
14 font -size: 30 px;
15 }
16 </style >
17
18 <div id='team_facts '>
19 <h3 >My favourite team </h3 >
20 Go Jaguars !
21 </div >
▶ Which of the options would be the output produced by this code? The
screenshots of the code are not to scale.
Answer:
5. WEB TECHNOLOGIES 29
A B
C D
30 5. WEB TECHNOLOGIES
5.3.3 HOWZAT!
https://isaaccs.org/eq/prog_gui_09
Here is the output from a web page about cricket, and part of the code for
this website.
5. WEB TECHNOLOGIES 31
Priyanka is the head teacher of a primary school; she has paid for a web
developer to create a new website for the school. The developer has sent her
some HTML code, but it has errors in it and the website is not displaying
properly. Priyanka has checked carefully and the image file school_exterior.jpg
does exist in the right folder, so the problem must be something else.
1 <h1 > Brookbank Primary School
2 <img scr=' school_exterior .jpg '>
3 <h3 >Head teacher 's welcome </h3 >
4
5 I would like to extend a warm welcome to you from our new
website .
Jodie is making a website for her dance studio which runs dance classes for
young people aged 5–18. She charges £5 per session for under 10s and £6.50
per session for children aged 10 and above. If you book more than one child
into the same class, there is a 10% discount on the total price.
Jodie enjoys coding as a hobby and
she has written some JavaScript code
to use on her website so that people
can calculate the cost of attendance.
Her page contains a form which looks
like this:
The data from this form is sent to a JavaScript subroutine to be processed,
and the code for this subroutine is below. The subroutine triggers a pop-up
box to inform the user how much they need to pay.
Lines 2 and 3 gather the number typed into the text boxes on the form, and
convert each number into a real or ‘floating point’ number. Line 9 formats
the total to two decimal places, so that it formats properly as currency, e.g.
5.00. On line 10, the .toString() method converts the total into a string
so that it can be concatenated. It is the JavaScript equivalent to str()
▶ What should Jodie put in the missing parts to complete her code?
1 function calculate_price (){
2 var under_10s =
parseFloat ( document . getElementById ('u10 ').value);
3 var tenplus =
parseFloat ( document . getElementById ('10plus '). value);
4 var total = ( under_10s * 5) + ( _______________________ );
5 var num_kids = under_10s + tenplus ;
6 if( ______________________ ){
7 total = __________________ * 0.9;
8 }
9 total = total . toFixed (2);
10 __________________ ('You will pay £' + total. toString ());
11 }
Computer systems
6 Systems architecture
Systems architecture refers to the structure of the internal components
of a computer system. Modern computers often have a von Neumann
architecture, which involves: a processor; a memory unit, which stores
both instructions and data; connections for input and output devices; and
secondary storage for data. The fetch-decode-execute cycle describes
how instructions are retrieved and processed in order to run a program.
Several factors affect processor performance, including the number of cores
and the size of the cache.
▶ Select the statement that accurately describes a factor that affects pro-
cessor performance.
⃝ Having more than one core (processing unit) always causes processor
performance to deteriorate because tasks need to be split up in order
to run in parallel.
⃝ Increasing the amount of cache memory improves processor perform-
ance because the cache stores the instructions that are used less fre-
quently, which frees up space in the main memory.
⃝ Increasing the amount of cache memory causes processor performance
to deteriorate because instructions need to be copied from cache to the
main memory.
⃝ Increasing the clock speed improves processor performance because it
ensures that the processor will execute more instructions per second.
34
6. SYSTEMS ARCHITECTURE 35
▶ Select one statement that describes one operation that happens in the
fetch phase of the fetch-decode-execute cycle.
⃝ The arithmetic and logic unit (ALU) carries out the instruction.
⃝ Laptop
⃝ Central Heating
⃝ Medical Equipment
⃝ Digital clock
⃝ Microwave
⃝ Vending Machine
36 6. SYSTEMS ARCHITECTURE
⃝ Dishwasher
⃝ Register
⃝ ALU
⃝ Bus
⃝ Control unit
▶ When comparing two processors which are identical except for the clock
speed - which of the following statements will be true about the processor
with the higher clock speed?
6.1.7 Tick-tock
https://isaaccs.org/eq/gcse_sys_16
The clock is used to synchronise the operations of the processor. Its speed
is measured in cycles per second, and expressed in hertz (Hz), where 1Hz is
one cycle per second.
My computer system has a published processor speed of 3.3 GHz.
▶ How many cycles per second is my processor designed to operate at?
⃝ 3,300,000,000
⃝ 3.3
⃝ 3,300
⃝ 3,300,000
□ The memory address register holds the address in main memory that
is currently being read or written.
□ The program counter keeps track of the memory address of the instruc-
tion that needs to be executed next.
□ The accumulator is a data register that can be used to store the results
of calculations.
□ The memory data register holds data fetched from memory or data
waiting to be stored in memory.
⃝ The fetch-decode-execute cycle uses the the arithmetic logic unit (ALU)
to connect the registers to the main memory.
▶ Which one of the following CPU components is used to reduce how long
the processor has to wait for data and instructions?
⃝ Cache
⃝ Bus
▶ Which one of the following statements describes the decode stage of the
fetch-decode-execute cycle?
⃝ The results of the calculations that took place are stored back to the
main memory.
⃝ The control unit (CU) works out what the instruction is about.
⃝ The arithmetic and logic unit (ALU) carries out the instruction.
▶ Which of the functions below is performed by the control unit during the
fetch-decode-execute cycle?
⃝ The contents of a memory location are erased after they are read
▶ Which of the below statements describes a way that can be used to improve
processor performance?
There are two computers, computer A has a single core processor, while
computer B has a quad core processor.
Computer B has more cores than computer A and therefore it will perform
more efficiently - as long as the required tasks to be carried out can take
advantage of computer B’s architecture.
▶ What is the name of the type of processing that computer B is capable
of?
⃝ The CIR stores temporarily data that need to be read from or written
to the main memory
⃝ The CIR stores the address of the instruction that needs to be fetched
from the main memory so that it is decoded
⃝ The CIR stores the instruction to be decoded so that it is not over-
written by additional data fetched to the MBR/MDR
⃝ The CIR stores the address of the next instruction to be executed so
that it can be fetched from the main memory
▶ The status register is one of the special purpose registers that have a
specific role to play in the fetch-decode-execute cycle.
Select the option that describes a role of the status register.
A B
Imagine a computer where RAM locations are addressed from 0 to 99. Inside
the computer an instruction is loaded from RAM. The instruction code in
denary is 622. The addressing mode used is direct addressing. The first
digit represents the instruction opcode. In this case the opcode 6 corresponds
to loading data from a memory location in RAM.
▶ When this instruction is executed, what will be the value that is stored
in the MAR?
⃝ 6
⃝ 22
⃝ 62
⃝ 622
A computer system has an address bus with 8 parallel lines. This means that
the address bus width is 8 bits. The capacity of each memory location is
16 bits (i.e. it corresponds to a word with a length of 16 bits).
▶ What is the total size of the main memory in bytes?
6. SYSTEMS ARCHITECTURE 45
The CPU is responsible for processing data and executing instructions inside
a computer, there are a number of stages that instructions must go through
before they reach the CPU.
▶ Which of the following statements about the instructions a CPU will
execute are true? (Select all that apply)
□ The instructions are translated into machine code that the processor
can understand
□ The user must enter their password to give permission for the instruc-
tions to be executed
□ The instructions are loaded into main memory from secondary storage
□ The data required for the instructions has been loaded into main
memory
▶ Number the operations below in the order they are performed during the
fetch stage of the fetch-decode-execute cycle.
⃝ Option A
Computer specification
Clock speed 3.6GHz
⃝ Option B
Computer specification
Clock speed 1.2GHz
⃝ Option C
Computer specification
Clock speed 4.6GHz
⃝ Option D
Computer specification
Clock speed 3.5GHz
7 Memory and storage
Computers have two fundamental types of memory — main memory and
secondary storage. Main memory is where data and instructions are stored
so that they can be accessed directly by the CPU. Secondary storage is
used to permanently store data such as the operating system and the user’s
files.
▶ Select three of the following statements about optical storage that are
true:
□ Optical media isn’t easily portable due to the internal moving parts
47
48 7. MEMORY AND STORAGE
Laura has planned to go hiking in Snowdonia. She wants to take photos and
videos of her trip with her digital camera and then show them to her friends,
but her camera is running out of space.
▶ Which type of storage is the most suitable in this case?
▶ Which storage device would you recommend so that Laura does not run
out of storage?
⃝ Hard drives are usually physically smaller than solid state drives, which
means that they have less capacity for backing up data.
⃝ Hard drives are prone to scratches because they have a moving read/write
head, and this can make parts of files unreadable.
Tia is calculating the amount of disk storage that her bitmapped graphic
will use. She has calculated that the total file size in bits as 12, 200, 000.
▶ How many megabytes of storage space will the file need?
▶ Number the below units of data storage into order from smallest (1) to
largest (6).
□ 9 TB
□ 8000 MB
□ 2000 bits
□ 7.8 GB
□ 200 bytes
□ 5.7 kB
50 7. MEMORY AND STORAGE
7.1.8 Back-up...
https://isaaccs.org/eq/gcse_data_14
Marik is about to back-up his mobile phone data. The back-up storage app
on his phone is reporting the following values in GB (gigabyte):
Description Size
Photos 17.25 GB
Documents 3.25 GB
Messages 21.25 GB
Other data 2.75 GB
⃝ 44,500,000,000 bytes
⃝ 5,000,500,000 bytes
⃝ 5,000,000,000 bytes
⃝ 5,500,000,000 bytes
Paula has an old computer whose system uses a 32-bit address bus width
and a 32-bit data bus. Each addressed memory location can store one byte
of data.
▶ Select the option that shows the maximum memory capacity of Paula’s
computer system in bytes:
⃝ 4000
⃝ 4
⃝ 23 2
⃝ 4294967296
□ Cache memory
□ Solid state disk (SSD)
□ Main memory
□ Magnetic hard disk (HDD)
7.3.4 Remember, remember
https://isaaccs.org/eq/gcse_sys_12
▶ Select four from the following statements about memory that are true:
□ ROM can store the code needed to load the operating system into
RAM
□ Virtual memory uses secondary storage to store data from the RAM
▶ Number the statements below into order to create one paragraph about
the characteristics of RAM and then the characteristics of ROM.
Your first day working at the supermarket was going so well, until you over-
hear your manager complaining that the barcode on a particular pack of
sweets is not working. You notice that the last number on the barcode that
your manager shows you is missing.
You know a little bit about how barcodes work and remember being taught
a manual way to check the numbers in a barcode. The final digit can be
calculated from the other numbers in the code.
The algorithm goes like this:
• Starting at the first digit in the barcode, add together every other
digit in the sequence
• Take the final digit (the least significant) from the result and subtract
it from 10
This is the number on the incomplete barcode that the manager shows you:
8 0 7 6 9 8 6 7 9 3 3
▶ Can you work out what the last digit should be so that you can type it
into the till and save the day?
54
8. HARDWARE 55
The ability to calculate the last number in a barcode from the other digits
allows the scanner to check that the input data is correct. If the data is
incorrect, a sound can be played to indicate that there has been an error.
▶ What is the name of this form of error detection?
⃝ Parity bit
⃝ Check digit
⃝ Checksum
⃝ Majority vote
▶ Pick the best output device from the list below for each person. Each
device should be selected no more than once.
□ Inkjet printer
□ Laser printer
□ Plotter
□ Digital camera
□ 3D printer
□ Scanner
9 Software
Software is the word used to describe the programs that provide the in-
structions to control the computer hardware components. There are several
broad categories of software: application software provides a tool for a
specific purpose (for example, a word processor), utility software helps
configure and maintain the computer, and system software controls the
hardware (for example, defragmentation software). Operating systems are
discussed in detail in the operating systems topic (Chapter 10).
□ Email software
□ Disk defragmenters
□ File managers
□ Debuggers
□ Backup software
Joshua works for a software company that releases software under a license
that grants users the rights to use, distribute, and modify the source code.
The company has a community of developers that contributes to the con-
tinuous improvement of the software code.
▶ Based on this information, which type of software is distributed by Joshua’s
company?
57
58 9. SOFTWARE
⃝ Utility software
⃝ General purpose software
⃝ Program translators
10.1.1 Types of OS
https://isaaccs.org/eq/sys_os_12
▶ A call centre has upgraded its company server so that the operating system
allows each user to sign in remotely and share the processor time. This allows
hundreds or even thousands of employees to access and share resources,
including to run programs at the same time. Select the option that best
describes the type of operating system the call centre has upgraded to:
60
10. OPERATING SYSTEMS 61
10.3.1 Me first!
https://isaaccs.org/eq/sys_os_11
▶ In which order will the jobs complete under each of the following schedul-
ing algorithms?
Round robin
(assume a time slice of 1 minute): Shortest job first:
Machine code represented as binary is really difficult for humans to read and
write. Programmers use hexadecimal to represent binary numbers instead.
▶ What is the hexadecimal representation of this machine code instruction?
0001 0000 0000 1101
63
64 11. HIGH- AND LOW-LEVEL LANGUAGES
⃝ Data
⃝ Data or a memory location
⃝ Data and a memory location
⃝ Memory location
In a 32-bit machine code instruction, 10 bits are used for the fundamental
operation (e.g. add), 2 bits are used for the addressing mode, and 20 bits
are used for the operand(s).
▶ How many different addressing modes can be supported with this struc-
ture?
Answer:
11. HIGH- AND LOW-LEVEL LANGUAGES 67
An assembly language program has been written, which achieves the same
outcome as the high-level program. Some statements have been indented to
improve readability. The last two lines of the assembly language program
are:
x DAT 10
y DAT 1
▶ Put the assembly language statements below in the correct order to pro-
duce a program that is equivalent to the high-level program above.
□ SUB y
□ top LDA x
□ end HLT
□ BRA top
□ BRZ end
□ STA x
12 Translators
A translator is a piece of software that handles the translation of source
code into a form that can be executed by a processor. Interpreters, com-
pilers, and assemblers are all types of translator, but the choice of trans-
lator depends on the situation in which it is used.
At a more advanced level, you will explore the multiple stages of translation
between source code and object code.
▶ Put the following stages of translation in the order carried out by a com-
piler:
□ Syntax analysis
□ Code optimisation
□ Code generation
□ Abstract syntax tree generation
□ Lexical analysis
12.1.2 Interpretation
https://isaaccs.org/eq/sys_trans_01
⃝ It syntax-checks the whole program, reports any errors, and then ex-
ecutes the program.
⃝ It syntax-checks each line of source code, halting when an error is
found.
⃝ It syntax-checks the whole program and reports all the errors at the
end of the process.
⃝ It syntax-checks each line of source code (halting if an error is found),
and then translates and executes the code one line at a time.
68
12. TRANSLATORS 69
Here is a piece of source code that will be compiled. As part of the process,
an abstract syntax tree (AST) will be produced.
while num1 != num2:
if num1 > num2
In the AST shown below, each node will contain one code element.
▶ Fill in the element which will appear at each node.
70 12. TRANSLATORS
• identifier
• literal
• leftpar
• rightpar
• quote
• number
• assignment
• comma
• keyword
The tokens used for the first line are: identifier, assignment, quote, literal,
quote
▶ What is the correct order of tokens that the compiler produces for the
second and third lines of code?
12. TRANSLATORS 71
□ Object code
□ Compiler
□ Source code
□ Linker
□ Executable file
13.1.1 Order!
https://isaaccs.org/eq/sys_bool_21
□ BRACKETS
□ OR, NOR, XOR
□ NOT
□ AND, NAND
72
13. BOOLEAN LOGIC 73
Select the correct truth table for an XOR gate from the options shown below.
A B
A B Q A B Q
0 0 1 0 0 1
0 1 1 0 1 0
1 0 1 1 0 0
1 1 0 1 1 0
C D
A B Q A B Q
0 0 0 0 0 0
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 1
Answer:
74 13. BOOLEAN LOGIC
▶ Select the correct truth table for the logic gate represented by this symbol:
A B
A B Q A B Q
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1
C D
A B Q A B Q
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
Answer:
13. BOOLEAN LOGIC 75
▶ Select the correct truth table for the logic gate represented by this symbol:
A B
A B Q A B Q
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1
C D
A B Q A B Q
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
Answer:
76 13. BOOLEAN LOGIC
▶ Select the correct truth table for the logic gate represented by this symbol:
A B
A B Q A B Q
0 0 0 0 0 0
0 1 0 0 1 1
1 0 0 1 0 1
1 1 1 1 1 1
C D
A B Q A B Q
0 0 0 0 0 1
0 1 1 0 1 1
1 0 1 1 0 1
1 1 0 1 1 0
Answer:
13. BOOLEAN LOGIC 77
▶ Circle the correct truth table for the logic gate represented by the following
symbol.
A B OUTPUT A B OUTPUT
0 0 0 0 0 0
0 1 1 0 1 1
1 0 1 1 0 1
1 1 1 1 1 0
A B OUTPUT
0 0 0 A OUTPUT
0 1 0 0 1
1 0 0 1 0
1 1 1
▶ The circuit diagram below shows a circuit with four NAND gates. Identify
which single logic gate can replace all four gates in the diagram to represent
the same logic.
⃝ NOT
⃝ OR
⃝ XOR
⃝ AND
⃝ Associative
⃝ Distribution
⃝ Commutative
⃝ Absorption
13. BOOLEAN LOGIC 79
⃝ Distribution
⃝ Absorption
⃝ Commutative
⃝ Associative
⃝ Distribution
⃝ Associative
⃝ Absorption
⃝ Commutative
⃝ Associative
⃝ Absorption
⃝ Commutative
⃝ Distribution
80 13. BOOLEAN LOGIC
⃝ Distribution
⃝ Commutative
⃝ Associative
⃝ Absorption
▶ Select the correct Boolean expression for the given truth table.
⃝ ¬B ∧ A ∨ B
⃝ ¬B ∨ A ∨ B
⃝ ¬B ∨ A ∧ B
⃝ B∧A∨B
A B C D
1 1 1
Output:
13.3.11 Is it true?
https://isaaccs.org/eq/sys_bool_34
⃝ A ∧ ¬A = 0
⃝ A ∧ ¬A = 1
⃝ A ∨ ¬A = 1
⃝ A∨0 = A
82 13. BOOLEAN LOGIC
A watering sprinkler (W) is on when the timer (T) is set, the temperature
(C) exceeds 26◦ Celsius, and the rain sensor (R) does not detect rainfall.
▶ Select the correct logic diagram for the sprinkler.
A B
C D
Answer:
13. BOOLEAN LOGIC 83
⃝ True (1)
⃝ A
⃝ False (0)
⃝ B
⃝ A
⃝ False (0)
⃝ True (1)
⃝ B
84 13. BOOLEAN LOGIC
⃝ A∨B∨C
⃝ ¬C
⃝ (A ∧ B) ∨ C
⃝ False (0)
⃝ ¬A ∧ B ∨ C
⃝ False (0)
⃝ A∧B∨C
⃝ A ∧ B ∨ ¬C
Use the laws of Boolean algebra to simplify the Boolean expression below.
B ∨ ¬B ∧ A
▶ Which of the following options shows the simplest equivalent logic?
⃝ ¬B ∨ A
⃝ A∨B
⃝ B
⃝ A
13. BOOLEAN LOGIC 85
Use the laws of Boolean algebra to simplify the Boolean expression below.
(B ∨ ¬B) ∧ (B ∨ A)
▶ Which of the following options shows the simplest equivalent logic?
⃝ 1
⃝ B∨A
⃝ 0
⃝ B ∨ ¬B ∧ A
Use the laws of Boolean algebra to simplify the Boolean expression below.
(A ∧ ¬B) ∨ (A ∧ B)
▶ Which of the following options shows the simplest equivalent logic?
⃝ A∧B
⃝ A ∧ (B ∨ ¬B)
⃝ A
⃝ 1
Use the laws of Boolean algebra to simplify the Boolean expression below.
X ∧ (Y ∨ 1)
▶ Which of the following options shows the simplest equivalent logic?
⃝ X ∧Y
⃝ X
⃝ 0
⃝ 1
86 13. BOOLEAN LOGIC
The truth table for a Boolean expression has been put into the Karnaugh
map below.
⃝ A∨B
⃝ A∧B
⃝ A⊻B
⃝ ¬A ∨ ¬B
13. BOOLEAN LOGIC 87
The truth table for a Boolean expression has been put into the Karnaugh
map below.
⃝ (B ∧ ¬D) ∨ (A ∧ ¬B)
⃝ A ∨ (B ∧ ¬D)
⃝ (¬C ∧ ¬D ∧ B) ∨ (A ∧ ¬B) ∨ (C ∧ ¬D ∧ B)
⃝ (A ∧ ¬B) ∨ (B ∧ C)
88 13. BOOLEAN LOGIC
⃝ B ∨ (A ∧ ¬C)
⃝ B ∨ ¬C
⃝ B ∨ (A ∧ ¬B)
⃝ B ∨ (A ∧ ¬B ∧ ¬C)
13. BOOLEAN LOGIC 89
A Karnaugh map has been drawn as shown below and the three blocks of
1s have been correctly identified.
The expression for the purple block is ¬C ∧ ¬D and the expression for the
yellow block is A ∧ ¬B. What is the expression for the red block?
▶ Select the simplest Boolean expression to represent the given Karnaugh
map.
⃝ ¬A ∧ C
⃝ A ∧ ¬C
⃝ A ∨ ¬C
⃝ A∧C
90 13. BOOLEAN LOGIC
A Karnaugh map has been drawn as shown below and the two blocks of 1s
have been correctly identified.
⃝ (A ∧ B) ∨ (C ∧ D)
⃝ (¬A ∧ ¬B) ∨ (¬C ∧ ¬D)
⃝ (¬A ∧ ¬B) ∧ (¬C ∧ ¬D)
⃝ ¬A ∨ ¬B ∨ ¬C ∨ ¬D
13. BOOLEAN LOGIC 91
⃝ (A ∧ ¬B ∧ D) ∨ (¬A ∧ ¬B ∧ D)
⃝ ¬B ∨ D
⃝ ¬B ∧ D
⃝ A ∧ ¬B ∧ D
92 13. BOOLEAN LOGIC
The offices at the Raspberry Pi Foundation have a security alarm that is set
automatically each evening at 6.00pm. If the alarm is armed and a person
is detected in the building, the alarm sounds (really loudly!).
Sensing that there could be a problem with the automatic alarm, the clever
technicians at Raspberry Pi made it so that the alarm will not be armed at
6.00pm if someone is still in the building. Instead, there is a manual switch
that can be used to set the alarm once the last person leaves.
▶ Complete the Boolean expression for the alarm (A) to be set to True (and
armed) when it is manually switched on, or if everyone has left the building
at 6.00pm.
13. BOOLEAN LOGIC 93
• No one can borrow a book if they have an unpaid fine on their account.
• The maximum number of books a user can borrow is six unless they
are an A level student or they have been waiting for the book for more
than four weeks.
The output B will be TRUE if the student is allowed to borrow the book.
▶ Choose the correct Boolean expression to match the logic of the problem
statement.
⃝ B = ¬D ∧ (W ∨ S ∨ ¬M )
⃝ B = ¬D ∨ (W ∨ S ∨ M )
⃝ B = ¬D ∧ (W ∨ S ∨ M )
⃝ B = ¬D ∨ (W ∨ S ∨ ¬M )
94 13. BOOLEAN LOGIC
The student has also been given Boolean expressions for some parts of the
circuit:
By using the information above, the student has correctly figured out the
literal representation for Q as:
Q = ((NOT A AND (B OR C))OR NOT(A OR B)
▶ Select the option that correctly represents the logic for the whole circuit.
⃝ Q = ¬B ∨ (A ∨ C) ∨ ¬A ∨ ¬B
⃝ Q = ¬A ∧ (B ∧ C) ∧ ¬A ∧ ¬B
⃝ Q = ¬A ∨ B ∨ C ∨ ¬A ∨ ¬B
There is more than one way to make use of the laws of Boolean algebra to
simplify the expression below:
(A ∨ B) ∧ (B ∨ C ∧ (D ∨ ¬D))
One option is:
(A ∨ B) ∧ (B ∨ C ∧ (D ∨ ¬D))
= (A ∨ B) ∧ (B ∨ C ∧ 1)
= (A ∨ B) ∧ (B ∨ C)
= B ∨ (A ∧ C)
▶ Select a method from the options below that will also simplify the Boolean
expression given above:
⃝ (A ∨ B) ∧ (B ∨ C ∧ (D ∨ ¬D))
= (A ∨ B) ∧ (B ∨ C ∧ 1)
= (A ∨ B) ∧ (B ∨ C)
= (A ∧ B) ∨ (A ∧ C) ∨ (B ∧ B) ∨ (B ∧ C)
= (A ∧ B) ∨ (A ∧ C) ∨ B ∨ (B ∧ C)
= (A ∧ B) ∨ (A ∧ C) ∨ B
= B ∨ (A ∧ B) ∨ (A ∧ C)
= B ∨ (A ∧ C)
⃝ (A ∨ B) ∧ (B ∨ C ∧ (D ∨ ¬D))
= (A ∨ B) ∧ (B ∨ C ∧ 1)
= (A ∨ B) ∧ (B ∨ C)
= (A ∨ B) ∧ (A ∨ C) ∧ (B ∨ B) ∧ (B ∨ C)
= (A ∨ B) ∧ (A ∨ C) ∧ 1 ∧ (B ∨ C)
= (A ∨ B) ∧ (A ∨ C) ∧ (B ∨ C)
= B ∨ (A ∨ C) ∧ (A ∨ C)
= B ∨ (A ∧ C)
96 13. BOOLEAN LOGIC
□ A∨1=1
□ A ∧ (A ∨ B) = A
□ A ∧ ¬A = 1
□ A ∨ B = ¬¬A ∧ ¬B
□ A ∧ (A ∨ B) = B
□ A∧1=1
The circuit diagram shown represents a full adder; a circuit that adds three
binary digits. The circuit outputs two binary digits.
13. BOOLEAN LOGIC 97
▶ Each of the following options show four rows from the truth table for the
circuit diagram shown above. Select the option that has rows that have been
completed correctly (for the given inputs).
Marco was asked to use the rules of Boolean algebra to simplify a Boolean
expression and to show his work. This is the expression he was given:
(¬A ∨ B) ∧ ¬(A ∨ ¬(B ∨ A))
Marco presented the following work to demonstrate how he simplified the
expression:
Marco’s work
= (¬A ∨ B) ∧ (¬A ∧ (B ∨ A))
= (¬A ∨ B) ∧ (¬A ∧ B ∨ ¬A ∧ A)
= (¬A ∨ B) ∧ (¬A ∧ B)
= ¬A ∧ ¬A ∧ B ∨ B ∧ ¬A ∧ B
= ¬A ∧ B ∨ ¬A ∧ B
= ¬A ∧ B
Marco took the following steps to simplify the expression:
• use of identity X ∨ X = X
• distributive law
• distributive law
The steps listed are not in the same order as the workings.
▶ Marco provided the steps in a random order and his teacher asked him to
review his answer and to write the steps in the correct order he has used it.
□ distributive law
□ distributive law
□ use of identity X OR X = X
In a test, the students are asked to use the De Morgan’s 1st Law to simplify
the following Boolean expression:
¬(¬A ∨ ¬B) ∨ B ∧ ¬A
One example of simplification was given:
¬(¬A ∨ ¬B) ∨ B ∧ ¬A
A ∧ B ∨ B ∧ ¬A
B ∧ (A ∨ ¬A)
B
▶ Select the option below that correctly used De Morgan’s 1st Law to sim-
plify the Boolean expression above:
⃝ ¬(¬A ∨ ¬B) ∨ B ∧ ¬A
¬(¬(¬A ∨ ¬B) ∧ ¬(B ∧ ¬A))
¬(¬(¬A ∨ ¬B) ∧ (¬B ∨ A))
¬(¬A ∧ ¬B ∨ ¬A ∧ A ∨ ¬B ∧ ¬B ∨ ¬B ∧ A)
¬(¬A ∧ ¬B ∨ 0 ∨ ¬B ∨ ¬B ∧ A)
¬(¬B ∧ (1 ∨ 1))
¬(¬B)
B
⃝ ¬(¬A ∨ ¬B) ∨ B ∧ ¬A
¬(¬(¬A ∨ ¬B) ∧ ¬(B ∧ ¬A))
¬(¬(¬A ∨ ¬B) ∧ (¬B ∨ A))
¬A ∧ ¬B ∨ ¬A ∧ A ∨ ¬B ∧ ¬B ∨ ¬B ∧ A
¬A ∧ ¬B ∨ 0 ∨ ¬B ∨ ¬B ∧ A
¬B ∧ (1 ∨ 1)
¬(¬B)
B
100 13. BOOLEAN LOGIC
A truth table can be used to check the logic of a Boolean expression. Con-
sider the following expression: Q = R ∨ (S ∧ ¬T )
▶ Create a truth table for the expression. There are three rows in the truth
table which produce an output (Q) of 0. What are the values of R, S, and
T for these three rows?
⃝ R = 0; S = 0; T = 0 ⃝ R = 0; S = 0; T = 0
R = 0; S = 0; T = 1 R = 0; S = 0; T = 1
R = 0; S = 1; T = 0 R = 0; S = 1; T = 1
⃝ R = 1; S = 0; T = 1 ⃝ R = 1; S = 0; T = 1
R = 0; S = 0; T = 1 R = 1; S = 1; T = 0
R = 0; S = 1; T = 0 R = 1; S = 1; T = 1
Lucia has made a circuit to control her garden lights. The circuit will have
a switch, a light sensor, and a rain sensor. The lights will come on when the
circuit is switched on, or when the light sensor detects that it is sufficiently
dark. The lights will not come on at all if it is raining.
▶ Complete the Boolean expression that will allow the garden lights (G) to
come on.
13. BOOLEAN LOGIC 101
Lucia has made a circuit to control her garden lights. The circuit will have
a switch, a light sensor, and a rain sensor. The lights will come on when the
lights are switched on or the light sensor detects that it is sufficiently dark.
They will not come on at all if it is raining.
When the input to the garden lights (G) is 1, the lights will turn on.
▶ Which of the following options shows the truth table for the circuit? Please
circle the correct answer.
A B
S L R G S L R G
0 0 0 0 0 0 0 0
0 0 1 0 0 0 1 0
0 1 0 1 0 1 0 0
0 1 1 0 0 1 1 1
1 0 0 1 1 0 0 0
1 0 1 0 1 0 1 1
1 1 0 1 1 1 0 0
1 1 1 0 1 1 1 1
C D
S L R G S L R G
0 0 0 1 0 0 0 1
0 0 1 1 0 0 1 0
0 1 0 0 0 1 0 0
0 1 1 0 0 1 1 0
1 0 0 1 1 0 0 1
1 0 1 1 1 0 1 0
1 1 0 1 1 1 0 1
1 1 1 0 1 1 1 0
102 13. BOOLEAN LOGIC
Santa has been dealing with Big Data for a long time, but now the ‘Naughty
or nice’ list that he and his elves have maintained since time immemorial
has grown too large for the team to handle.
To solve this problem, he finds his smartest elves and sets them the task of
creating a logic equation to manage the lists.
Santa gives the elves six Boolean variables to consider when evaluating sixth
form students to put on the ‘Nice’ list, and asks them to write a logic state-
ment that will organise the list.
Smart elves are not that different from smart humans: the solutions they
come up with are often complicated and difficult to understand.
When the elves leave the room, shouts of “Eureka!” can be heard across
the North Pole. Beaming with pride, the lead elf presents their equation to
Santa.
“What a mess!” Santa exclaims, ”I can’t use this.”
( )
( ) ( ) ( )
D ∨ (D ∧ F ) ∨ E ∧ (B ∧ ¬E) ∨ (¬A ∧ C) ∨ A ∧ (A ∨ F )
▶ Fill in the missing values in the truth table for the logic circuit diagram
below, given the following inputs:
A B C D E
0 0 0 0 0
0 0 1 0 0
0 1 0 1 0
0 1 1 1 1
1 0 0 0
1 0 1 1 1
1 1 0
1 1 1 1 1
104 13. BOOLEAN LOGIC
A B
C D
Answer:
A B C Q
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 1
13. BOOLEAN LOGIC 105
▶ Which of the following options shows the simplest Boolean expression that
matches the logic of the truth table?
⃝ (A ∨ B) ∧ (B ∨ C) ∧ (A ∨ C)
⃝ (A ∨ B) ∧ (B ∨ C) ∧ (A ∨ C) ∧ (A ∨ B ∨ C)
⃝ (A ∧ B) ∨ (B ∧ C) ∨ (A ∧ C)
⃝ (A ∧ B) ∨ (B ∧ C) ∨ (A ∧ C) ∨ (A ∧ B ∧ C)
A half adder is a simple circuit that adds two one-bit numbers. The circuit
has two inputs and two outputs. The inputs are labelled A and B. The
outputs are labelled C and S.
▶ Which of the following options shows the correct truth table for the half
adder?
A B
A B C S A B C S
0 0 0 0 0 0 0 0
0 1 0 1 0 1 0 1
1 0 0 1 1 0 0 1
1 1 1 0 1 1 0 1
C D
A B C S A B C S
0 0 0 0 0 0 1 1
0 1 0 1 0 1 1 0
1 0 1 0 1 0 1 0
1 1 1 1 1 1 0 1
Answer:
106 13. BOOLEAN LOGIC
Robbie has got into the festive spirit and decorated a tree in his living room.
However, he doesn’t want the lights to come on during daylight hours, or
when no one is in the house.
He has a light sensor that will detect when it gets dark and is using his
Raspberry Pi to collect geolocation data from his mobile phone and that of
his partner, Alex. You should assume that Alex and Robbie are inseparable
from their phones!
▶ Complete the Boolean expression for the switch (S) to be set to TRUE
(and turn the lights on) when it is dark and either Robbie or Alex is at
home.
S=
Cybersecurity
14 Malicious code
Malicious software (malware) is created with the intent to cause damage
to computer systems or steal data, and computer users must take steps to
mitigate these threats. There are many different forms of malware, including
a wide variety of viruses, trojans, and worms. Spyware can be used
to track your use of computer systems, and keyloggers can capture and
transmit any data that you enter into a computer system.
Fortunately, for every threat, there is a form of defence. It is essential that
everyone who uses a computer understands how their system can be exposed
to threats, and understands the importance of keeping software up-to-date
and regularly scanning for malware.
⃝ Network forensics is used to identify where a hack has come from, how
the hack was achieved, and what data might have been stolen.
107
108 14. MALICIOUS CODE
14.1.3 DDoS
https://isaaccs.org/eq/net_sec_06
⃝ A programmer reading through the code that they have written, check-
ing every branch of code, and determining what the program would
do. This typically finds logic errors.
⃝ One or more programmers looking at code written by someone else,
trying to find errors that may give rise to vulnerabilities. A code review
might find memory faults such as a buffer overflow.
⃝ Releasing the software to a limited audience of trusted users, sometimes
employees or a developer community, so that they can find bugs, before
the software is made generally available.
⃝ Using software to run automated testing of program code. This auto-
mated testing software might generate input and check that the output
is as expected. This finds runtime and logic errors quicker than humans
can.
□ Use of firewall
□ Receive and share files only with users on a local area network
⃝ Worm attack
⃝ Trojan attack
⃝ Social engineering attack
⃝ Denial-of-service attack
⃝ Encryption
⃝ Strict user access levels
⃝ Strong passwords
⃝ A firewall
14.3.4 Eavesdropping
https://isaaccs.org/eq/gcse_net_04
⃝ Encryption
⃝ Firewall
⃝ Passwords
⃝ Anti-malware software
14. MALICIOUS CODE 111
Many websites ask users to fill in and submit information. Examples include
places to type usernames, passwords, or credit card details. Often these
forms are linked to a database that can record the data. A SQL injection
occurs when hackers type malicious commands using SQL code into the
input boxes, with the intent to gain unauthorised access to the database’s
contents.
▶ Read the options below and select an example of a SQL injection.
⃝ Option A
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
⃝ Option B
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
⃝ Option C
SELECT * FROM Users WHERE Name ="Username" AND Pass ="myPassword"
⃝ Option D
SELECT * FROM Users WHERE Name ="noName" AND Pass =""
15 Network security
Computer networks are a part of everyday life, and many people will spend
at least part of their day using a device that is connected to some kind
of network. On a computer network, criminals can launch attacks from
anywhere in the world. This means that they can be hard to track down and
hard to prosecute. Access to networks can be controlled by distributing user
IDs and passwords, and by setting appropriate access rights for authorised
users. Codes of conduct and acceptable use policies can be set, to ensure
that users follow guidelines for keeping corporate data safe, and to hold
them accountable if they don’t. Backup systems and recovery procedures
will ensure that essential data can be recovered if the worst happens.
• A lowercase letter
• An uppercase letter
• A number
• A symbol
OR
□ saveEarth89
□ @1234/221B+24601!
□ fRiEnDenter
□ horsebatterycomputerstaple
□ pAsw0rd
□ aA1,aA1,
112
15. NETWORK SECURITY 113
A company wants to control which devices can use their private network.
They would like to make sure that only devices owned by their employees
are able to connect to the WiFi inside their offices.
▶ Which of the following device characteristics should the company use to
identify the devices that they will allow to connect to the network?
⃝ Device name
⃝ MAC address
⃝ Device model number
⃝ IP Address
15.1.4 Password123
https://isaaccs.org/eq/cyb_sec_01
It is good practice to use strong passwords, ie ones that are difficult to crack.
A long password is usually strong because it would take more attempts to
crack the password. However, other factors are also important.
▶ Disregarding length, which of the following passwords is the strongest?
⃝ I*saacC£S9
⃝ Awesomesauce123
⃝ The name of your pet combined with your date of birth
⃝ qwertyuiop
114 15. NETWORK SECURITY
An Acceptable Use Policy (AUP) sets out rules that an organisation’s com-
puter users must follow.
▶ Why is such a policy needed when we have a wide range of legislation that
covers computer use and misuse?
□ The organisation may want to restrict certain actions which are not
illegal.
□ Although an action may be illegal, it may take a long time for a trans-
gression to be dealt with in a court of law.
□ The user is forced to read and sign the AUP, which removes the option
for them to use lack of awareness of the rules as a defence for acting
against the rules.
Although computer networks allow users to share information, they are also
the main entrance for security issues. In some cases, personal data can be lost
or stolen, and the organisations have a legal responsibility to keep personal
data secure by preventing unauthorised access or inappropriate use. Below
are some measures that can be used to increase network security.
▶ Which option can NOT be used as an organisation’s way to increase
network security?
▶ Some firewalls use stateful inspection. Why is this more effective than
stateless inspection at stopping cyberattacks?
⃝ Dynamic filtering encrypts every packet that passes through the fire-
wall to protect users against eavesdropping or packet sniffing. There-
fore, the remote device must know the encryption key to connect.
⃝ Dynamic filtering only inspects the header of a packet, which means
that it can examine packets much more quickly in order to shut down
a cyberattack.
⃝ Dynamic filtering hides the user‘s IP address from the external network
using network address translation (NAT), thereby keeping the user’s
genuine IP address anonymous.
⃝ Dynamic filtering keeps track of open connections and checks the pay-
load of a packet as well as its header, so unexpected packets can be
blocked even after a connection is authorised.
116
Data and information
17 Representation of numbers
Numbers in everyday life are usually represented using the digits 0 to 9,
but this is not the only way in which a number can be represented. There
are multiple number base systems, which determine which digits are used to
represent a number. The number system that we are most familiar with is
called denary or decimal (base 10), but binary (base 2) and hexadecimal (hex
or base 16) are also used by computers. You can perform arithmetic calcula-
tions on numbers written in other base notations, and even convert numbers
between bases. At a more advanced level, you will learn that represent-
ing negative numbers and fractional numbers using binary is also possible.
There are several different methods, each with their own advantages and
disadvantages.
▶ Numbers can be stored using different number bases. Base 2 is binary, base
10 is denary, and base 16 is hexadecimal. Why are hexadecimal numbers
widely used?
⃝ They are easier for humans to work with than long binary numbers.
⃝ They are the only way that colour codes can be represented.
117
118 17. REPRESENTATION OF NUMBERS
You can convert denary (base-10) numbers into binary (base-2) numbers
and vice versa. In a computer system, the range of numbers that can be
represented will depend on the number of bits allocated to store them. For
example, the denary number 15 is 1111 in binary so you need at least 4-bits
to store this value.
8 4 2 1
1 1 1 1
8 + 4 + 2 + 1 = 15
▶ What is the maximum denary number that can be represented using
8-bits?
When you add two binary numbers, you can use the same method as denary
addition: working from the right (the least significant bit), add up the bits
in each column with the same place value and, if there is a carry, add it into
the next column to the left (that with a higher place value).
▶ Perform the following calculation and select the option that correctly
illustrates the method of adding the two binary numbers.
110101012 + 000101012
⃝ Option A
Carry 1 1 1 1 1 1
1 1 0 1 0 1 0 1
+ 0 0 0 1 0 1 0 1
Result 1 1 1 0 1 0 1 0
17. REPRESENTATION OF NUMBERS 119
⃝ Option B
Carry 1 1 1
1 1 0 1 0 1 0 1
+ 0 0 0 1 0 1 0 1
Result 1 1 1 0 1 0 1 0
17.1.7 Add it up
https://isaaccs.org/eq/data_numbases_15
▶ What is the result of adding 1111102 and 101012 ? Both values are un-
signed binary integers. Express your answer as an unsigned binary
integer.
⃝ 11100100
⃝ 011100
⃝ 00011100
⃝ 11100000
17. REPRESENTATION OF NUMBERS 121
▶ Convert the value 001010112 to a denary (base 10) number. The binary
value is encoded as an 8-bit two’s complement number.
▶ Convert the value 111010012 to a denary (base 10) number. The binary
value is encoded as an 8-bit two’s complement number.
⃝ +233
⃝ +105
⃝ -23
⃝ -105
122 17. REPRESENTATION OF NUMBERS
⃝ +256 to -256
⃝ +128 to -128
⃝ +127 to -128
⃝ +255 to -256
□ 01111111
□ 01001110
□ 10000000
□ 11001110
□ 11111111
17. REPRESENTATION OF NUMBERS 123
0 1 1 0 1 1 1 1
+ 0 0 1 1 1 0 0 1
Emily has picked her favourite colour for the background of her website. The
value of the colour in binary is 1010101011110000110100012 and it is too long
to remember! Help Emily by converting the number into hexadecimal.
▶ Convert the binary number into hexadecimal.
17.1.16 Zombies
https://isaaccs.org/eq/gcse_data_04
Maya is playing a video game involving zombie enemies. She wants to let
her team players know about a trap. Convert the following denary numbers
into hexadecimal and combine the answers to find out the secret message.
Secret message: 14110 23410 1310
▶ Convert the denary numbers into hexadecimal and enter the message.
124 17. REPRESENTATION OF NUMBERS
A B
FF000016 FF000016
FF149316 FF149316
FF7F5016 FF7F5016
FFE4B516 FFE4B516
C D
FF000016 FF000016
FF7F5016 FFE4B516
FFE4B516 FF149316
FF149316 FF7F5016
17. REPRESENTATION OF NUMBERS 125
Which of the following base-10 and base-16 numbers has the most bits set
to 1 after the number is converted into binary?
▶ Convert the numbers into binary and select the number that has the most
1s.
⃝ 10010
⃝ C516
⃝ A216
⃝ 7910
17.1.19 Convert it 1
https://isaaccs.org/eq/gcse_data_20
17.1.20 Convert it 2
https://isaaccs.org/eq/gcse_data_21
17.1.21 Convert it 3
https://isaaccs.org/eq/gcse_data_22
17.1.22 Convert it 4
https://isaaccs.org/eq/gcse_data_23
17.1.23 Convert it 5
https://isaaccs.org/eq/gcse_data_24
17.1.24 Convert it 6
https://isaaccs.org/eq/gcse_data_25
Kalpak has been given his last three test results by his teacher. His teacher
has given the results in binary, so Kalpak still has to work out his overall
total for the tests. Can you help Kalpak, calculate his overall test marks?
Test 1 0 0 1 0 0 0 0 1
Test 2 0 0 1 0 0 0 1 0
Test 3 + 0 0 1 0 0 1 1 0
—————————————
Answer =
⃝ 01100111
⃝ 01101001
⃝ 01100101
⃝ 00100101
Agneta has just received her latest monthly salary. She has done well this
month obtaining two bonus related payments and is putting the money to-
wards her holiday fund.
The binary numbers below represent Agneta’s bonus payments. Can you
work out the total, in binary, of Agneta’s bonus?
Bonus 1 1 0 0 1 0 1 1
Bonus 2 + 1 0 1 0 1 0 0 1
—————————————
Answer =
⃝ 111000102
⃝ 111001002
⃝ 111100102
⃝ 111101002
The binary numbers shown below are represented using sign and mag-
nitude. The smallest number is defined as the negative number that
is furthest away from 0 on the number line, and the largest number is
defined as the positive number that is furthest away from 0 on the
number line.
17. REPRESENTATION OF NUMBERS 129
▶ What is the smallest number that can be represented using sign and
magnitude with 8 bits?
⃝ 10000000
⃝ 01000000
⃝ 10000001
⃝ 01111111
⃝ 11111111
⃝ 1C7
⃝ 455
⃝ 111000111
⃝ 199
A square number is the result of a number that has been multiplied by itself.
For example, 81 is a square number because it is the product of multiplying
9 x 9. This is written as 92 (“nine squared”) in denary. When you want to
find the square of a number, you are asking for the product of multiplying
the number given, by itself, i.e. ‘square of 9’. One of the following options,
represents the square of 15 or 152 . The options below are written in different
number bases.
▶ Convert the numbers to denary and select the correct option:
▶ What is the result in denary of shifting 000001112 five places to the left
and then two places to the right?
132 17. REPRESENTATION OF NUMBERS
ASCII is a character set which in its standard form uses a 7-bit binary code
to represent each character, number and symbol on an English/American
keyboard. ASCII code tables usually display the codes in denary as well as
binary (and sometimes in hex too).
For example, the ASCII code for the uppercase letter ‘P’ is 8010 , which is
10100002 in binary. The ASCII code for the lower case letter ‘h’ is 10410 ,
which is 11010002 in binary.
A three word statement has been written using a combination ASCII codes
in binary and denary.
▶ Decode each of the characters and write the words below.
Word 1 = 7310 11100112 11000012 9710 11000112
▶ Select the denary number that is the same value as the binary number
01110011012 . The binary number is represented in unsigned fixed point
form with 6 places before the binary point and 4 places after the binary
point.
⃝ 28.8125 (or 28 13
16 or
461
16 )
⃝ 7.203125 (or 7 13
64 or
461
64 )
▶ Select the denary number that is the same value as the binary number
11001110012 to denary. It is represented in two’s complement fixed
point form with 6 places before the binary point and 4 places after the
binary point.
⃝ −3.109375 (or −3 64
7
or − 199
64 )
134 17. REPRESENTATION OF NUMBERS
▶ Select the binary number that is the same value as the denary number
1
7 16 (or 113
16 or 7.0625 as a decimal), encoding the number as an unsigned
fixed point number with 4 places before the binary point and 4 places
after the binary point.
⃝ 11110010
⃝ 01110001
⃝ 00010111
⃝ 01110010
▶ Select the binary number that is the same value as the denary number
−4 34 (or − 19
4 or −4.75 as a decimal), encoding the number as a fixed point
two’s complement number with 4 places before the binary point and 4
places after the binary point.
⃝ 10110100
⃝ 11000100
⃝ 11001100
⃝ 01001100
mantissa exponent
0 . 1 1 0 0 1 1 0 0 1 0 0
▶ Convert the floating point number into denary. Write your answer as a
signed decimal number (e.g. +3.75) - do not leave any spaces in your
answer.
mantissa exponent
1 . 0 0 1 0 1 0 0 1 1 1 1
17. REPRESENTATION OF NUMBERS 137
⃝ −1.6875
⃝ +0.578125
⃝ −0.421875
⃝ −27, 648
mantissa exponent
0 . 1 0 1 0 0 0 0 1 0 1 1
mantissa exponent
⃝
1.0111000 0010
mantissa exponent
⃝
1.0111000 1110
mantissa exponent
⃝
1.1101110 0000
mantissa exponent
⃝
0.1001000 1110
Ayeesha is flying home to see her family for the festive season. She has just
learnt about floating point representation and has decided to store the cost
of her plane ticket in her budget as a floating point binary number. Her
plane ticket costs £234.75.
▶ Convert this figure to a normalised two’s complement binary floating point
number using a 12-bit mantissa and 6-bit exponent. Which is the correct
answer?
mantissa exponent
⃝
1.00010101010 001001
mantissa exponent
⃝
0.11101010110 001000
mantissa exponent
⃝
1.11010101100 000111
mantissa exponent
⃝
0.01110101011 001001
17. REPRESENTATION OF NUMBERS 139
▶ Floating point numbers are normalised so that they can be stored with
optimum precision. Which of the following values is not properly normal-
ised?
mantissa exponent
⃝
0.011101101 0110
mantissa exponent
⃝
1.010011110 1111
mantissa exponent
⃝
1.000000001 0110
mantissa exponent
⃝
0.111010001 0100
mantissa exponent
1 . 0 0 0 0 1 0 1 0 0 0 1 0 1
mantissa exponent
⃝
1.0111101 0101
mantissa exponent
⃝
1.0111101 1011
mantissa exponent
⃝
101111.01 0000
mantissa exponent
⃝
110000.11 0000
▶ Select the correct result for the addition of binary numbers shown below.
The representation used is normalised two’s complement floating point,
with 8 bits for the mantissa and 4 bits for the exponent.
mantissa exponent
01110110 0011
+ 01001011 0100
mantissa exponent
⃝
010000110 0100
mantissa exponent
⃝
10000110 0100
mantissa exponent
⃝
01000011 0101
mantissa exponent
⃝
11000001 0111
18 Representation of text
All data on a computer system is represented using binary patterns, which
are sequences of 1s and 0s. In order to represent text, each individual letter
or character must be represented by a unique binary pattern. In order
to consistently represent characters from many different languages, these
patterns must be agreed throughout the world, through standards such as
ASCII and Unicode. Once you know how a letter is represented, you can
calculate the size of a text file and work out how much storage space is
required.
141
142 18. REPRESENTATION OF TEXT
▶ The standard ASCII code for the character 3 is 5110 . What is the ASCII
code for 9 in binary? Select the correct standard ASCII representation of 9.
⃝ 001110102
⃝ 01110012
⃝ 01011012
⃝ 000010012
⃝ 001110012
One of the encoding standards for Unicode is UTF-8. This system uses
variable-width encoding to break a character code into bytes (groups of 8
bits). A single-byte character code starts with 0 and can represent each of
the 128 characters from standard ASCII:
[0xxxxxxx]
Character codes higher than 127 start with a sequence of bits that signify
how many bytes are being used. For example, for characters that need to
be represented with two bytes, the first byte starts with 110 to indicate that
two bytes are needed. If three bytes are needed, the first byte starts with
1110.
Each of the subsequent bytes start with 10 to show they follow on from a
start byte, for instance:
[110xxxxx] [10xxxxxx]
▶ How many different character codes would it be possible to represent when
using two bytes in this way?
18. REPRESENTATION OF TEXT 143
Divya wants to send a secret message to her friend, so she has written a
program to create her own cipher. Divya’s cipher involves taking each letter
of the plaintext message and converting it to the corresponding ASCII code.
Using Divya’s program, the message “hi” would appear as:
1 plaintext - 'hi '
2 ciphertext - '104 105 '
□ There is a Unicode character set that uses only 8 bits per character.
□ The first 128 codes in ASCII and Unicode are used to represent the
same characters.
19 Representation of images
All data on a computer system is represented using binary patterns, which
are sequences of 1s and 0s. In order to represent an image, one method is to
store it as if it were a grid of coloured squares, with each colour represented
by a unique binary pattern. The image dimensions and the number of colours
used are factors that affect the size of the image file.
At a more advanced level, you will learn that images can also be stored
as mathematical equations describing shapes, which are then rendered back
into an image when viewed by the user. It is useful to know the benefits
and drawbacks of each image representation method in order to decide the
correct format in which to save a particular image.
A bitmapped graphic uses a colour depth of 3-bits and this allows for 8 dif-
ferent colours. If the number of different colours that need to be represented
increases to 30, what is the minimum new colour depth required?
▶ Write the minimum colour depth for a bitmapped image with 30 colours.
▶ What is the storage capacity required for a bitmap image with the dimen-
sions 1024 x 768 pixels that has 256 different colours, if the file metadata
takes up 20% extra space? Give your answer in kBs. Assume 1kB = 1000
bytes.
144
19. REPRESENTATION OF IMAGES 145
Naga has made an icon for a maze solving game she has created. The icon
has been created as a bitmapped graphic. It is 32 pixels wide and 32 pixels
high and uses 9 different colours.
▶ What is the total file size (excluding any metadata)? Give your answer
in bits.
Image files contain metadata which can be described as “data about data”.
When Zoe looks at the properties of one of her photos, she sees the following
information that has been extracted from the file metadata:
Property Value
Manufacturer Canon
Model EOS 250D
Date and time 2021:04:06 14:31:00
Geolocation 53.61766, -2.1552
Pixel X dimension 2240
Pixel Y dimension 1680
Flash Flash did not fire
▶ Which of the items of metadata (from the list shown) is needed to accur-
ately display the image to someone who wants to view the photo? Tick all
that apply.
□ Model
□ Pixel Y dimension
□ Manufacturer
□ Geolocation
□ Pixel X dimension
□ Flash
19. REPRESENTATION OF IMAGES 147
⃝ Multiply the resolution of the image by the colour depth and multiply
by 8.
⃝ Divide the resolution of the image by the colour depth and divide by
8.
⃝ Divide the resolution of the image by the colour depth and multiply
by 8.
⃝ Multiply the resolution of the image by the colour depth and divide
by 8.
20 Representation of sound
All data on a computer system is represented using binary patterns, which
are sequences of 1s and 0s. The most common technique used to represent
sound is sampling the sound at regular intervals and storing each sample
as a value represented by a bit pattern. The frequency of the sampling and
the level of accuracy with which the sound’s value is stored both have an
effect on the size and quality of the sound file.
⃝ You can record music using MIDI but you can’t synthesise music using
MIDI technology.
Bob wants to share a sound recording of his favourite gig with his friends.
▶ If the performance lasted 1 hour and the recording was made with a
sampling rate (frequency) of 15,000 Hz and a sample resolution (size) of 16
bits, what is the minimum size of the audio file in gigabytes?
148
20. REPRESENTATION OF SOUND 149
If a music track is recorded in stereo, there are two sets of data (one for
each of the left and right channels). A track is recorded in stereo that
lasts 3 minutes. The sample resolution (size) is 14 bits and a sampling rate
(frequency) of 55 kHz has been used.
▶ Calculate the minimum stereo storage requirements needed for this stereo
music file, in its uncompressed form. Write your answer in megabytes
(MB).
▶ What is the storage capacity required for a song that is 5 minutes long and
was recorded using 20,000 samples per second and 8 bits per sample? The
file metadata takes up 10% extra space. Give your answer in MBs. Assume
1kB = 1000 bytes.
21 Compression
Compression is a technique that reduces file size. Some compression tech-
niques are referred to as lossy, because they cause data to be lost during the
compression process. Other techniques are referred to as lossless, because
they allow the original data to be exactly reconstructed from the compressed
data. Each approach has its advantages and disadvantages. Popular com-
pression methods include run length encoding, Huffman coding, and
dictionary-based methods.
150
21. COMPRESSION 151
21.3.2 Ill-suited
https://isaaccs.org/eq/data_compr_02
▶ What degree of compression (divide the compressed size by the original file
size) will be achieved for the first two rows only? Express your answer
as a value with two decimal places.
154 21. COMPRESSION
A board for a game has been produced as a bitmap image. It has 64 squares.
Each individual square will be 80 pixels x 80 pixels. The bitmap will be
compressed using run length encoding (RLE).
▶ What colour depth (in bits) is needed to represent the range of colours?
Give your answer as a number.
Consider the following passage of text from The Picture of Dorian Gray by
Oscar Wilde.
▶ Ignoring the space needed for the dictionary, how many bytes are needed
to store the word “Beauty” in compressed form?
▶ Which of the following words from the passage will have the biggest impact
on reducing file size?
⃝ “autobiography”
⃝ “the”
⃝ “beautiful”
156 21. COMPRESSION
▶ Complete the trace table by ‘dry running’ the algorithm with an input
value of “ABBBAA”.
A student has written a basic algorithm for run length encoding (RLE). The
algorithm is shown in pseudocode below. It accepts a string of alphabetical
characters and produces a compressed version of that string. The new string
will contain a single instance of each character, followed by a number indic-
ating the number of consecutive instances of that character. The amount of
compression achieved will depend on having a certain number of repeated
characters.
▶ Fill in the missing code
22.1.1 Encryption
https://isaaccs.org/eq/gcse_net_07
⃝ jglrcrwp
⃝ jchnynsl
⃝ jcinymsl
⃝ nhlrcrxp
158
22. ENCRYPTION 159
Ewan is playing a collaborative role-playing game with his friend Kasia. The
players meet up every week to play the game and try to defeat their friend
Mac, who is the gamemaster.
Ewan wants to send Kasia a message containing some secret information
about the game before the next meeting, but he needs to be sure that only
Kasia can decrypt the message, and she must have confidence that it has
definitely come from Ewan. In particular, it would be bad if Mac could
decrypt the message, or send false messages pretending to be from Ewan!
▶ What process should Ewan and Kasia follow for the safe transfer of the
message? Number the steps in the correct order.
Caesar has received a message from you asking him for his sandwich order,
but he doesn’t want everyone else to know what he wants. He has sent you
the following encrypted message, along with a key value of 6.
ngs gtj inkkyk
▶ What does Caesar want in his sandwich?
160 22. ENCRYPTION
⃝ patching
⃝ keyloggers
⃝ digital certificate
⃝ captcha
Misha’s mum, Olga, wants to tell Misha what she is getting his sister for
Christmas. No one else must find out, so they are going to use public/private
key cryptography to communicate securely.
▶ Which key should Olga use to encrypt the message?
At Bletchley Park, Alan has sent Joan a message that he has encrypted.
He has used a substitution cipher where each letter has been substituted by
another. This is not a Caesar cipher. The substitutions are non-sequential,
but the same substituton is always made. For example, he has substituted
the letter H with the letter I.
Joan observes that one letter appears more than any other and uses her
knowledge of letter frequencies as a starting point to decrypt the message.
Alan always writes his messages in English.
DTTM DT OF MIT QOMEITF
▶ Can you help Joan decrypt the message?
162 22. ENCRYPTION
22.2.6 Codebreaker
https://isaaccs.org/eq/data_encrypt_11
It’s your first day at a new job, as a codebreaker for GCHQ, the top cyber-
security department in Britain.
They want you to get straight to work, and your first task is to crack an
encrypted message that the agency has intercepted. The message reads:
JTU ZLAWVJUB YVF BAUL FAJ BUXUWAM VFN ZFJUWWURJKVW MAGUQ. ZJ
ZL FURULLVQN PAQ TZY JA IU ZYYUQLUB ZF VF UFXZQAFYUFJ AP
AJTUQ YUF , GTALU JURTFZEKUL TU VILAQIL BKQZFC JTU PZQLJ
JGUFJN NUVQL AP TZL WZPU. TU YVN JTUF MUQTVML BA V WZJJWU
QULUVQRT AP TZL AGF VFB YVDU V XUQN PUG BZLRAXUQZUL GTZRT
VQU MVLLUB AF JA AJTUQ YUF. PQAY JTZL MAZFJ AP XZUG JTU
LUVQRT PAQ FUG JURTFZEKUL YKLJ IU QUCVQBUB VL RVQQZUB AKJ
IN JTU TKYVF RAYYKFZJN VL V GTAWU , QVJTUQ JTVF IN
ZFBZXZBKVWL .
Your commanding officer tells you that they suspect that whoever encrypted
this message used a substitution cipher.
You know that ciphers like this are susceptible to frequency analysis, so you
put the message through an algorithm that counts the frequency of each
letter. It produces the following frequency distribution:
You know that the most commonly used letter in the English language is E.
▶ Using the data that the algorithm has provided, which ciphertext letter
do you think has been used as a substitute for E?
22. ENCRYPTION 163
▶ In the UK, are the authorities (e.g. the police and MI5) allowed to demand
encryption keys?
Aran has written a program to enable him to send messages using the Caesar
cipher. The pseudocode for the program is presented below, but a statement
within a selection block is incomplete.
Assume that:
• The built-in function ASC returns the ASCII numeric code of a character
• The built-in function CHR returns the character for a given numeric
code
164
23. DATABASE CONCEPTS 165
23 Database concepts
Most organisations use databases to store, sort, and search through the data
that they hold. Databases can be as simple as a single file, and as complex
as a set of related tables, each with fields and keys. It is important that
data within a database is kept up-to-date and consistent, and it is crucial to
avoid storing the same data in multiple places.
At a more advanced level, you will learn that creating an entity relation-
ship model and designing a set of tables using the rules of normalisation is
important. Challenges arise when lots of users want to access data simultan-
eously, and you will learn that transactions and transaction processing
are needed to ensure that the data does not get out of sync.
23.2.2 Relations
https://isaaccs.org/eq/data_dbs_03
⃝ One-to-one
⃝ One-to-many
⃝ Many-to-many
Most databases have many users and allow concurrent access to tables.
▶ Which of the following situations will cause a problem (tick all that apply):
Charlie runs a dog training and agility club. There are a range of different
classes. Some classes, such as puppy training, run several times a week; while
others, such as advanced gun dog training, run only once a week. Owners
pay a monthly membership fee based on the number of dogs that they own.
As a member, they can book their dog(s) into as many classes as they like.
Charlie has an A level in Computer Science and has set up a system to
manage his business. He has designed a database to hold the data he needs.
The table descriptions are as follows:
tblOwner (OwnerId, Name , Phone , Email)
tblDog (DogName, OwnerId , Breed , Colour )
tblClass (Day, Time, ClassType , MaxPlaces )
tblBooking (OwnerId, ClassType, DogName )
When Charlie tries to use his new system, he encounters several problems.
Some of the possible issues are listed below.
▶ Select all of the issues that could arise because of the current design.
□ Charlie will not be able to book a dog into the same class the following
week.
□ Charlie will not be able to add two dogs with the same name.
□ Charlie will not be able to add two owners with the same name.
□ Charlie will not be able to record more than one dog for an owner.
□ Charlie will not be able to sort his reports by the surname of owner.
24 SQL
SQL is short for Structured Query Language, and it is a language used
for constructing statements called queries that allow you to search for,
insert, delete, and update data within a database. At a more advanced
level, you will learn that SQL queries can be used to create the structure of
a database, and complex queries can extract data from the database across
multiple tables.
Charlie runs a dog training and agility club. There are a range of different
classes. Some classes, such as puppy training, run several times a week; while
others, such as advanced gun dog training, run only once a week. Owners
pay a monthly membership fee based on the number of dogs that they own.
As a member, they can book their dog(s) into as many classes as they like.
Charlie has an A level in Computer Science and has set up a system to
manage his business. He has designed a database to hold the data he needs.
The table descriptions are as follows:
tblOwner (OwnerId, Name , Phone , Email)
tblDog (DogName, OwnerId , Breed , Colour )
tblClass (Day, Time, ClassType , MaxPlaces )
tblBooking (OwnerId, ClassType, DogName )
Charlie has two rooms; one can take a maximum of 10 dogs and the other
a maximum of 15. Because of high demand for agility training, Charlie is
switching all of these classes (basic and advanced agility) to the larger room.
He is going to use SQL to update the database accordingly.
▶ Which of the following statements is the one that Charlie needs?
168
24. SQL 169
Vanessa has made a new collage of a seascape inspired by her recent trip to
Santorini. She wants to add the details to the database.
▶ Select the correct parts for the SQL statement and number them into the
correct order. They do not all need to be used.
Vanessa wants the details of everyone who purchased a copy of any collage
that she produced in 2019. The report must display the following fields:
collage ID, print number, customer’s surname, forename, and email address.
The report must be sorted in order of customer surname.
▶ Part of the SQL statement below is missing. Using the format for express-
ing a SQL SELECT statement given in the Isaac material, identify the missing
statement.
This is the data for one of the records in the table that records sales:
Vanessa wants to see the details of all sales that were made in 2019. She
wants the report to include the surname and email address of the customer
together with the collage ID, print number, and the amount it sold for. The
report will be ordered by the date of sale. The field SaleDate has a date data
type in the database and the dates are stored as YYYY-MM-DD.
▶ Number the lines of the query into the correct order to produce the report.
□ ORDER BY tblSale.SaleDate
□ WHERE tblCustomer.CustomerId = tblSale.CustomerId
□ FROM tblSale, tblCustomer
172 24. SQL
Vanessa finds a receipt noting that a customer, David Patel, purchased print
number 12 of the collage with id 7.
The database has a record of this print being sold, but to a different customer
- Susan Green who had previously purchased print number 11 of the same
collage.
This is the contents of tblSale for the sale of print numbers 11 and 12.
tblSale
7 11 2020/05/30 100 74
7 12 2020/06/01 100 74
This is the record in tblCustomer for the customer with customerId 74. There
is no record for the customer with customerId 75.
tblCustomer
74 Green Susan s.green@fastmail.com
Vanessa concludes that an error was made when updating the database with
the sale of print number 12 and it has been assigned to the wrong customer.
24. SQL 173
Can you help Vanessa make the necessary updates to the database so the sale
of print number 12 is correctly recorded against David Patel who is a new
customer? Referential integrity is in force between tblCustomer.CustomerId
(primary key) and tblSale.CustomerId (foreign key).
▶ Select the correct SQL statements and put them into the correct order.
They do not all need to be used.
□ SET
UPDATE tblSale
CustomerId = 75
WHERE CollageId = 7 AND PrintNumber = 12
□ SET
UPDATE tblCustomer
LastName = 'Patel ', FirstName = 'David ', Email =
'david@mymail .com '
WHERE CustomerId = 74
Suhreena wants to create a program for her A level project that will allow
her to run polls that the students can participate in using the school portal.
Each poll consists of one question and any number of response options.
Each student can only vote for one option in each poll. Once a vote is
submitted, it can’t be changed. When a poll is over, it can be set as inactive.
Suhreena wants to store the polls in a relational database. The table defin-
itions for the database are as follows:
tblStudent (StudentId, FirstName , LastName , YearGroup )
tblPoll (PollId, QuestionText , IsActive , PublishedDate )
tblOption (OptionId, PollId , OptionText )
tblVote (StudentId, OptionId, SubmittedDate , SubmittedTime )
Suhreena wants to run a poll among the Y12 and Y13 students about the
impact of climate change.
• The poll options are: extreme temperatures and sea level rise.
□ UPDATE tblPoll
SET QuestionText = 'Which is a higher risk of climate change?'
SET OptionText = 'extreme temperatures', 'sea level rise'
WHERE PollId = 1
Suhreena wants to create a program for her A level project that will allow
her to run polls that the students can participate in using the school portal.
Each poll consists of one question and any number of response options.
Each student can only vote for one option in each poll. Once a vote is
submitted, it can’t be changed. When a poll is over, it can be set as inactive.
Suhreena wants to store the polls in a relational database. The table defin-
itions for the database are as follows:
tblStudent (StudentId, FirstName , LastName , YearGroup )
tblPoll (PollId, QuestionText , IsActive , PublishedDate )
tblOption (OptionId, PollId , OptionText )
tblVote (StudentId, OptionId, SubmittedDate , SubmittedTime )
Suhreena wants to produce a list with the results of the poll about climate
change. The poll has PollId = 1. She wants the list to include the names
of the students that voted in the poll, ordered by year group, and the
option that they voted for.
▶ Which one of the below SELECT statements is correct?
24. SQL 177
⃝ Option A
1 SELECT tblStudent .FirstName , tblStudent .LastName ,
tblStudent .YearGroup , tblOption . OptionText
2 FROM tblStudent , tblVote , tblPoll
3 WHERE tblStudent . StudentId = tblVote . StudentId
4 AND tblOption . PollId = tblPoll . PollId
5 AND tblPoll . PollId = 1
6 ORDER BY YearGroup
⃝ Option B
1 SELECT tblStudent .FirstName , tblStudent .LastName ,
tblStudent .YearGroup , tblOption . OptionText
2 FROM tblStudent , tblVote , tblOption
3 WHERE tblStudent . StudentId = tblVote . StudentId
4 AND tblVote . OptionId = tblOption . OptionId
5 AND tblOption . PollId = 1
6 ORDER BY YearGroup
⃝ Option C
1 SELECT tblStudent .FirstName , tblStudent .LastName ,
tblStudent .YearGroup , tblOption . OptionText
2 FROM tblStudent , tblVote , tblOption
3 WHERE tblStudent . StudentId = tblVote . StudentId
4 AND tblOption . PollId = 1
5 ORDER BY YearGroup
178 24. SQL
Suhreena wants to create a program for her A level project that will allow
her to run polls that the students can participate in using the school portal.
Each poll consists of one question and any number of response options.
Each student can only vote for one option in each poll. Once a vote is
submitted, it can’t be changed. When a poll is over, it can be set as inactive.
Suhreena wants to store the polls in a relational database. The table defin-
itions for the database are as follows:
tblStudent (StudentId, FirstName , LastName , YearGroup )
tblPoll (PollId, QuestionText , IsActive , PublishedDate )
tblOption (OptionId, PollId , OptionText )
tblVote (StudentId, OptionId, SubmittedDate , SubmittedTime )
Suhreena wants to produce a list with information on all the polls that are
active in the database. For each poll, she wants the poll question and
options, and the date it was published.
▶ Which one of the below SELECT statements is correct?
⃝ Option A
1 SELECT tblPoll .PollId , tblPoll . QuestionText ,
tblPoll . PublishedDate
2 FROM tblPoll
3 WHERE tblPoll . IsActive = 'TRUE '
⃝ Option B
1 SELECT tblPoll . QuestionText , tblOption .OptionText ,
tblPoll . PublishedDate
2 FROM tblPoll , tblOption
3 WHERE tblPoll . PollId = tblOption . OptionId
4 AND tblPoll . IsActive = 'TRUE '
⃝ Option C
1 SELECT tblPoll . PublishedDate , tblPoll . QuestionText ,
tblOption . OptionText
2 FROM tblPoll , tblOption
3 WHERE tblPoll . PollId = tblOption . PollId
4 AND tblPoll . IsActive = 'TRUE '
Data structures and algorithms
25 Data structures
Almost all programs process data in some form, and data needs to be stored
in such a way that it can be easily manipulated by program code. Very basic
(or primitive) data types such as an integer (a whole number) or Boolean
(True or False) allow you to store a single value. It is possible to combine
these primitive data types to create compound data types such as a record,
or to create more complex data structures such as arrays and lists.
At a more advanced level, static and dynamic structures are introduced,
together with abstract data types (such as stacks and queues), which al-
low more sophisticated organisation and manipulation of data, and provide
methods for adding, removing, and traversing the data.
□ Queue
□ Boolean
□ String
□ List
□ Character
□ Stack
179
180 25. DATA STRUCTURES
25.1.2 Student 13
https://isaaccs.org/eq/gcse_prog_19
A new student joins the school, and a record with the identifier student13 is
created:
1 student13 = StudentRecord
2
3 student13 . student_id = 0013
4 student13 . first_name = " Samantha "
5 student13 . last_name = " Tailor "
6 student13 . class_id = "CS01"
7 student13 . enrolled = True
However, a mistake has been made - the student’s surname was spelled
incorrectly. The school officer has typed ‘Tailor’ instead of ‘Taylor’.
▶ How would you correctly reference the field in the student record that
must be corrected?
⃝ student13.last_name
⃝ last_name: String
⃝ last_name
⃝ StudentRecord.last_name
25. DATA STRUCTURES 181
Emily was organising a competition for a charity event at her school. She
needed a program that would randomly pick four people to participate from
her class. She started by creating an array with the people who donated
money from her class.
array donations [8]
After she had added all the names, the array looked like this:
donations = ['Miguel', 'Laura', 'Mariam', 'Arthur', 'Musa', 'Magda', 'Ben',
'Diane']
1 participants = 0
2 WHILE participants < 4
3 pick = RANDOM_INT (0 ,7) # Gets a random integer between
0 and 7
4 IF donations [pick] != " Selected " THEN
5 PRINT( donations [pick ])
6 donations [pick] = " Selected "
7 participants = participants + 1
8 ENDIF
9 ENDWHILE
▶ On the day of the event, if the random numbers that Emily got were 4,
1, 7, 1, 3, what was the output of the program?
A stack is used to store the changes made to some text in a simple word
processor. Every time a change is made, the details are pushed onto the
stack. Each time the ‘Undo’ button is pressed, the last operation is popped
from the stack and the operation is undone.
The state of the stack after a few minutes of editing is shown in the table
below. The operation ‘style — Arial’ is currently at the top of the stack.
style — Arial
emphasis — italic
align — right
align — left
emphasis — normal
style — Georgia
size — 12
colour — black
The following operations are then carried out by the user in the order shown:
2. undo
3. undo
4. change size to 14
▶ How will the text be formatted at the end of the sequence of operations?
A stack has been used to store a sequence of numbers. The stack is as shown
in the table below (state 1). The number 3 is at the top of the stack.
3
71
19
At the end of a sequence of operations, the stack looks like this (state 2):
1
19
▶ Select the correct set of operations to transform the stack from state 1
to state 2.
• Adam
• Sasha
• Mohammed
• Jay
▶ To which position will front point after all the names have been enqueued?
▶ To which position will rear point after all the names have been enqueued?
▶ Which position will Mohammed occupy after all the names have been en-
queued?
25. DATA STRUCTURES 185
▶ To which position will rear point after all the names have been added?
▶ In which position will Mohammed be after all the names have been added?
186 25. DATA STRUCTURES
▶ To which position will the top pointer point after all the operations have
been carried out?
▶ When all of the operations have been carried out, which name will be at
the top of the stack?
25. DATA STRUCTURES 187
Sam wants to make sure that everyone gets a piece of the festive cake before
they go for seconds. The cake has 15 pieces and his friends are Brandon,
Millie, Dorris, Adele, Robin, and Joe.
He uses a linear queue to manage cake requests. When a person is en-
queued, it means that they have been given a piece of cake. When a person
is dequeued, it means that they have eaten their piece of cake and are ready
for another one.
The following diagram is an abstraction of a linear queue and it is used
to represent the slices of cake. At the moment, the queue is empty. The
front pointer (the fork) points to the start of the queue. The rear pointer
(the knife) points to the end of the queue. Each piece of cake is in a specific
position in the queue and the first piece is in position 0.
▶ To which position will front point after everyone has been given their first
piece of cake?
▶ To which position will rear point after everyone has been given their first
piece of cake?
▶ To which position will front point after Brandon and Millie have finished
their first piece of cake and are having seconds, but all of the other people
are still eating their first piece?
▶ To which position will rear point after Brandon and Millie have finished
their first piece of cake and are having seconds, but all of the other people
are still eating their first piece?
▶ To which position will rear point after everyone has been given their
second piece of cake?
□ When there are relatively few edges compared to the number of nodes
in the graph and the amount of memory space is a potential issue
25.2.14 Is it a tree?
https://isaaccs.org/eq/dsa_datastruct_23
Benji has written an algorithm that calculates the multiples of a given num-
ber. The algorithm:
▶ If the program is run and the value 12 is input, how many numbers will
there be in the table array?
192 25. DATA STRUCTURES
A student has written some code for a subroutine which carries out a form
of linear search. The code they have written is shown in pseudocode below:
1 FUNCTION linear_search (search_item , data_array )
2 found = -1
3 FOR count = 0 TO 49
4 IF data_array [ count] == search_item THEN
5 found = count
6 ENDIF
7 NEXT count
8 RETURN found
9 ENDFUNCTION
▶ The code has been tested and works as the student expected it to. What
is the length of the array that is being searched?
Josh creates his first record to store information about a T. rex like this:
1 t_rex = Dinosaur
▶ What line of code would Josh type to store the information that the t_rex
eats meat?
25. DATA STRUCTURES 193
Kelly is making a program to teach her baby sister some new words. First,
she created an array called words like this:
1 array words [5]
Kelly also wrote and ran some other code to add different words into the
array, so it now looks like this in the computer’s memory:
Index 0 1 2 3 4
Contents “ball” “book” “teddy” “lion” “flower”
What would the output be if Kelly ran the below code? Assume that each
output starts on a new line.
1 index = 2
2 WHILE index < 4
3 PRINT (words[ index ])
4 index = index + 1
5 ENDWHILE
▶ What would be output by the code? Assume that each output starts on
a new line.
194 25. DATA STRUCTURES
The declarations for the record structure and the array are shown below:
1 MusicRecord = RECORD
2 track_id : Integer
3 track_name : String
4 artist : String
5 duration : Time
6 ENDRECORD
7
8 ARRAY album [15]
▶ Assuming that the tracks will be added to the array in the same order
that they are arranged on the album, how would Sergiu access the name of
the fifth track on the album?
⃝ MusicRecord[5].track_name
⃝ album[4].track_name
⃝ album.track_name[4]
⃝ album[5].track_name
25. DATA STRUCTURES 195
You are creating a system for a local charity and will use a record structure
to store the information for each volunteer.
The definition of a suitable record structure to store the volunteer data is
shown below.
1 VolunteerRecord = RECORD
2 volunteer_id : Integer
3 first_name : String
4 last_name : String
5 date_of_birth : Date
6 email : String
7 active : Boolean
8 ENDRECORD
The following pseudocode shows the process of storing the details of a vo-
lunteer called Raj Whelen.
1 volunteer1 = VolunteerRecord
2
3 volunteer1 . volunteer_id = 1
4 volunteer1 . first_name = "Raj"
5 volunteer1 . last_name = " Whelan "
6 volunteer1 . date_of_birth = "05/07/1985"
7 volunteer1 .email = " RajWhelan@abc .com"
8 volunteer1 . active = True
⃝ volunteer1.last_name + volunteer1.first_name
⃝ volunteer1.first_name + volunteer1.last_name
⃝ last_name + first_name
⃝ first_name + last_name
196 25. DATA STRUCTURES
A nursery keeps track of important details about the children who attend.
For each child, this information is stored in a dictionary like this:
1 {
2 'name ': 'Nadia ',
3 'dietary ': 'vegetarian ',
4 'emergency contact ': 'Mr Leigh ',
5 'days_present ' : ['Tuesday ', 'Wednesday ', 'Thursday ']
6 }
▶ Fill in the missing code to create the report for the kitchen.
▶ Which of the following options represents an adjacency list for the given
graph?
A B
□ if rear + 1 is equal
to maxsize then
□ end if
□ increment rear by 1
□ insert data at
queue[rear]
□ else
□ display message
"Queue is full"
Every morning, the drivers for a delivery company receive a route for col-
lecting and dropping off deliveries. Some items are collected at one location
and dropped off at another, so these locations must be visited in the right
order.
The graph shown below represents the locations for a small number of cus-
tomers. The graph is directed to show that the locations must be visited in
a particular order. This shows that a route from 2 to 6 could be made via
3 or 5, but location 6 could not be visited ahead of location 2. The delivery
company’s scheduling system uses the graph data to produce a suitable route
for each of the drivers.
▶ Which adjacency matrix represents the data for the given graph?
25. DATA STRUCTURES 199
Vertex 1 2 3 4 5 6
1 0 1 0 0 0 0
2 0 0 1 0 1 0
⃝ 3 0 0 0 0 0 1
4 0 1 0 0 0 0
5 0 0 0 0 0 1
6 0 0 0 0 0 0
Vertex 1 2 3 4 5 6
1 1
2 1 1
⃝ 3 1
4 1
5 1
6
Vertex 1 2 3 4 5 6
1 2
2 3 5
⃝ 3 6
4 2
5 6
6
Vertex 1 2 3 4 5 6
1 0 1 0 0 0 0
2 1 0 1 1 1 0
⃝ 3 0 1 0 0 0 1
4 0 1 0 0 0 0
5 0 1 0 0 0 1
6 0 0 1 0 1 0
200 25. DATA STRUCTURES
The figure below is a weighted graph that represents the distance between
the locations of six rental properties. The six properties have been labelled
with the numbers 1–6. When there is no edge between two nodes, this means
that it is not possible to travel directly between those two properties. When
there is an edge between two nodes, the edge is labelled with the distance
(miles) to travel between the two properties.
Node 1 2 3 4 5 6
1 4 5 5 3
2 3 5
⃝ 3 5 5 6
4 5 6
5 4 2 5
6 3 4
Node 1 2 3 4 5 6
1 0 1 1 1 1 0
2 1 0 0 0 1 0
⃝ 3 1 0 0 0 1 1
4 1 0 0 0 0 1
5 1 1 0 0 1 0
6 0 0 1 1 0 0
Node 1 2 3 4 5 6
1 2 3 4 5
2 1 5
⃝ 3 1 5 6
4 1 6
5 1 2 3
6 3 4
Node 1 2 3 4 5 6
1 4 5 5 3
2 4 1
⃝ 3 5 2 5
4 5 6
5 3 1 2
6 5 6
202 25. DATA STRUCTURES
Original queue:
Reversed queue:
A stack can be used to reverse a queue and an algorithm has been developed
to do this.
1 SIZE_OF_QUEUE = 4
2
3 PROCEDURE reverse (queue , stack):
4 FOR i = 0 TO SIZE_OF_QUEUE - 1
5 item = ## MISSING OPERATION A ##
6 ## MISSING OPERATION B ##
7 NEXT i
8 FOR i = 0 TO SIZE_OF_QUEUE - 1
9 item = ## MISSING OPERATION C ##
10 ## MISSING OPERATION D ##
11 NEXT i
12 ENDPROCEDURE
25. DATA STRUCTURES 203
▶ The four missing operations to reverse the queue are shown below. Put
the operations into the correct order with MISSING OPERATION A at the
top of the list and order MISSING OPERATION D at the bottom of the
list.
□ push(item)
□ enqueue(item)
□ dequeue()
□ pop()
25.4.7 1SAAC
https://isaaccs.org/eq/dsa_datastruct_30
• the total is divided by the number of slots in the hash table using
modular division
▶ If a hash table has 55 slots (buckets) what hash value will be generated
for the key value 1SAAC?
204 25. DATA STRUCTURES
▶ To which position will front point after all the operations have been
carried out?
▶ To which position will rear point after all the operations have been carried
out?
▶ In which position will Germaine be after all the operations have been
carried out?
25. DATA STRUCTURES 205
What will be the result of running the following tree traversal pseudocode
for the tree shown? Every node contains three attributes:
• data
• left (a pointer to the node’s left child)
• right (a pointer to the node’s right child)
A graph problem often requires you to traverse every edge between the nodes
in the graph in a systematic way. This process helps identify the connected
components of the graph and find paths between nodes. Over the course of
a traversal, the state of each node progresses from unvisited to visited to
completely explored.
⃝ • For BFS : A, B, C, E, F, D, G
• For DFS : A, B, E, F, C, D, G
⃝ • For BFS : A, B, C, D, E, F, G
• For DFS : A, C, G, D, B, F, E
⃝ • For BFS : A, C, G, D, B, F, E
• For DFS : A, C, B, G, D, F, E
⃝ • For BFS : A, C, B, G, D, F, E
• For DFS : A, B, C, D, E, F, G
25. DATA STRUCTURES 207
▶ Which of the following graphs illustrates the data stored in the adjacency
list?
A B
C D
208 25. DATA STRUCTURES
• The data
Index pointers are used because the data is stored in an array. There will
be a separate index pointer to indicate the root node.
The table that follows represents a binary tree. The value of the root index
pointer is 0.
▶ What are the data values of the child node(s) of the node that has the
data value 6?
⃝ 7 and 8
⃝ 2 and 10
⃝ 2 and Null
⃝ 10 and 5
25. DATA STRUCTURES 209
A hash table has 48 slots (buckets) and hash keys are five digit numbers
such as those shown in the list below:
• 31971
• 43219
• 56342
• 96756
▶ If the keys listed are hashed using the example of the simple hashing
algorithm (shown above), what hash values will be generated?
A B
A collision occurs when a hash function produces the same hash value for
two or more keys.
A hash table has 10 slots and the following keys must be hashed:
• 8527 • 1979
• 1974 • 2021
• 1971 • 6173
• 9459 • 6579
▶ When the keys are hashed, which of the following statements is true?
As Santa’s reindeer are brought in from the icy tundra, they are added to
a binary search tree (in the order that they arrive in). Dasher is the first
to arrive, followed by Dancer, Prancer, Vixen, Comet, Cupid, Donner, and
Blitzen. The tree is stored as three one-dimensional arrays:
▶ The diagram below shows the three arrays with several missing values.
What are the missing values for [a] and [b]?
D L R
0 Dasher 1 2
1 Dancer 4 -1
2 Prancer [a] [b]
3 Vixen
4 Comet
5 Cupid
6 Donner
7 Blitzen
[a] [b]
26 Searching algorithms
When faced with the problem of searching for an item in a list of items, you
may have to deal with an unordered list. The only way to find a specific
item is to look at every item in the list one after another. This algorithm is
called a linear search. If the list of items is ordered, you can repeatedly
split the list in half and check only the half in which the item that you are
searching for might be found. This algorithm is called a binary search.
At a more advanced level, you will learn that these searching algorithms can
be implemented either iteratively or recursively. You will learn that a
binary search tree could also be used. You will also learn that the relative
complexity of each algorithm can be compared, to allow the best choice to
be made for a specific problem.
In a software project, you have four lists and need to search through them.
You have just learnt some new searching algorithms and know that linear
search is the least efficient, so you want to implement it first.
▶ From the choices below, select the list for which it would be most appro-
priate to use linear search.
212
26. SEARCHING ALGORITHMS 213
You are trying to find a movie in the media library stored on your computer,
and decide to use a binary search algorithm to do it. Here is a pseudocode
implementation of binary search:
1 FUNCTION binary_search (data_set , item_sought )
2 index = -1
3 found = False
4 first = 0
5 last = LEN( data_set ) - 1
6 WHILE first <= last AND found == False
7 midpoint = ( first + last) DIV 2
8 IF data_set [ midpoint ] == item_sought THEN
9 index = midpoint
10 found = True
11 ELSE
12 IF data_set [ midpoint ] < item_sought THEN
13 last = midpoint - 1
14 ELSE
15 first = midpoint + 1
16 ENDIF
17 ENDIF
18 ENDWHILE
19 RETURN index
20 ENDFUNCTION
▶ Your media collection has 100 titles in it. How many comparisons will be
made on your media collection while attempting to find the movie?
214 26. SEARCHING ALGORITHMS
A wildfowl trust tags the birds that visit over the year with a unique number
in order to keep track of them. The details of the birds are stored in a binary
search tree for efficient searching.
The numbers from the tags of 13 birds have been entered to a sample
binary search tree, and these are shown in the following diagram of the tree.
▶ In what order will the nodes of the binary search tree be visited when
the bird with tag number 1999 is searched for? Not all numbers need to be
used.
□ 2000
□ 650
□ 61
□ 1999
□ 1400
□ 2198
□ 126
□ 1983
□ 926
□ 630
□ 1230
□ 738
□ 1444
26. SEARCHING ALGORITHMS 215
A bird has been found with the tag number 750. In what order will the
nodes of the binary search tree be visited when searching for the tag 750 to
find out whether (or not) the tag exists in the sample binary search tree?
▶ Put only the relevant numbers into the correct order. Not all numbers
need to be used.
□ 126
□ 1983
□ 1230
□ 1999
□ 1444
□ 926
□ 2000
□ 1400
□ 2198
□ 738
□ 630
□ 650
□ 61
▶ In the example provided, what is the maximum number of nodes of the
binary search tree that will need to be examined to find any bird?
⃝ O(logn)
⃝ O(n2 )
⃝ O(n logn)
⃝ O(n)
216 26. SEARCHING ALGORITHMS
Mabel uses an app on her mobile phone to store the contact details of each
of her 251 friends. The app stores the names and addresses in an ordered
array of records. The records are ordered by name, and none of Mabel’s
friends have the same name.
Mabel uses the app to retrieve the postal addresses of selected friends so
that she can invite them to her New Year’s Eve party. The app makes use
of a binary search algorithm to locate each record.
▶ What is the maximum number of comparisons that will be required to
retrieve the details of a specific friend, by name, so that Mabel can send
them an invitation?
A warehouse has the details of 10, 000 products stored in a list, ordered by
product number.
▶ What is the maximum number of comparisons that will be made to
find a specific product, by product number, using a binary search?
26. SEARCHING ALGORITHMS 217
• ID : an ID that increments,
• student_name : the name of the student,
• volunteer : a boolean variable that specifies if they agreed to volunteer
or not.
⃝ Binary search will find the student much faster than linear search if
the array is searched by using the student_name field.
⃝ Binary search can find a student in maximum logn + 1 comparisons
(where n is the number of elements in the array) if the ID is used to
search for a student.
⃝ Linear search is the only algorithm that is suitable for finding a student
in the array if the student list is below 100 entries.
⃝ Linear search has a time complexity of O(n2 ) (where n is the number
of elements in the array) as it needs to go through the array and check
all three fields for each student.
26. SEARCHING ALGORITHMS 219
▶ Here is the binary search function, fill in the statement to calculate the
midpoint.
Bubble sort moves each item in a list up until it reaches a value that is
higher than that item. It then looks at the next item and does the same.
Once all of the items have been moved, the collection is sorted. Consider
the pseudocode below.
1 PROCEDURE bubblesort_ascending ( data_set )
2 num_items = LEN( data_set )
3 swaps = True
4 WHILE i < ( num_items - 2) AND swaps == True
5 swaps = False
6 FOR j = 0 TO ( num_items - i - 2)
7 IF ( data_set [j] > data_set [j + 1]) THEN
8 temp = data_set [j]
9 data_set [j] = data_set [j + 1]
10 data_set [j + 1] = temp
11 swaps = True
12 ENDIF
13 NEXT j
14 i = i + 1
15 ENDWHILE
16 ENDPROCEDURE
⃝ temp is used to store a copy of one of the values that is being swapped.
⃝ temp is used to store the total number of items in the list.
⃝ temp is used to count the number of comparisons between items.
⃝ temp is used to stop the algorithm when the list is sorted.
220
27. SORTING ALGORITHMS 221
List 1 List 2
⃝
Green Purple Yellow Blue Magenta Red
List 1 List 2
⃝
Blue Green Purple Red Yellow Magenta
List 1 List 2
⃝
Green Purple Red Yellow Blue Magenta
Doris is going to sort the array prime_numbers with items: [83, 73, 43,
23, 97, 67, 47, 79, 89] into ascending order using bubble sort.
▶ In which order will the items of the array be after the second pass of
the algorithm?
Martin has a list that represents the number of visits to the gym he has made,
each month, since joining some months ago. Martin wants to keep track of
the visits to make sure he is getting good value for his gym membership.
However the list is currently unordered and needs to be sorted into ascending
order.
The list currently contains 5 items:
[7, 1, 3, 8, 5]
The data will be sorted using merge sort as shown in pseudocode below.
The merge_sort function, which is recursive, makes a call to a merge sub-
routine that merges two lists, placing the items into ascending order.
▶ How many times (including the first) will the function merge_sort be
called to sort the list?
224 27. SORTING ALGORITHMS
▶ How many swaps are needed in total to sort this array into ascending
order using bubble sort?
27.1.7 Stepping up
https://isaaccs.org/eq/dsa_search_17
Anil has been keeping a record of his daily step count and has recorded the
data in an array as shown below.
Steps
14577 12434 12113 12566 12321 12707 10350
27. SORTING ALGORITHMS 225
To sort the data, into ascending order, Anil will follow the merge sort
method.
In the current step of the algorithm (step 3), the original list has been split
into seven sublists and these can now be merged.
Step 3:
▶ What will Anil expect to see as a result of the next step (step 4) which
starts the merging of the seven sublists?
The next step (step 5) of the algorithm continues with the merging of the
four sublists from the previous step.
▶ What will Anil expect to see as a result of the next step (step 5) which
merges the four sublists from the previous step (step 4)?
List 1 List 2
⃝
12113 12434 12566 10350 12321 12707 14577
List 1 List 2
⃝
14571 12566 12434 12113 12707 12321 10350
List 1 List 2
⃝
12113 12434 12566 14577 10350 12321 12707
226 27. SORTING ALGORITHMS
Pam Singh‘s computer science students have done a class test and their
scores have been recorded on Pam’s tracking sheet. The tracking system
allows Pam to sort the data on a specified field and Pam wants to sort it so
that the student with the highest score appears at the start of the list.
An insertion sort will be used to sort the data.
▶ Number the lines into the correct order to show the state of the list
of scores as the data is progressively sorted (i.e. as each item is correctly
positioned).
The initial order of the list is: 43, 74, 64, 68, 49, 70
⃝ Quick sort performs better than merge sort in the worst case.
⃝ Quick sort will out perform merge sort if an optimal pivot value is
chosen.
27. SORTING ALGORITHMS 227
The list will be sorted using the insertion sort algorithm. This algorithm
works by building up a sorted sublist at the lower part of the original list.
To do that, one by one the items in the list are examined and inserted into
the correct position in the sorted sublist.
The following pseudocde subroutine is an implementation of the insertion
sort algorithm. There is a block of code missing.
▶ Put the statements into the correct order to complete the missing part of
the code.
1 PROCEDURE insertion_sort ( items)
2 num_items = LEN( items)
3 FOR index = 1 TO num_items - 1
4 item_to_insert = items[index]
5 previous = index - 1
6 >>>> [ missing block of code] <<<<
7 NEXT index
8 ENDPROCEDURE
□ items[previous
items[previous]
+ 1] =
□ previous = previous - 1
□ items[previous
item_to_insert
+ 1] =
□ ENDWHILE
228 27. SORTING ALGORITHMS
The quick sort algorithm works by selecting a pivot value and partioning
the list around that value. The process is repeated for each partion until it
contains a single element. Assuming that:
• the first value in the partition is selected as the pivot value every time
a new partition is processed
• the process is recursive with the left partition being processed before
the right partition
⃝ 50 and 7
⃝ 43 and 35
⃝ 80 and 35
⃝ 21 and 64
position 0 1 2 3 4 5 6
value 67 589 166 222 300 115 352
The list will be sorted using the insertion sort algorithm. This algorithm
works by building up a sorted sublist at the lower part of the original list.
To do that, one by one the items in the list are examined and inserted into
the correct position in the sorted sublist.
▶ What is the position that 589 will take the first time it is moved to a
different position in the list, as part of the sorting process.
230 27. SORTING ALGORITHMS
▶ Fill in the four missing code statements (lines 16, 20, 24 and 33).
The quick sort algorithm repeatedly partitions a list around a pivot value.
The pivot value is chosen using a specified rule as part of the algorithm, for
example, the last item in the partition may be used.
A major supplier of electronic components uses a system with a feature
that displays the components in alphabetical order (by name). Although
the supplier has tens of thousands of components in their inventory, the
list is fairly static (i.e. it is fairly rare for new components to be added or
components to be deleted). However, occasionally, changes to the product
list are made.
The users of the system have complained that the alphabetical product list
takes a long time to display. It has been suggested to the programmer (by
their team leader) that the rule that determines the choice of pivot value
might be a problem.
▶ Which of the following options for the pivot value is the most likely to
be causing the problem when sorting a list that is already substantially in
order?
Your classmate asks you for help in picking an efficient sorting method to
use in his zoo application.
He wants to sort the list of animals below into alphabetical order:
animals = [‘aoudad’, ‘camel’, ‘cheetah’, ‘crow’, ‘baboon’, ‘deer’, ‘hare’, ‘leo-
pard’, ‘mink’, ‘peccary’, ‘moose’, ‘mule’, ‘parrot’]
▶ Which of the below statements is correct?
⃝ Merge sort will be the most efficient choice because it has the lowest
time and space complexity.
⃝ Bubble and insertion sort will take the same amount of time to sort the
list because they both have a time complexity of O(n<sup>2</sup>).
⃝ Bubble sort will make the fewest comparisons because it stops as soon
as the list is sorted.
⃝ Insertion sort will make the fewest comparisons because the list is
almost sorted.
Kofi has written a program to sort an array of data into descending order.
The algorithm is a version of bubble sort and is shown in pseudocode below.
1 # Initialise variables
2 items = [28 , 40, 21, 25, 30, 27, 25]
3 num_items = LEN( items)
4 temp = 0
5 pass_number = 1
6 swapped = False
7
8 # Continue while swaps have been made and there are more
passes to evaluate
9 WHILE swapped == True AND pass_number <= num_items - 1
10 swapped = False
11 FOR index = 0 TO num_items - 2
12 # Check if items are out of order
13 IF items[ index] > items[index + 1]
14 # Swap items
15 temp = items[ index]
27. SORTING ALGORITHMS 233
There is a problem with the algorithm and it will not sort the data correctly.
▶ What is the problem?
⃝ O(nlogn), as there will be (at most) n passes through the list and for
each pass there will be (at most) logn comparisons.
⃝ O(2n), as there will be (at most) n − 1 passes through the list and for
each pass there will be (at most) n + 1 comparisons.
⃝ O(n), as there will be (at most) 1 pass through the list and for that
pass there will be (at most) n − 1 comparisons.
⃝ O(n2 ), as there will be (at most) n − 1 passes through the list and for
each pass there will be (at most) n − 1 comparisons.
234 27. SORTING ALGORITHMS
The insertion sort algorithm has the same time complexity as the bubble
sort: O(n2 ).
▶ Which of the following statements correctly describes the reason why the
time complexity of the insertion sort is expressed as O(n2 )?
⃝ Starting with the second item, the list is fully traversed once, which is
n − 1 operations. For each item to be correctly positioned, a maximum
of n − 1 items will be compared and moved.
⃝ The whole list of items is processed n times. On each iteration, one
item is being examined and all the other n − 1 items are moved to
make room to insert that item in the sorted sublist.
⃝ Starting with the first pair of items, the outer loop goes through the
list n − 1 times. In each pass, the number of items that may need to
be swapped is at most n − 1.
⃝ There are two for loops in the standard insertion sort algorithm and
each loop iterates a maximum of n times in order to ensure that each
item is inserted into the correct place.
Two sorting algorithms are quick sort and bubble sort. Two students have
been arguing about which is the best to use. Barack favours the quick sort
algorithm whereas Salome is championing the bubble sort.
Both students have written two statements in support of their favoured
algorithm but only one of the statements is correct.
▶ Which one is it?
⃝ The quick sort algorithm is more suitable for sorting large data sets
than the bubble sort algorithm.
⃝ The quick sort algorithm is better than the bubble sort algorithm for
sorting a set of data that is already substantially in order.
⃝ On average, the bubble sort algorithm is faster at sorting data than
the quick sort algorithm.
⃝ The bubble sort algorithm has lower space complexity than quick sort.
27. SORTING ALGORITHMS 235
Kate has written some pseudocode to sort an array of data into ascending
order. The algorithm she wrote is a version of bubble sort.
Part of the pseudocode has already been completed. The first three state-
ments and the last statement are presented below:
1 ARRAY items = [3, 8, 1, 10, 23, 78, 12]
2 num_items = LEN(items )
3 temp = 0
4
5 >>>>> missing code statements <<<<<<
6
7 ENDFOR
▶ Put the rest of the statements into the correct order to complete the
pseudocode.
□ ENDFOR
□ IFitems[index
(items[index] >
+ 1])THEN
□ FOR index = 0 TO
num_items - 2
□ ENDIF
□ FOR pass_number = 1
TO num_items - 1
□ items[index
temp
+ 1] =
□ temp = items[index]
□ items[index] =
items[index + 1]
28 Pathfinding algorithms
There is a set of problems in computer science that require us to find the
shortest path between a set of points. The applications are numerous and
commonplace — from satellite navigation to internet packet routing. See-
ing as this type of problem arises so frequently, there are some standard al-
gorithms that can be used to find a solution, such as Dijkstra’s algorithm.
Some algorithms are more efficient than others at finding the shortest path.
236
28. PATHFINDING ALGORITHMS 237
Dijkstra’s algorithm will be run to fnd the shortest path between the start
node E and all other nodes. The algorithm selects the next current node by
picking the node from the unvisited list with the lowest cost.
▶ What is the cost of the shortest path from E to D? Enter your answer as
an integer value.
▶ What is the route of the shortest path from E to B? Select your answer
from the options shown below.
⃝ E-G-C-H-B
⃝ E-G-H-B
⃝ E-A-H-B
⃝ E-G-F-B
238 28. PATHFINDING ALGORITHMS
This graph represents the network on a university campus. The nodes are
computers and the weights show how long it takes for a signal to get from
one computer to the other (in milliseconds).
Using Dijkstra’s algorithm, you can find the quickest path to all of the nodes
on the network from your starting node (highlighted in grey).
The structured English that follows defines the main steps of the algorithm.
1 While the unvisited list is not empty:
2 Set current node to the node with the lowest cost from
the unvisited list
3 Copy cost and previous values for current node from the
unvisited list to the visited list
4 Remove the current node from the unvisited list
5
6 For each neighbour of current node:
7 If neighbour is not in the visited list
8 Calculate new cost = weight of edge + cost of
current node
9 If new cost is less than neighbour 's cost in
unvisited list
10 Update the neighbour 's cost to become the new
cost
28. PATHFINDING ALGORITHMS 239
Follow the algorithm for the graph given, then answer the following ques-
tions.
Visited list
Unvisited list
Key Value Previous
S
A
B
C
D
E
F
G
H
I
Ali is planning to visit his friend Eli. The graph shown below illustrates the
connections between Ali’s house (node A) and that of Eli (node E).
Ali will use Dijkstra’s algorithm to find the shortest path between the two
houses. The algorithm selects the next current node by picking the node
from the unvisited list with the lowest cost.
▶ Which of the following options shows the final visited list that is produced
by running the algorithm?
Visited list
Node Cost (from start) Previous
A 0 none
⃝ B 12 A
C 5 A
D 11 C
E 13 D
28. PATHFINDING ALGORITHMS 241
Visited list
Node Cost (from start) Previous
A 0 none
⃝ B 8 C
C 5 A
D 11 C
E 13 D
Visited list
Node Cost (from start) Previous
A 0 none
⃝ C 5 A
B 8 C
D 11 B
E 13 D
Visited list
Node Cost (from start) Previous
A 0 none
⃝ C 5 A
B 8 C
D 11 C
E 13 D
▶ Using the visited list that is produced by following the algorithm, which
option correctly shows the route of the shortest path from A to E?
⃝ A-C-D-E
⃝ A-C-B-D-E
⃝ A-C-E
⃝ A-B-D-E
242 28. PATHFINDING ALGORITHMS
The big sales start tomorrow morning at the shops, and Queenie wants to
get there as quickly as possible to bag a bargain.
The route data is stored in an adjacency matrix. The nodes are road
junctions and the weights represent the time in minutes between junctions.
Queenie’s home is node Q and the town centre is T.
A L Q R S T V
A 4 3 8 2
L 4 3 5
Q 3 6
R 8 3 6 4
S 2 2
T 5 4 2
V 2 2
Visited list
Unvisited list
Key Value Previous
Q
A
L
R
S
T
V
▶ Using Dijkstra’s algorithm, find the length of the quickest route (“shortest
path”) from her home (Q) to the town centre (T).
• Road junctions are also stored as nodes and the weights represent the
cost of fuel to drive from node to node.
The company has 50 depots and hundreds of vans; the graph data below
shows a small subset of the graph data in the form of an adjacency list.
⃝ N
⃝ P
⃝ C
⃝ H
29 Complexity
Algorithmic complexity is a way of comparing the efficiency of an al-
gorithm. Complexity can be measured in terms of the time that it takes for
a program to run (time complexity) or in terms of the memory that it will
use (space complexity).
Complexity will usually vary in relation to the size of the input, and can
be expressed using Big O notation. When we have the choice of several
different approaches to solving a problem, Big O notation allows us to readily
compare one algorithm to another so that we can choose the best option.
Some problems are too complex to be solved (at least by today’s computer
systems) and these problems are labelled intractable. Heuristic tech-
niques can be used to find ‘good enough’ solutions to intractable problems.
⃝ When a program that solves the problem has polynomial time com-
plexity or less
⃝ When it is not possible to tell how long the program that solves the
problem will run for
⃝ When the time complexity of the program that solves the problem
grows so fast that it becomes impractical for large inputs
⃝ When it is not possible to write a program that can solve the problem
245
246 29. COMPLEXITY
⃝ O(n)
⃝ O(log n)
⃝ O(n2 )
⃝ O(n log n)
⃝ O(n)
⃝ O(n log n)
⃝ O(log n)
⃝ O(n2 )
⃝ O(log n)
⃝ O(n)
⃝ O(n2 )
⃝ O(n log n)
29. COMPLEXITY 247
▶ What is the correct Big O notation for an algorithm where the number of
operations (steps) can be expressed as:
4n3 + 3n log2 n + 273
n is the size of the input.
248 29. COMPLEXITY
▶ Number the following Big O complexities into the order of increasing time
complexity:
□ O(n²)
□ O(log n)
□ O(n)
□ O�(2)
□ O(n!)
□ O(n log n)
□ O(1)
Impacts of digital technology
30 Legislation
Until the Computer Misuse Act 1990, there were no legal provisions in
UK law governing the use and misuse of computer systems. However, the use
of computers has become so widespread that further laws such as the Regu-
lation of Investigatory Powers Act 2000 have been enacted to take into
account technological growth and the widespread use of encryption. There
have also been recent changes to data protection law. The General Data
Protection Regulation (GDPR) in EU law creates a European standard
to protect individuals, and regulates how companies and organisations may
collect, hold, and use personal data. The Data Protection Act 2018 is the
UK’s implementation of the General Data Protection Regulation (GDPR).
249
250 30. LEGISLATION
You’re signing up to a European website for a cool new game. The form
asks for personal details, such as full name, email address, home address,
and telephone number. You want to make sure that your information will be
stored securely, which UK legislation should you check the website complies
with before entering your details?
▶ Select all that apply:
⃝ Writing malware is not illegal, but using that malware to commit fur-
ther offences, such as fraud or extortion, is illegal.
The police can use their powers under various Acts of Parliament in order
to investigate and prosecute computer-related crimes.
For each item, select the appropriate answer.
▶ An individual gains unauthorised access to a computer. They do not do
anything with the data they find.
▶ The police demand that a suspect hands over keys to encrypted informa-
tion.
⃝ This is illegal.
⃝ This is illegal.
252 30. LEGISLATION
Communicating via the internet has rapidly emerged as the new normal in
many people’s daily lives, but a number of ethical concerns also have emerged
when engaging participants online, such as data breaches, for example.
Below, you have an example of a data breach:
”Maria works for a local UK government office as a financial assistant and
has access to users’ personal data, such as credit card details, date of birth,
and address. She uses a USB flash drive to make a copy of her work daily
to act as a backup file just in case the power goes down and she can’t use
her computer to retrieve the information. However, one afternoon, she left
the office, and by mistake she took the USB flash drive home together with
her belongings. The next morning, she looked for the USB flash drive and
she couldn’t find it. She informed her manager what had happened and the
incident was escalated to the legal department team, who reported the data
breach to the Data Protection Officer.”
▶ Consider the above scenario and select the UK legislation that directly
apply to this type of data breach:
31 Programming concepts
Almost all programs consist of the same basic ‘building blocks’, built together
in different ways to achieve a particular goal. Variables, data types, se-
quence, selection, and iteration are examples of these basic concepts,
which all new programmers need to learn. In order to compare and manipu-
late data, and to make decisions in a program, programmers use a variety of
different logical, relational, and arithmetic operators. It is also useful
to be able to generate randomness in a program, for example selecting a
random number or a random item from a list.
31.1.1 Constants
https://isaaccs.org/eq/gcse_prog_08
A banking system uses a constant to store the current rate of VAT so that
it can be used in calculations.
1 VAT_RATE = 0.20
⃝ The value of a constant can only change while the program is running.
⃝ You cannot change the value of a constant in the program source code.
⃝ A constant stores a value that does not change during the execution
of the program.
254
31. PROGRAMMING CONCEPTS 255
A B
X Y Output X Y Output
2 4 False 2 4 False
5 4 False 5 4 True
6 6 True 6 6 True
C D
X Y Output X Y Output
2 4 False 2 4 True
5 4 False 5 4 True
6 6 False 6 6 True
Answer:
256 31. PROGRAMMING CONCEPTS
□ Apple
□ Peach
□ Orange
□ Banana
□ Mango
1 number = 5
2 triple = True
3
4 IF triple == True AND number >= 10 THEN
5 number = number * 3
6 ELSE
7 number = number + 5
8 ENDIF
▶ What is the value of the variable number once the code has finished ex-
ecuting?
31. PROGRAMMING CONCEPTS 257
▶ Select the while loop condition that will produce the output that is shown.
Read the description of each identifier in the table below and decide whether
the identifier denotes a variable or a constant.
Read the description of each variable in the table below and decide on the
best data type to implement each variable.
Andy’s mum is trying to create a program that displays advice about the
weather. She has designed the program using structured English but the
statements have been jumbled!
▶ Number the statements into the correct order.
□ ELSE
□ PRINT("It is cold outside, dress up warm!")
□ IF temperature < 15 THEN
□ PRINT("It isn't cold outside but you may want to carry a jacket!)"
□ ELSEIF temperature < 25 THEN
□ PRINT("It is hot outside. Make sure you take some water!)"
□ ENDIF
260 31. PROGRAMMING CONCEPTS
Ms Smith has prepared a program that outputs her students’ grades based
on their scores in the end of year exam and in their projects. Which value
will be displayed on the screen for a student who got an exam score of 75 and
a project score of 90?
1 IF exam > 40 AND exam < 60 THEN
2 IF project < 50 THEN
3 grade = "Fail"
4 ELSE
5 grade = "Pass"
6 ENDIF
7 ELSEIF exam >= 60 AND exam < 90 THEN
8 IF project > 60 THEN
9 grade = "Merit "
10 ELSE
11 grade = "Pass"
12 ENDIF
13 ELSEIF exam >= 90 AND exam <= 100 THEN
14 IF project > 80 THEN
15 grade = " Distinction "
16 ELSE
17 grade = "Merit "
18 ENDIF
19 ELSE
20 grade = "Fail"
21 ENDIF
22 PRINT( grade)
The pseudocode for the program is presented below, but the condition for
the selection block is missing.
1 IF [ MISSING CONDITION ] THEN
2 PRINT (" Eligible ")
3 ELSE
4 PRINT (" Not Eligible ")
5 ENDIF
Can you work out the value of the variable total once the code has finished
executing?
Remember that in pseudocode, the loop FOR i ← 1 TO 5 will run five times:
1, 2, 3, 4, 5 inclusive.
1 total = 0
2 FOR i = 0 TO 3
3 FOR j = 0 TO i
4 total = total + i
5 NEXT j
6 NEXT i
total i j total i j
▶ What is the value of the variable total once the code has finished execut-
ing?
31. PROGRAMMING CONCEPTS 263
Sian is writing a program for a game with a grid. Here is the grid she is
using:
Sian wants to write some code to
x \y 1 2 3
generate the grid positions of every
1
shaded square on her grid so that she
2 @
can check them. For example, the co-
3
ordinates of the square containing the
4 #
@ sign would be x=2 y=2.
▶ Which of these pieces of code generates all of the shaded grid positions?
OPTION A
1 x = 1
2 y = 1
3 WHILE x <= 4 AND y <= 3
4 PRINT ("x=" + STR(x) + " y=" + STR(y))
5 x = x + 1
6 y = y + 1
7 ENDWHILE
OPTION B
1 FOR x = 1 TO 4
2 FOR y = 1 TO 3
3 PRINT ("x=" + STR(x) + " y=" + STR(y))
4 NEXT y
5 NEXT x
OPTION C
1 FOR x = 1 TO 7
2 PRINT ("x=" + STR(x) + " y=" + STR(x - 1))
3 NEXT x
OPTION D
1 FOR x = 1 TO 3
2 FOR y = 1 TO 4
3 PRINT ("x=" + STR(x) + " y=" + STR(y))
4 NEXT y
5 NEXT x
264 31. PROGRAMMING CONCEPTS
1 PROCEDURE main ()
2 input_value = INPUT (" Enter a number : ")
3 num = INT( input_value )
4 count = 0
5 WHILE num < 500
6 num = num * 2
7 count = count + 1
8 ENDWHILE
9 PRINT (count - 1)
10 ENDPROCEDURE
Trace table
num count num < 500 OUTPUT
16 0 TRUE
32 1 TRUE
⃝ 64 2 TRUE
128 3 TRUE
256 4 TRUE
512 5 FALSE
511
Trace table
num count num < 500 OUTPUT
16 0 TRUE
32 1 TRUE
⃝
64 2 TRUE
128 3 TRUE
256 4 TRUE
FALSE 3
31. PROGRAMMING CONCEPTS 265
Trace table
num count num < 500 OUTPUT
16 1 TRUE
32 2 TRUE
⃝ 64 3 TRUE
128 4 TRUE
256 5 TRUE
512 6 FALSE
5
Trace table
num count num < 500 OUTPUT
16 0 TRUE
32 1 TRUE
⃝ 64 2 TRUE
128 3 TRUE
256 4 TRUE
512 5 FALSE
4
Martin wrote a program a few weeks ago, but he has forgotten to comment
his code, so he can’t remember how it works.
1 end = 10
2 FOR i = 1 TO end
3 IF (i MOD 2) == 0 THEN
4 PRINT (" red ")
5 ELSE
6 PRINT (" blue ")
7 ENDIF
8 NEXT i
⃝ 8
⃝ blue
⃝ 0
⃝ red
266 31. PROGRAMMING CONCEPTS
Mark likes to play chess in the evenings. He prepared a program that com-
pares his calendar with his friend Jacob’s and notifies him if there is a day
that they are both available to play chess.
Here is an example of the calendars that Mark is using.
C – available for chess
X – busy
Mark uses the following arrays in his algorithm to represent the values of
the two calendars.
1 ARRAY marks_calendar [5][6]
2 ARRAY jacobs_calendar [5][6]
To find out which days he can play chess with Jacob, he experiments with
the loops below.
▶ Which of the loops will output the days that Mark can play chess with
Jacob?
OPTION A
1 FOR i = 0 TO 4
2 FOR j = 0 TO 5
3 IF marks_calendar [i][j] == jacobs_calendar [i][j] THEN
4 PRINT ( marks_calendar [j][0] + " Day: " +
marks_calendar [0][i])
5 ENDIF
6 NEXT j
7 NEXT i
31. PROGRAMMING CONCEPTS 267
OPTION B
1 FOR i = 1 TO 4
2 FOR j = 1 TO 5
3 IF marks_calendar [i][j] == 'C' AND
jacobs_calendar [i][j] == 'C' THEN
4 PRINT ( marks_calendar [j][0] + " Day: " +
marks_calendar [0][i])
5 ENDIF
6 NEXT j
7 NEXT i
OPTION C
1 FOR i = 1 TO 4
2 FOR j = 1 TO 5
3 IF marks_calendar [i][j] == jacobs_calendar [i][j] THEN
4 PRINT ( marks_calendar [i][0] + " Day: "+
marks_calendar [0][j])
5 ENDIF
6 NEXT j
7 NEXT i
OPTION D
1 FOR i = 1 TO 4
2 FOR j = 1 TO 5
3 IF marks_calendar [i][j] == 'C' AND
jacobs_calendar [i][j] == 'C' THEN
4 PRINT ( marks_calendar [i][0] + " Day: " +
marks_calendar [0][j])
5 ENDIF
6 NEXT j
7 NEXT i
Answer:
268 31. PROGRAMMING CONCEPTS
Kjella has written a program that allows a user to enter all of the costs that
they have accumulated whilst working on a project and then outputs the
total. The program is shown in pseudocode below.
1 total = 0
2 DO
3 cost = INT( INPUT (" Please enter a cost or -1 to stop "))
4 total = total + cost
5 WHILE cost != -1
6 PRINT ( total )
▶ If the user enters 25, 18 and then −1, how many times will the statements
inside the loop be repeated?
Jag and his friends are going out for a meal before they break up for the
school holidays. They have agreed that they will leave a tip of 12.5%, and
split the bill between them. They have agreed to split the bill in such a way
that people who only have a main course will pay less than people who have
both a main course and a dessert. Jag has written a program to work out
how much each person should contribute.
The format() subroutine will format a number to a given number of decimal
places, truncating any extra digits. Here are some examples:
format (12.23333 , 2) returns 12.23
format (17.854 ,1) returns 17.8
format (8.5 ,3) returns 8.500
On the night, there were nine people who went out for the meal. Three of
them had a dessert. The bill (before tip) was £160.
▶ By tracing the code to find out the algorithm that Jag used, how much
will Nic, who did have a dessert, have to pay for his meal (including his
share of the tip)?
Roma is writing a program to manage her party playlist. The code isn’t
doing quite what she expected it to do. This is what she has written:
1 ARRAY playList = [" The Beatles ", "Ed Sheeran ", " Stormzy ",
" Mariah Carey", "Dua Lipa", "Shakin ' Stevens "]
2 ARRAY played = [1, 2, 3, 2, 2, 3]
3 m = played [0]
4 FOR i = 0 TO LEN( playlist ) - 2
5 IF played [i+1] < played [i] THEN
6 m = i
7 ENDIF
8 NEXT i
9 played [m] = played [m] + 1
10 play( playlist [m])
The subroutine play() takes the name of an artist as a parameter and will
locate and play a song by that artist. This is a prewritten subroutine and
works correctly.
▶ When she runs the program to test her code, which artist will be played?
270 31. PROGRAMMING CONCEPTS
Malika then runs her code with an input of 8. The output looks like this:
▶ The FOR loop has a missing value in the loop definition. What is the
missing value?
⃝ 4
⃝ n
⃝ 3
⃝ 2
⃝ term_1
⃝ n
⃝ i
⃝ next_term
272 31. PROGRAMMING CONCEPTS
▶ What is the value of the variable answer once the code has finished ex-
ecuting?
31. PROGRAMMING CONCEPTS 273
▶ What will the output be if the variable number has a value of 78?
32 String handling
A string is a sequence of letters, numbers, spaces, or other symbols. Data in
the form of a string is used in almost all programs, whether it is to display
information for the user, or to read information stored in a database. It
is useful to be able to manipulate string data, for example to determine
whether a password is sufficiently long, or to remove or replace characters.
274
32. STRING HANDLING 275
Nitin owns a car showroom, and he has records of all of the cars he has in
stock. The records include the cars’ number plates. The number plates are
all in the following format, where L is a letter and N is a number:
1 LLNNLLL
Nitin has written a program to try to extract only the two numbers (NN)
from the number plate of every car, which represent the year in which it
was registered. The documentation for the programming language said, “to
obtain a substring, you must specify the starting position (numbering starts
at 0), the ending position, and the string itself”. He isn’t sure whether the
program he has written is correct. Here is his code:
1 numberplate = " ZX19CSV "
2 year = numberplate [2:5]
3 PRINT(year)
Nyasha has written a program to slice part of a string, but he has gotten
stuck.
1 word = " typewriter "
2 slice = <<< missing code >>>
3 PRINT( slice )
▶ Which of the following pieces of code should Nyasha set as the value of
the variable slice so that he gets the output ‘write’?
⃝ word[5:5]
⃝ word[4:5]
⃝ word[5:9]
⃝ word[4:8]
276 32. STRING HANDLING
Ross has an ultra valuable collection of rare board games, which he stores
in a locked cupboard in his house. The cupboard has a combination lock on
the door that can only be opened by using a four-digit passcode.
Ross uses the string “boardgames” to remember his passcode:
• The index of each vowel in the string “boardgames” is one of the digits
in the passcode
• In English, the vowels are “a”, “e”, “i”, “o” and “u”
□ PRINT("Please enter
the word to spell")
□ word = INPUT()
□ FOR i = 0 TO
LEN(word)-1
□ PRINT(word[i])
□ NEXT i
□ PRINT(word)
□ FOR i = 0 TO LEN(word)
□ PRINT(word[0:1])
□ PRINT(word[0:i])
278 32. STRING HANDLING
Maja is writing a program for splitting the cost of a pizza between three
people.
▶ Arrange the following statements in the correct order so that the program
correctly outputs a string explaining how much each person must pay. Not
all statements are required.
□ cost = INPUT()
□ float_cost = FLOAT(cost)
□ per_person_string = STR(per_person_cost)
□ float_cost = INT(cost)
□ per_person_cost = FLOAT(per_person_cost)
32. STRING HANDLING 279
Jenni works for a publishing company where she edits short stories. One
short story author has a broken shift key, and therefore hasn’t used any
capital letters!
Jenni wants to save time by writing a function that takes a sentence as
input, and outputs the sentence with the first letter capitalised. Here is the
program she has written so far:
1 PROCEDURE caps_first ( sentence )
2 letter = sentence [0:0]
3 uppercase = CHR( ASC( letter ) - 32 )
4 ENDPROCEDURE
▶ Put the statements shown below in the correct order to finish off Jenni’s
function to return the same sentence but with the first letter as a capital.
For example, if the sentence entered is:
"it was a dark and stormy night."
Then the return value of the function needs to be:
"It was a dark and stormy night."
□ RETURN new_sentence
□ new_sentence[
□ 0:
□ 1:
□ +
□ uppercase
□ new_sentence =
□ letter
□ sentence[
□ LEN(sentence)]
□ LEN(sentence)-1]
□ RETURN sentence
280 32. STRING HANDLING
Alex is a teacher. She has been given a file with a list of students’ names in
the following format:
John SMITH
So she can use the names in her register, she writes a function that takes a
name from the list and returns it in the following format:
SMITH, John
This is Alex’s function:
1 FUNCTION format_name (name)
2 split = name.INDEX (" ")
3 first = name [0: split -1]
4 last = name[ split +1: LEN(name) -1]
5
6 RETURN last + ", " + first
7 ENDFUNCTION
Alex’s function works and produces the output she wants for most of her
students. However, there is one student whose name causes the program to
break.
▶ What string does Alex’s function return for the student called Neil
Patrick HARRIS?
32. STRING HANDLING 281
When Nadia runs this program, it doesn’t produce exactly the output she
was expecting.
▶ What is the output of Nadia’s program?
282 32. STRING HANDLING
Travis is working with some data stored in CSV format. Each line of data
contains multiple data values separated from each other by commas. Travis
has written a recursive subroutine to help him output a line of data in a
more readable way.
1 PROCEDURE csv_output ( whole_string , delimiter )
2 location = whole_string .INDEX( delimiter )
3
4 word = whole_string [0: location -1]
5 rest = whole_string [ location +1: LEN( whole_string ) -1]
6
7 IF location >= 0 THEN
8 PRINT (word)
9 csv_output (rest , delimiter )
10 ELSE
11 PRINT (rest)
12 ENDIF
13 ENDPROCEDURE
Remember that the SUBSTRING function takes three arguments: the first char-
acter to include, the last character to include, and the string to take the
substring from.
Assume that each OUTPUT statement displays on a new line.
▶ If Travis calls this procedure with the following arguments, what will the
output be?
csv_output("do,you,know,the,muffin,man", ",")
33 Subroutines
A subroutine is a named section of code that can be called by writing
the subroutine’s name in a program statement. Subroutines can also be
referred to as procedures or functions. A procedure just executes a set
of instructions, whilst a function will return a value when it has finished
executing. Writing subroutines makes the code more readable and reusable,
as the code is broken into smaller sections. Most programming languages
come with a standard library of built-in subroutines to perform common
functions, but also have the capability to allow the programmer to write
their own custom subroutines.
The cube of a given number is that number multiplied by itself three times.
For example, the cube of 3 is 27.
Lucy has created a program (shown in pseudocode below) that uses a sub-
routine named cubed to carry out the calculation. When she runs the pro-
gram, Lucy is not getting the output that she was expecting.
1 FUNCTION cube(num)
2 cubed_value = num * num * num
3 RETURN cubed_value
4 ENDFUNCTION
5
6 PROCEDURE main ()
7 input_value = INPUT (" Enter a value to be cubed: ")
8 user_num = INT( input_value )
9 cube( user_num )
10 ENDPROCEDURE
▶ Lucy realises that problem is with the final line of code. How should she
amend it so that the cubed value is outputted correctly?
⃝ PRINT(cubed_value)
⃝ PRINT(cube(user_num))
⃝ PRINT(num)
⃝ PRINT(user_num)
283
284 33. SUBROUTINES
Maja has written a program that is supposed to display how much one person
should pay if a restaurant bill is split equally between the people present.
The program isn’t working correctly: when Maja runs it, the amount does
not appear on the screen.
1 FUNCTION split_the_bill (amount , number_of_people )
2 result = FLOAT ( amount ) / INT( number_of_people )
3 RETURN result
4 ENDFUNCTION
5
6 PROCEDURE main ()
7 bill_total = INPUT (" Enter the total bill amount ")
8 people = INPUT (" How many people were eating ?")
9 PRINT (" The amount you should pay is ...")
10 split_the_bill ( bill_total , people )
11 ENDPROCEDURE
▶ Why doesn’t the program print the amount?
George tests his program by typing in the numbers 5 and 2, and this is what
he sees:
Enter the first number : 5
Enter the second number : 2
10
The result is null
1 PROCEDURE spanish ()
2 PRINT (" Hola ")
3 ENDPROCEDURE
4
5 PROCEDURE greek ()
6 PRINT (" Geia sas ")
7 ENDPROCEDURE
8
9 PROCEDURE italian ()
10 PRINT (" Ciao ")
11 ENDPROCEDURE
12
13 PROCEDURE welcome ()
14 greek ()
15 PRINT (" Hello ")
16 spanish ()
17 ENDPROCEDURE
18
19 welcome ()
▶ Trace the program and write down what its output will be when the
procedure welcome() is called.
33. SUBROUTINES 287
▶ Variables can be local or global. Select all of the statements that cor-
rectly state an advantage of using local variables.
□ When the value of the local variable is modified in one subroutine, the
changes are visible in another subroutine.
□ When you use local variables, you do not have to worry that they will
be changed by code in other subroutines
Three local fitness centres have decided to merge into one organisation called
Three Fit. Each fitness centre has a different customer relationship manage-
ment (CRM) software and Three Fit wants to develop one CRM software
with all the customer data from the three original systems.
Jamil has created a program to extract the data from the three different
systems into the joined new CRM software using subroutines.
▶ Select all the options that describe the benefits of using subroutines in
a program.
□ Using subroutines can help Jamil break down the problem into more
manageable parts that he can program.
□ To join the data from the three original systems into one, Jamil should
use only one subroutine in the program.
□ The subroutines don’t need to be reprogrammed every time Jamil
needs to use them in the program.
□ Subroutines can be reused in different parts of Jamil’s program or even
future programs.
□ If a change needs to be made in Jamil’s program, it can be applied to
the code of the corresponding subroutine once.
□ By using subroutines Jamil can ensure the accuracy of the data from
the three original systems.
⃝ It stores the base case and the general case for each recursive subroutine
⃝ It stores a set of values for local variables and parameters for each
subroutine
⃝ It stores the return address, value of parameters, and value of local
variables for each active subroutine
⃝ It stores a list of all active subroutines so that they will be run in the
correct order
33. SUBROUTINES 289
▶ Trace the code and add the subroutine identifier missing on line 6 and
the parameters missing on line 9. The program should register the user and
then display the user details.
1 PROCEDURE register_user ()
2 user_name = INPUT (" Please enter your name: ")
3 user_age = INPUT (" Please enter your age: ")
4 user_email = INPUT (" Please enter your email address : ")
5
6 __________ (user_email , user_name , user_age )
7 ENDPROCEDURE
8
9 PROCEDURE display_user_details ( __________ )
10 PRINT (" Name: " + name)
11 PRINT (" Age: " + age)
12 PRINT (" Email: " + email)
13 ENDPROCEDURE
14
15 register_user ()
1 PROCEDURE increase_num ()
2 num2 = 2
3 num1 = num2 + 5
4 num2 = 13
5 ENDPROCEDURE
6
7 num1 = 4
8 num2 = 10
9 increase_num ()
10 num3 = 4
11 PRINT (num1 + num2 + num3)
▶ Trace the pseudocode and enter the output that will be produced when
the program is run.
290 33. SUBROUTINES
33.4.1 Stack it up
https://isaaccs.org/eq/prog_sub_14
1 PROCEDURE main ()
2 find_y (5, 2, 3)
3 ENDPROCEDURE
4
5 FUNCTION multiply (a, b)
6 RETURN a * b
7 ENDFUNCTION
8 PROCEDURE main ()
9
10 FUNCTION add(a, b)
11 RETURN a + b
12 ENDFUNCTION
13
14 PROCEDURE find_y (x, m, c)
15 PRINT ("x=" + STR(x) + " y=")
16 PRINT (add( multiply (m, x), c))
17 ENDPROCEDURE
▶ What is the maximum number of stack frames which will be on the call
stack at any one time during this program’s execution?
292 33. SUBROUTINES
⃝ 1
⃝ 6
⃝ 5
⃝ 0
34 File handling
More complicated programs usually need to store data from one run of the
program to the next. A simple way of doing this is storing the data in a
text file. You can read and write to files using built-in functions in your pro-
gramming language. At a more advanced level, you will learn that programs
can also store data in binary files, but the data is in a format that humans
are unable to read.
Consider the following letter contained in a text file. When the file is opened
in a text editor such as Notepad or TextEdit, the following text is displayed
to the user.
Dear Mr Spencer ,
Kind regards ,’
Johnnys Mum
▶ How many newline characters are in the raw data of the text file?
293
294 34. FILE HANDLING
While decluttering your hard drive, you come across a folder that you haven’t
opened in a long time. You open it up to examine the contents.
The list of files is shown below.
Cat.png
Picture .txt
List.docx
Data.txt
Flyer .pdf
Text.jpeg
Locations .csv
To -Do.txt
An algorithm has been designed to scan files for malicious code. There are
two different versions of the program: one to scan text files, and one to scan
binary files.
You have been asked to test the version of the program for binary files.
First, you need to test its ability to recognise binary files, so you set the
program to run over the following list of files.
List.xls
Cat.png
Image .txt
Giraffe .jpeg
game.exe
Shopping .txt
Friends .mp4
▶ How many binary files should the algorithm find in the list?
34. FILE HANDLING 295
The following pseudocode has been written to print some lines of text from
the file.
1 friend_file = OPEN_READ (" friends .txt ")
2 all_data = friend_file . READALL ()
3 friend_file . CLOSE ()
4 PRINT( all_data [1] + " " + all_data [4])
▶ What will be the output of this code?
⃝ Ben Neil
⃝ Clare Carmen
⃝ An error, because line 4 does not exist.
⃝ An error, because the file has been opened in write mode.
While writing some code for a new app, Laura wants to test that she can
open a file and close it again. She has all of the data for the app stored in a
file called data.txt. She writes the following statements into her code editor
and runs the program.
1 file_data = OPEN_WRITE (" data.txt ")
2 file_data . CLOSE ()
After running her code, Laura opens her data.txt file in a text editor.
▶ What does she see?
You are showing five of your classmates how to write multiple lines at
once to a text file using an array. Your intention is for each piece of data
from the array to appear on a separate line in the file, like this:
Bike
Car
Bus
Plane
The program that you are going to use to write the array data to the file is
as follows:
1 new_data = ### missing array ###
2
3 info_file = OPEN_WRITE (" info.txt ")
4 info_file . WRITE_ALL ( new_data )
5 info_file .CLOSE ()
You tell them to put their data into an array called new_data. After they
have done this, you ask to see the arrays that they have created.
1 new_data = [" Bike\ newline ", "Car\ newline ", "Bus\ newline ",
"Plane \ newline "]
2 new_data = [" Bike", "Car", "Bus", "Plane "]
3 new_data = ["\ nBike ", "\ nCar", "\ nBus", "\ nPlane "]
4 new_data = [" Bike\n", "Car\n", "Bus\n", "Plane\n"]
5 new_data = [Bike "\n", Car "\n", Bus "\n", Plane "\n"]
▶ Which of the arrays will achieve the intended result when you run the
program?
⃝ 1, 3, and 4
⃝ 3 and 4
⃝ 3, 4, and 5
⃝ 2
⃝ 4
34. FILE HANDLING 297
Lion
You have a text file called zooanimals.txt Penguin
which looks like this when it is opened in a Giraffe
Yak
text editor. (You can assume that Lion is the
Badger
first line of the text file).
Porcupine
Chameleon
A program has been written to manipulate Jaguar
and output the contents of the text file. Warthog
Grizzly bear
Flour
Eggs
Milk
Sugar
A student has written a program to process the file. The program is shown
in pseudocode below.
1 shopping_file = OPEN_READ (" shopping .txt ")
2 items = shopping_file . READ_ALL ()
3 shopping_file .CLOSE ()
4
5 shopping_file = OPEN_WRITE (" shopping .txt ")
6 FOR i = LEN( items) TO 1
7 shopping_file . WRITE_LINE (items[i -1])
8 NEXT i
9 shopping_file .CLOSE ()
The file method readLines will read all of the lines from the file into an array.
Each line of the original file will be an element in the array.
▶ Which of the following options correctly shows the contents of the file
’shopping.txt’ when the program has finished running?
Sugar
Milk
⃝
Eggs
Flour
Flour
Eggs
⃝
Milk
Sugar
Sugar
⃝ Milk
Eggs
35 Recursion
Recursion is the ability of a subroutine to call itself. Many novice pro-
grammers make recursive calls inadvertently! A recursive call makes use of
a stack and stack frames to store the data from each depth of function
call. There are some problems for which a recursive algorithm is the natural
choice, for example, a recursive tree traversal or the standard algorithm for
a merge sort. If you are feeling overwhelmed by recursion, you will be happy
to learn that, for every recursive solution, there is an iterative solution
(ie the same problem can be solved using loops). However, you will find
that with study and practice, you may eventually enjoy the elegance of a
recursive subroutine.
299
300 35. RECURSION
When the subroutine is run with the value 18 specified as the argument, i.e.
do_something(18), the subroutine returns the value 4.
▶ What value is returned when the subroutine is run with the value 100
specified as an argument, i.e. do_something(100)?
n return
Answer:
35. RECURSION 301
Scores is an array that contains the test scores of each student from a
recent class test. Each element of the array contains a record containing the
student’s surname, first name, and score. These values are accessed using
the syntax:
student . surname
student . forename
student . score
The array is ordered by surname and contains records for these students:
Ahmed, Atkinson, Bashir, Bell, Chesworth, Cooper, Endover, Faujdar, James,
Khan, Mohammad, Murray, Singh, Williams, Young
The teacher wants to know what score was achieved in the test by the stu-
dent with the surname James. The search is carried out using the recursive
subroutine defined below.
When the subroutine is called for the first time, the arguments specified are
0 for first and 14 for last, i.e.
search("James", scores, 0, 14)
▶ How many times in total will the subroutine be called (including the
first call) so that the score for the student with the surname James can be
retrieved?
35. RECURSION 303
Answer:
▶ Trace the subroutine to determine what the final return value will be when
the following call is made:
do_something (5, 2)
x y return
Answer:
35. RECURSION 305
⃝ If a shared reference is used, every recursive call will use the same value
for n
⃝ A value is used so that the calculation does not throw a runtime error
306 35. RECURSION
307
Programming paradigms
37 Object-oriented programming
Object-oriented programming (OOP) is an approach to systems devel-
opment that is focused on objects and the way that they interact. Objects
surround us in the real world. Look around you. For example, I am a person,
and I have a desk, a computer, and a cup of water; these are all objects. How
do they interact? I sit at my desk, switch on the computer, and drink some
water. The OOP method of programming (or paradigm) is different to
the procedural paradigm, which many programmers start out with on their
learning journey. Code is written to define objects and classes, and certain
principles such as encapsulation, inheritance, and polymorphism are
important to the design of an object-oriented program. Programmers use a
diagrammatical language called UML to model objects in a program and
their interactions.
37.1.1 Encapsulation
https://isaaccs.org/eq/prog_oop_02
⃝ It ensures that child classes can use the attributes and methods of the
parent class.
⃝ It ensures that any interaction with an object is only allowed via its
public interface.
308
37. OBJECT-ORIENTED PROGRAMMING 309
□ A child class can alter the behaviour of a method that it has inherited
from the parent class.
□ A parent class inherits all of the attributes and methods of the child
classes that it has.
1 CLASS Rectangle
2 PRIVATE width
3 PRIVATE height
4
5 PUBLIC PROCEDURE Rectangle ( given_width , given_height )
6 width = given_width
7 height = given_height
8 ENDPROCEDURE
9
10 PUBLIC PROCEDURE draw ()
11 FOR column = 0 TO height
12 FOR row = 0 TO width
13 PRINT ("* ")
14 NEXT row
15 NEXT column
16 ENDPROCEDURE
37. OBJECT-ORIENTED PROGRAMMING 311
17 ENDCLASS
18
19 PRINT (" Draw a rectangle of …stars ")
20 height = INPUT (" Enter the height : ")
21 width = INPUT (" Enter the width: ")
22
23 my_shape = NEW Rectangle (_______ , _______ )
24 my_shape .draw ()
37.1.5 Interstellar
https://isaaccs.org/eq/prog_oop_09
▶ Select the statement that completes the missing code in the if statement
of the show_habitable_planets method.
⃝ planets.habitable == True
⃝ planets[count].get_habitable()== True
⃝ Planet.habitable == True
⃝ Galaxy[count].get_habitable()== True
37. OBJECT-ORIENTED PROGRAMMING 313
Jemma is developing a game for her younger brother that takes place in
space. So far, she has created part of the definition of the Planet class.
1 CLASS Planet
2 PRIVATE distance_sun # Float given in million km
3 PRIVATE satellites # Integer
4 PRIVATE habitable # Boolean
5 PRIVATE main_colour # String
6
7 PUBLIC PROCEDURE Planet ( given_distance_sun ,
given_satellites , given_habitable , given_main_colour )
8 distance_sun = given_distance_sun
9 satellites = given_satellites
10 habitable = given_habitable
11 main_colour = given_main_colour
12 ENDPROCEDURE
13
14 PROCEDURE set_distance_sun ( number )
15 distance_sun = number
16 ENDPROCEDURE
17 ENDCLASS
▶ Select the statement that can create an object of the Planet class called
mars so that it is habitable, has two satellites, is 227.9 million kilometres
away from the sun, and has a dominant colour of red.
Olivia maintains the computer systems for a car manufacturer who is branch-
ing out into the production of electric vehicles. She is going to use poly-
morphism to change the car control systems to support electric cars.
▶ Which of the following examples uses polymorphism to model an electric
car?
1 # Option 1 --------------------
2 CLASS Car
3 PRIVATE engine_type
4
5 PUBLIC PROCEDURE Car ()
6 engine_type = " combustion "
7 ENDPROCEDURE
8
9 PUBLIC PROCEDURE set_engine_type ( given_engine_type )
10 engine_type = given_engine_type
11 ENDPROCEDURE
12 ENDCLASS
13
14 electric_car = NEW Car ()
15 electric_car . engine_type = " electric "
1 # Option 2 --------------------
2 CLASS Car
3 PUBLIC FUNCTION get_engine_type ()
4 RETURN " combustion "
5 ENDFUNCTION
6 ENDCLASS
7
8 CLASS ElectricCar EXTENDS Car
9 PUBLIC FUNCTION get_engine_type ()
10 RETURN " electric "
11 ENDFUNCTION
12 ENDCLASS
37. OBJECT-ORIENTED PROGRAMMING 315
1 # Option 3 --------------------
2 CLASS Car
3 PRIVATE engine_type
4 ENDCLASS
5
6 CLASS ElectricCar EXTENDS Car
7 PRIVATE charge
8
9 PUBLIC FUNCTION get_charge ()
10 RETURN charge
11 ENDFUNCTION
12 ENDCLASS
1 # Option 4 --------------------
2 CLASS Car
3 PRIVATE engine_type
4
5 PUBLIC PROCEDURE Car ()
6 engine_type = " combustion "
7 ENDPROCEDURE
8 ENDCLASS
9
10 CLASS ElectricCar
11 PRIVATE engine_type
12
13 PUBLIC PROCEDURE ElectricCar ()
14 engine_type = " electric "
15 ENDPROCEDURE
16 ENDCLASS
Answer:
316 37. OBJECT-ORIENTED PROGRAMMING
The travel_time method of the Rider class has the following functionality:
• If the skill of the person travelling is greater than 8 and there are no
barriers on the way to the castle, then the time required for travel
is calculated as the distance to the castle divided by the speed of the
horse
• In any other scenario, it takes double the amount of time to reach the
castle
37. OBJECT-ORIENTED PROGRAMMING 317
▶ Enter the statement that completes the code under the if statement.
Mike is creating a game inspired by The Lord of the Rings. Each character of
the game can belong to one of the following tribes: Elves, Dwarves, Hobbits,
Men, Wizards, Orcs, and Trolls. The characters that belong to the tribe of
Elves have a commonly known name and a secret elven name. Their special
power is archery.
A part of the definitions of the Elf and Character classes is presented below.
super is used to call the constructor of the Elf parent class from the Character
child class.
In the main program, an instance of the Character class called my_character
is created, and then an output statement is used to demonstrate the value
of an attribute.
1 CLASS Elf
2 PRIVATE strength : Integer
3 PRIVATE speed : Integer
4 PUBLIC power: String
5
6 PUBLIC PROCEDURE Elf( given_strength , given_speed )
7 strength = given_strength
8 speed = given_speed
9 power = " Archery "
10 ENDPROCEDURE
11
12 PUBLIC FUNCTION get_strength ()
13 RETURN strength
14 ENDFUNCTION
15 ENDCLASS
16
17 CLASS Character EXTENDS Elf
18 PRIVATE elf_name : String
19 PUBLIC name: String
20
21 PUBLIC PROCEDURE Character ( given_strength , given_speed ,
given_elf_name , given_name )
22 SUPER ( given_strength , given_speed )
23 elf_name = given_elf_name
24 name = given_name
25 ENDPROCEDURE
26
27 PUBLIC FUNCTION get_elf_name ()
28 RETURN elf_name
29 ENDFUNCTION
37. OBJECT-ORIENTED PROGRAMMING 319
30 ENDCLASS
31
32 # Main program
33 PROCEDURE new_character ()
34 my_character = NEW Character (200 , 1000 , " Greenleaf ",
" Legolas ")
35 PRINT (...................)
36 ENDPROCEDURE
▶ Look at the list of output statements and select the ones that will
cause an error if they are used in the main program to display the value
of an attribute.
□ PRINT(my_character.get_strength())
□ PRINT(my_character.speed)
□ PRINT(my_character.power)
□ PRINT(my_character.elf_name)
□ PRINT(my_character.name)
□ PRINT(my_character.get_elf_name())
320 37. OBJECT-ORIENTED PROGRAMMING
⃝ The Frog class is a parent class to the Animal class and so it inherits
all of its attributes and methods.
⃝ Having a definition of the display_habitat method in the Frog class
will cause a runtime error.
⃝ It is possible to have two different definitions of the display_habitat
method in this example due to polymorphism.
⃝ The habitat attribute can be accessed and used directly in the Frog
class.
38 Event-driven programming
Event-driven programming is an approach to programming in which
code is written to respond to events. Events can be triggered by users, such
as by clicking on an icon or entering some text. In automated systems,
sensors can be used to detect events such as when a particular temperature
is reached in a glasshouse or a specific water level is detected on a flood
defence system.
The programs that respond to events are called event handlers. The event
handler will ensure that appropriate processing takes place in response to
the event that triggered it.
▶ Select all the statements which are true about a program with a GUI.
Half of the statements provided are false.
321
Software engineering
39 Program design
Program design is an essential part of systems development. Algorithms
can be expressed in a variety of ways. A flowchart is a useful visual tech-
nique to show the flow of logic through a program. Pseudocode is useful
when the design will be passed to a programmer who can convert the pseudo-
code into real program code.
⃝ A procedure that will close down the program smoothly when an ex-
ception is encountered.
⃝ A validation routine that will run successive tests to identify and rectify
the cause(s) of the problem.
⃝ A validation routine that will use an else statement to catch any pos-
sible problems that the programmer has not explicitly dealt with.
322
39. PROGRAM DESIGN 323
Answer:
324 39. PROGRAM DESIGN
• index = -1
• i = 0
• WHILE i < LEN(data_set)AND found == False
• PRINT (index)
• ENDWHILE
• index = 1
• IF data_set[i] == item_sought THEN
• i = i + 1
• found = True
• found = False
• ENDIF
39. PROGRAM DESIGN 325
326 39. PROGRAM DESIGN
▶ Dry run the algorithm when it is called with the values n1=616 and n2=24.
Record each value that is taken by f as the algorithm is run.
f n1 n2 temp
39. PROGRAM DESIGN 327
num out r
index 0 1 2 3 4 5 6
value 23 12 99 16 8 106 77
It will look like this after the algorithm has been applied:
index 0 1 2 3 4 5 6
value 77 23 12 99 16 8 106
39.3.6 Precondition
https://isaaccs.org/eq/prog_pas_03
The statements below provide a definition of white box, black box, alpha,
and beta testing.
▶ Which of the statements best describes white box testing?
330
40. TESTING 331
▶ Which of the following sets of total cost test data includes the values that
should be selected to test the subroutine? You can assume that the data has
already been validated and that only valid data is passed into the subroutine
(so there is no need to test for invalid values).
Data set A
Data set B
Data set C
Answer:
332 40. TESTING
When designing a test plan, it is important that you predict the outcome of
each test.
A subroutine has been written to convert degrees Celsius to Fahrenheit. One
of the tests is specified as follows:
⃝ 12.2
⃝ 15.5
⃝ 26.7
⃝ 45.0
40. TESTING 333
The student has written a test plan for the subroutine with some tests as
shown below:
Test # Purpose Data Expected results
1 Test that the 35 80 1 Input is accepted and returned by
subroutine 100 the subroutine
accepts valid
data
2 Test that the 105 two The user gets a message (“That is
subroutine not a valid test mark”) and is
rejects prompted again to enter a mark
invalid data for the student
▶ Identify one piece of test data, from the student’s plan, that is a boundary
(extreme) value.
334 40. TESTING
Charlie has been asked to write a subroutine to print the largest of three
positive integers given in a specified order. The subroutine should compare
the three values and output the largest value of the three.
If there are any values that are the same, it should output the value that is
provided first in the list of arguments (i.e. if the values provided for b and
c are equal, then the program should output the value of b or if the values
provided for a and c are equal, then the program should output the value of
a).
Here is the pseudocode for the subroutine:
1 PROCEDURE print_largest (a, b, c)
2 IF a > b AND a > c THEN
3 PRINT ("a =")
4 PRINT (a)
5 ELSEIF b > a AND b >= c THEN
6 PRINT ("b=")
7 PRINT (b)
8 ELSE
9 PRINT ("c=")
10 PRINT (c)
11 ENDIF
12 ENDPROCEDURE
Charlie has produced a test plan with carefully designed test data and has
manually calculated the expected results.
When he starts testing his code, he gets the expected results for Test 1 and
2 but some of the remaining tests do not work as expected due to a logic
error in the code.
▶ Trace the pseudocode using each of the sets of test data for Tests 3-6 and
identify which of the following options shows the results of Charlie’s testing.
40. TESTING 335
⃝
Test Number Test Data Expected result Actual result
1 a=1, b=10, c=100 c=100 c=100
2 a=12, b=14, c=1 b=14 b=14
3 a=22, b=10, c=11 a=22 a=22
4 a=100, b=100, c=10 a=100 c=10
5 a=10, b=10, c=10 a=10 c=10
6 a=10, b=20, c=20 b=20 b=20
⃝
Test Number Test Data Expected result Actual result
1 a=1, b=10, c=100 c=100 c=100
2 a=12, b=14, c=1 b=14 b=14
3 a=22, b=10, c=11 a=22 a=22
4 a=100, b=100, c=10 a=100 b=100
5 a=10, b=10, c=10 a=10 a=10
6 a=10, b=20, c=20 b=20 b=20
⃝
Test Number Test Data Expected result Actual result
1 a=1, b=10, c=100 c=100 c=100
2 a=12, b=14, c=1 b=14 b=14
3 a=22, b=10, c=11 a=22 a=22
4 a=100, b=100, c=10 a=100 b=100
5 a=10, b=10, c=10 a=10 c=10
6 a=10, b=20, c=20 b=20 c=20
⃝
Test Number Test Data Expected result Actual result
1 a=1, b=10, c=100 c=100 c=100
2 a=12, b=14, c=1 b=14 b=14
3 a=22, b=10, c=11 a=22 a=22
4 a=100, b=100, c=10 a=100 a=100
5 a=10, b=10, c=10 a=10 b=10
6 a=10, b=20, c=20 b=20 b=20
336 40. TESTING
Diane has written some code to calculate the factorial of a number, but it
isn’t working properly. She doesn’t get the right result when her code is run
with the call factorial(5).
1 FUNCTION factorial (n)
2 total = 1
3 FOR i = 1 TO n
4 total = total * n
5 NEXT i
6 RETURN total
7 ENDFUNCTION
▶ What is the name for the type of error Diane has made?
41.1.2 Am I SMART?
https://isaaccs.org/eq/prog_softeng_07
⃝ Be easy to use
337
338 41. SOFTWARE ENGINEERING PRINCIPLES
41.1.3 Lifecycle
https://isaaccs.org/eq/prog_softeng_05
□ Testing
□ Feasibility study
□ Design
□ Development
□ Analysis
⃝ RAD
⃝ Waterfall lifecycle
⃝ Spiral model
⃝ Extreme programming
41. SOFTWARE ENGINEERING PRINCIPLES 339
Documenting your code can be a laborious process. However, there are tech-
niques that you can use that will make the process far less time-consuming.
▶ From the list below, select one technique that will NOT help you make
your code self-documenting.
□ It allows the end user to give feedback on parts of the system before
too much time is spent on developing them fully.
42 Computational thinking
Computational thinking is a process of problem-solving. This can involve:
Decomposition — breaking a problem down into smaller parts
Abstraction — removing unnecessary detail to reduce complexity
Pattern recognition — identifying the problem as an example of a class
of problems that have already been solved
Automation — developing the algorithm(s) to solve the problem
At a more advanced level, you will learn about a wide range of abstrac-
tion techniques and computational methods that can be used to help solve
complex problems.
A company that sells cosmetic products online wants to use data mining to
find out how to best support its customers.
▶ Select the sentence that wouldn’t be a result of this process.
340
42. COMPUTATIONAL THINKING 341
⃝ Ask five gamers to play the game until the end to check that they do
not encounter any bugs
⃝ Release a beta version of the game and ask the users if the game models
space conditions accurately
42.2.3 Pipelining
https://isaaccs.org/eq/dsa_ctm_09
42.2.4 Visualisation
https://isaaccs.org/eq/dsa_ctm_10
⃝ Writing down all the possible routes from the root to the leaves of the
tree makes it easier to test the algorithm.
42.4.1 Backtracking
https://isaaccs.org/eq/dsa_ctm_06
⃝ Decomposition
⃝ Information hiding
⃝ Automation
⃝ Generalisation
42.4.3 What am I?
https://isaaccs.org/eq/dsa_ctm_04
Sami is creating a game. The game will allow the player to move a small
alien through a maze to return safely to his spaceship. The alien only has
enough oxygen to get back via the shortest route, which the player must
find. Sami has tackled the problem by removing unnecessary detail so that
the problem can be reduced to a type of problem for which a solution already
exists.
▶ What type of problem has she identified?