0% found this document useful (0 votes)
809 views354 pages

Isaac Cs Ocr Book 2022

This document is the introduction to the Isaac Computer Science Workbook published by the Raspberry Pi Foundation. It provides notes for students and teachers on how to use the workbook which contains over 300 computer science questions sorted by topic and level. The questions are meant to help students master A-level Computer Science concepts and can be accessed online or in the printed workbook.

Uploaded by

Ricky Jacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
809 views354 pages

Isaac Cs Ocr Book 2022

This document is the introduction to the Isaac Computer Science Workbook published by the Raspberry Pi Foundation. It provides notes for students and teachers on how to use the workbook which contains over 300 computer science questions sorted by topic and level. The questions are meant to help students master A-level Computer Science concepts and can be accessed online or in the printed workbook.

Uploaded by

Ricky Jacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 354

Isaac Computer Science Workbook (OCR)

Published in the United Kingdom by the Raspberry Pi Foundation


www.raspberrypi.org

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

First published & printed 2022


Printed and bound in the UK

Typeset in LATEX

A catalogue record for this publication is available from the British Library

ISBN 978 1913 722 166

Use this book in parallel with the electronic version at


isaaccomputerscience.org. The Isaac Computer Science platform is free
to use and offers marking and compilation of results. Register as a student
or as a teacher to access full functionality and support.
i

Notes for the Student and the Teacher

About Isaac Computer Science


Isaac Computer Science is a resource for students of A level Computer Science. It
is part of the National Centre for Computing Education programme, funded by the
Department for Education. We provide high-quality learning materials for use in
the classroom, for homework, and for revision. Our team of experienced teachers
write resources to cover every topic in the A level Computer Science specification.
With Isaac Computer Science, you can learn about new topics or revise previous
learning, with confidence that all of the content is of high quality and relevant to
your A level exam.

About this book

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:

• Level 1: A question that requires one foundation concept to be directly


applied.
• Level 2: A question that requires one progression concept to be directly
applied.
• Level 3: A question that requires the application of multiple foundation
concepts.
• Level 4: A question that includes multiple concepts (foundation and/or
progression) that must be selected and combined with skill.

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.

Online versions of all of these questions can be found at isaaccomputerscience.org.


Students and teachers can register for free to access support and additional func-
tionality.
Students can:
• Learn from resources based on the AQA and OCR A level Computer Science
specifications
• Enter their answers for instant marking
ii

• Receive instant feedback on common wrong answers


• Track their progress
• Watch videos to help them answer questions
• Register for events such as Booster sessions, Masterclasses, and Discovery
Days
Teachers can:
• Access resources based on the AQA and OCR A level Computer Science
specifications
• Set questions for homework or work in class
• Get detailed results for each student
• Register their students or classes to attend events such as Booster sessions,
Masterclasses, and Discovery Days
• Register to attend Teacher CPD sessions
iii

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

Suggested Teaching Order

A suggested teaching order is listed below, please check isaaccomputerscience.


org/teaching_order for the latest version.

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

Notes for the Student and the Teacher i

Acknowledgements iii

Suggested Teaching Order iv

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

Data and information 117


17 Representation of numbers . . . . . . . . . . . . . . . . . . . 117

vi
CONTENTS vii

18 Representation of text . . . . . . . . . . . . . . . . . . . . . 141


19 Representation of images . . . . . . . . . . . . . . . . . . . . 144
20 Representation of sound . . . . . . . . . . . . . . . . . . . . 148
21 Compression . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
22 Encryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
23 Database concepts . . . . . . . . . . . . . . . . . . . . . . . . 165
24 SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168

Data structures and algorithms 179


25 Data structures . . . . . . . . . . . . . . . . . . . . . . . . . 179
26 Searching algorithms . . . . . . . . . . . . . . . . . . . . . . 212
27 Sorting algorithms . . . . . . . . . . . . . . . . . . . . . . . . 220
28 Pathfinding algorithms . . . . . . . . . . . . . . . . . . . . . 236
29 Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Impacts of digital technology 249


30 Legislation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Programming fundamentals 254


31 Programming concepts . . . . . . . . . . . . . . . . . . . . . 254
32 String handling . . . . . . . . . . . . . . . . . . . . . . . . . . 274
33 Subroutines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
34 File handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
35 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
36 Integrated Development Environments (IDEs) . . . . . . . . 307

Programming paradigms 308


37 Object-oriented programming . . . . . . . . . . . . . . . . . 308
38 Event-driven programming . . . . . . . . . . . . . . . . . . . 321

Software engineering 322


39 Program design . . . . . . . . . . . . . . . . . . . . . . . . . 322
40 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 330
41 Software engineering principles . . . . . . . . . . . . . . . . 337

Theory of Computation 340


42 Computational thinking . . . . . . . . . . . . . . . . . . . . . 340
Computer networks

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.

1.1.1 Getting connected!


https://isaaccs.org/eq/gcse_net_15

▶ 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.

⃝ The network should be more secure, because data passed by signals on


the higher frequency band is doubly encrypted.

⃝ The network should be faster, because the higher frequency band is


less congested.

⃝ The network should be more accessible, because signals on the higher


frequency band pass through walls more easily.

1
2 1. NETWORK FUNDAMENTALS

1.1.2 Bus topology


https://isaaccs.org/eq/net_network_01

▶ Which one of the statements below is an incorrect description of the


physical bus network topology?

⃝ 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.

1.1.3 Client-server and peer-to-peer networking


https://isaaccs.org/eq/gcse_net_11

▶ Below are statements that highlight some of the differences between client–
server and peer-to-peer networking. Pick one statement that is not correct.

⃝ Management of network security and maintenance is usually easier in


a client–server model.
⃝ In a client-server model, all processing must be done in the server side.
⃝ In a peer-to-peer network, a computer can act as both a client and a
server.
⃝ In a peer-to-peer network, any device can share resources with any
other device in the network.
1. NETWORK FUNDAMENTALS 3

1.1.4 Needed for WiFi


https://isaaccs.org/eq/net_network_08

▶ What would be a reason for not being able to connect to a specific private
wireless network?

⃝ Encryption not used on the network.


⃝ Your MAC address not being on the address table of the network
switch.
⃝ Being in the same room as another device on the network.
⃝ Not being in the range of the network.

1.1.5 Peer-to-peer networking


https://isaaccs.org/eq/gcse_net_12

▶ Which one of the statements below correctly describes the peer-to-peer


networking model?

⃝ In peer-to-peer networking, there is no central server.


⃝ In peer-to-peer networking, devices can’t share their resources with,
and request resources from the other devices in the network.
⃝ The peer-to-peer networking model is very secure, because every device
goes through an authentication process before it joins the network.
⃝ Peer-to-peer networking involves a central, powerful computer called a
server, and a number of client computers that need to connect to the
server to carry out specific tasks.

1.1.6 Benefits of WiFi


https://isaaccs.org/eq/net_network_05

▶ Which of the following is a benefit of using devices with WiFi connections


instead of wired connections?

⃝ The devices have a more reliable connection to the network.


⃝ Devices are portable which increases the flexibility of their use.
⃝ The communication of the devices is more secure.
⃝ The processing power of the devices increases.
4 1. NETWORK FUNDAMENTALS

1.1.7 Ethernet
https://isaaccs.org/eq/gcse_net_17

▶ Which of the following statements about Ethernet is not correct?

⃝ All Ethernet devices can process the data received from the router,
because they all use the same protocols.

⃝ Ethernet is a method to connect computers to a network using a wire-


less router.

⃝ Ethernet is a group of networking technologies commonly used in local


area networks.

⃝ Ethernet routers use the same set of protocols.

1.1.8 Let's go virtual


https://isaaccs.org/eq/gcse_net_20

A school has a humanities department, a maths department, and a PE de-


partment. Even though all computers in the school are connected using the
same physical infrastructure into one network, the school has divided the
computers up into separate virtual networks. This means that they appear
to the users as separate LANs, because certain resources should only be
accessed by the members of a specific department.
▶ Select the statements that describe a benefit of having a virtual network
(or VLAN).

□ Security is easier to manage, as a single LAN connects all the com-


puters.

□ It’s cheaper to set up one physical LAN and then divide it into virtual
networks, rather than setting up multiple LANs.

□ Scalability is easier, as devices can be located anywhere in the building


but still belong to the necessary LAN.

□ Each computer can access all other computers in any virtual networks
installed.
1. NETWORK FUNDAMENTALS 5

1.1.9 Star topology


https://isaaccs.org/eq/net_network_02

▶ Which one of the below statements correctly describes a principle of the


star network topology?

⃝ In a star topology, a failure in the cable that a device uses to connect


to the network will bring the whole network to a stop.

⃝ The most efficient way to set up a LAN with a star topology is by


using a hub to direct the traffic between the connected devices.

⃝ Collisions do not occur in a star topology, because the central device


manages traffic by using the carrier-sense multiple access with collision
detection (CSMA/CD) protocol.

⃝ A network physically set up in star topology can behave logically as


a bus network when the central device follows a bus protocol when
transmitting data.

1.1.10 Client–server networking


https://isaaccs.org/eq/net_network_03

▶ Which one of the below statements is correct for the client-server net-
working model?

⃝ A server requests services to clients in order to process and display


their responses.

⃝ 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.

⃝ If the server is unable to provide a response the clients exchange data


directly with each other.
6 1. NETWORK FUNDAMENTALS

1.1.11 Peer-to-peer networking


https://isaaccs.org/eq/net_network_04

▶ Which one of the following statements is correct in relation to the peer-


to-peer networking model?

⃝ 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.12 The order of CSMA/CA


https://isaaccs.org/eq/net_network_07

▶ Number the following steps of CSMA/CA with RTS/CTS in the order


that they operate:

□ Check that the channel is idle


□ Wait for Clear to Send
□ Else, if free, send Request to Send
□ If received, send message
□ If not free, wait random time
1. NETWORK FUNDAMENTALS 7

1.1.13 Collisions
https://isaaccs.org/eq/net_network_10

▶ Fill in the missing words

Transmission across shared network media has to contend with collisions.

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.

1.1.14 Network interface controller


https://isaaccs.org/eq/net_network_11

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.

□ A router can be used in combination with a wireless NIC to repeat and


strengthen the wireless signal.

□ When a wireless NIC can connect to a device using a USB port it is


often referred to as a ‘wireless network adapter’.

□ A wireless NIC can be plugged into a device to enable wireless com-


munication.
8 1. NETWORK FUNDAMENTALS

1.1.15 Office space


https://isaaccs.org/eq/net_network_13

An organisation has decided to make office space available to remote working


employees who occasionaly wish to use an office. They need to consider how
to set up the network and are considering a star topology using a switch.
▶ Which of the five statements listed below are features of a star topology?
More than one statement may be correct.

□ The network will not allow two or more computers to transmit at the
same time because it may cause a collision.

□ The switch will broadcast the packets of data to all devices.

□ Terminators will be used at the end of the cables so that the electrical
signal will not bounce back.

□ Every device will be connected to the switch,.

□ Every device will send data packets through the switch.

1.3.1 Limit wireless collisions


https://isaaccs.org/eq/net_network_09

▶ Fill in the missing words

WiFi networks suffer from ‘ nodes’. This is where two devices


on a network are not in range of one another and both try and send to a
third device.

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

to send / to send control pro-


tocol. This ensures only one device can send their data at any one point in
time.
1. NETWORK FUNDAMENTALS 9

1.3.2 Star network topologies


https://isaaccs.org/eq/gcse_net_02

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?

1.3.3 Network topologies


https://isaaccs.org/eq/gcse_net_01

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.

2.1.1 Controlling information


https://isaaccs.org/eq/gcse_net_16

▶ Which of the following would be classed as control information inside a


packet?

⃝ The route that the packet should take

⃝ The payload

⃝ The checksum

⃝ The recipient’s IP address

2.1.2 Once you POP, you can't stop


https://isaaccs.org/eq/gcse_net_18

▶ 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.

⃝ There is a maximum limit of 100 emails that can be retrieved at once.

⃝ 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

2.1.3 Data packets


https://isaaccs.org/eq/gcse_net_10

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?

⃝ Time the data was sent


⃝ Sender’s IP address
⃝ Checksum
⃝ Receiver’s IP address

2.1.4 HTTP protocol


https://isaaccs.org/eq/gcse_net_05

Networks use protocols to establish a common set of rules to communicate.


Network communication on the internet is arranged in abstract layers called
the TCP/IP model (also referred to as the TCP/IP stack).
▶ At which layer in this model would you expect to see the HTTP protocol?

⃝ Application layer
⃝ Link or data link layer
⃝ Network or internet layer
⃝ Transport layer

2.1.5 TCP protocol


https://isaaccs.org/eq/gcse_net_06

Networks use protocols to establish a common set of rules to communicate.


Network communication on the internet is arranged in abstract layers called
the TCP/IP model (also referred to as the TCP/IP stack).
▶ At which layer in this model would you expect to see the TCP protocol?

⃝ Link or data link layer


⃝ Transport layer
⃝ Network or internet layer
⃝ Application layer
12 2. THE INTERNET

2.1.6 Rooting for an answer


https://isaaccs.org/eq/net_internet_01

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?

⃝ Only the data link (link) layer

⃝ All of the layers

⃝ Internet (network) and transport layers

⃝ Internet (network) and data link (link) layers

2.1.7 Big headed


https://isaaccs.org/eq/net_internet_02

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?

⃝ Source and destination sockets

⃝ Source and destination MAC addresses

⃝ Source and destination IP addresses

⃝ Source and destination port numbers

2.1.8 Too many servers


https://isaaccs.org/eq/net_internet_03

▶ 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

2.1.9 Sending an email


https://isaaccs.org/eq/net_internet_11

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

⃝ Link (Data link) layer

⃝ Internet (Network) layer

⃝ Application layer

2.3.1 Dude, where's my page?


https://isaaccs.org/eq/gcse_net_13

▶ Number the following statements in order, to explain what happens when


you type the URL of a webpage into your browser. (Assume that none of
the information is cached.)

□ 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

2.3.2 Layers of protocols


https://isaaccs.org/eq/gcse_net_14

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)

Below are four commonly used communication protocols. Each protocol


works on only a single layer of the layers listed above.
▶ Using the order of the layers given above, number the protocols so that
they are in the same position in the list as the layer that they work on:

□ Wi-Fi
□ IP
□ UDP
□ HTTP
2.3.3 Neighbourhood watch
https://isaaccs.org/eq/net_internet_09

A network has been configured with a subnet mask of 255.255.192.0 (or


/18)
▶ Which of the following pairs of hosts would be on the same network
(subnet)?

⃝ 192.168.12.120 and 192.128.12.120


⃝ 192.168.200.12 and 192.168.220.12
⃝ 192.168.200.13 and 192.168.120.136
⃝ 192.128.226.12 and 192.128.128.12
2. THE INTERNET 15

2.3.4 Communication rules


https://isaaccs.org/eq/gcse_net_21

Protocols are agreed sets of rules that allow devices to communicate with
each other. Some of the protocols used on the Internet are:

1. Hypertext Transfer Protocol (HTTP)

2. Secure Hypertext Transfer Protocol (HTTPS)

3. File Transfer Protocol (FTP)

4. Simple Mail Transfer Protocol (SMTP)

5. Post Office Protocol (POP)

6. Internet Message Access Protocol (IMAP)

▶ Number these descriptions in order to match the order of the protocols


listed above. For example, first you need to find the description for the
Hypertext Transfer Protocol (HTTP).

□ Used to transfer and share files across the internet.


□ Encapsulates all of the requested information in an encrypted data
stream so that it is secure.

□ Responsible for retrieving emails from email servers by email-client


applications.

□ Used when an email-client application wants to send an email to an


email server.

□ Retrieves emails from the email server. Deletes the remote copy of
the email once it has been downloaded to a computer.

□ Used to access webpages and responsible for retrieving information


from remote servers across the World Wide Web.
16 2. THE INTERNET

2.3.5 Send it
https://isaaccs.org/eq/net_internet_05

In a wide area network, devices are configured as follows:

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

Computer A wants to send a packet to 192.12.0.15.


▶ Where will it be sent to in the first instance? Answer with the IP address
in dotted decimal form
2. THE INTERNET 17

2.3.6 What's in an address?


https://isaaccs.org/eq/net_internet_06

An internet host has the IP address 192.168.100.4/17 — the address is


written in CIDR form.
▶ Three facts in the list below can be determined by the specified address.
Select the three that are correct.

□ The host has a non-routable IP address

□ Host 192.168.120.4 is on the same network (subnet)

□ The subnet mask could be expressed as 255.255.128.0

□ The broadcast address is 192.168.255.255

□ The network (subnet) can support 32,768 hosts

□ The network (subnet) address is 192.168.100.0

2.3.7 What's in a URL


https://isaaccs.org/eq/net_internet_08

A URL contains lots of information. Consider this URL:


1 https :// mail. google .com/mail/u/0/# inbox

▶ Select all of the facts from the list below that can be determined by
studying the URL:

□ mail is a subdomain

□ The TLD is com

□ google.com is a fully qualified domain name

□ The data exchanged between client and server will be encrypted

□ The request will use server port 143


18 2. THE INTERNET

2.3.8 Browser hopping


https://isaaccs.org/eq/net_internet_07

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.

1. Stay the same


2. Take on the next sequential value
3. Change to a value chosen at random between a specified range
4. Change to a new value chosen from a list on the server
5. Change to a new value allocated to hardware within the client

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.

3.1.1 Network media


https://isaaccs.org/eq/net_hard_03

▶ Which of the following network media can provide reliable communication


over a long distance?

⃝ Fibre-optic cable

⃝ WiFi

⃝ Coaxial cable

⃝ UTP (Ethernet) cable

3.3.1 What type of cable is that?


https://isaaccs.org/eq/net_hard_04

Digital data can be transmitted between computers and devices through


wires (cables) and wireless communication. Two types of cables that are
commonly used in wired networks are unshielded twisted pair (UTP) cables
and fibre-optic cables.
▶ Which of the following statements is false?

⃝ A UTP cable can reliably carry electrical signals for long distances.

⃝ Data transmitted through fibre-optic cables is not affected by electrical


interference.

⃝ A fibre-optic cable uses repeaters to boost the signal when needed.

⃝ An unshielded twisted pair (UTP) cable is also commonly referred to


as an ‘Ethernet cable’ or a ‘Cat 5 cable’.

19
20 3. NETWORK HARDWARE

3.3.2 Dave's data


https://isaaccs.org/eq/net_hard_05

Dave’s work computer is connected to his company’s LAN. He types in the


web address of a website he wants to visit.
▶ Number the following network hardware components in the order in which
they would receive the data packet containing this request. (Note: This is
not an exhaustive list of all hardware required. Some steps in the journey
have been left out.)

□ Network interface card


□ UTP cable
□ Switch
□ Fibre optic cable
□ Router
3.3.3 Network problem
https://isaaccs.org/eq/net_hard_01

A large company with offices in different cities has many interconnected


networks. There is a hardware fault on one of the office networks that
means that none of the computers on one network can communicate with
each other. Devices on other networks can still communicate with each other.
▶ Which is the most likely hardware fault?

⃝ The modem has broken.

⃝ The NICs have lost their configuration settings.

⃝ A switch connecting computers in the affected office has broken.

⃝ The router in the affected office has been switched off.


3. NETWORK HARDWARE 21

3.3.4 Network hardware


https://isaaccs.org/eq/net_hard_02

▶ Which of the following is not a component that is used to communicate


across a local area network?

⃝ UTP (Ethernet) cable


⃝ Switch
⃝ Wireless NIC
⃝ Modem
4 Communication
Communication systems determine the way in which computers exchange
data. There are a wide variety of ways in which data can be transmitted,
and the method chosen will influence both the speed and the reliability of
data transfer. Different communication systems are suitable for different ap-
plications. Each communication system comprises a variety of components,
which must be configured to meet the demands of the applications that the
system serves.

4.1.1 Bandwidth
https://isaaccs.org/eq/gcse_net_03

▶ Define the term bandwidth.

⃝ A method of assigning IP addresses.


⃝ The amount of data that can be transmitted in a given time.
⃝ The amount of nodes on a network.
⃝ A preventative method that helps to stop unauthorised users accessing
a network.

4.1.2 Protocols
https://isaaccs.org/eq/gcse_net_08

▶ What is a network protocol?

⃝ A set of rules that define how computers on a network communicate.


⃝ A piece of malware.
⃝ A way of connecting two or more computers together.
⃝ A device to enable a stand-alone computer to connect to the internet.

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.

5.1.1 I need a rest


https://isaaccs.org/eq/net_internet_10

REST (Representational State Transfer) is an architecture style for develop-


ing web services that specify the use of distinct Hypertext Transfer Protocols
for all four CRUD (Create/Retrieve/Update/Delete) operations.
▶ In the table below, specify the HTTP methods that will complete the
mapping. Choose the methods from the following list: DELETE, GET,
POST, PUT.

REST operation SQL HTTP method


Create INSERT
Retrieve SELECT
Update UPDATE
Delete DELETE

5.1.2 Do you have ID?


https://isaaccs.org/eq/prog_gui_02

▶ Select all correct statements about HTML ID and class attributes.

□ An ID given to a HTML element should be unique

□ The same class can be assigned to multiple HTML elements

□ The style for an ID can be defined using CSS

□ The same ID should be assigned to multiple HTML elements

□ An ID must contain letters and numbers

□ The style for a class can be defined using CSS

23
24 5. WEB TECHNOLOGIES

5.1.3 The downfall of Jason


https://isaaccs.org/eq/net_internet_04

The figure below shows a fragment of a JSON file.


1 "quiz ": {
2 " arithmetic ": {
3 "q1": {
4 " question ": "60 x 3 = ?",
5 " options ": [
6 "180" ,
7 "63" ,
8 "20" ,
9 "57"
10 ],
11 " answer ": "180"
12 },
13 "q2": {
14 " question ": "12 x 8 = ?",
15 " options ": [
16 "20" ,
17 "96" ,
18 "1.5" ,
19 "4"
20 ],
21 " answer ": "96"
22 }
23 }
24 }

▶ Which of these is an advantage of using JSON files over XML as a method


for exchanging data? Tick all that apply:

□ Objects use a simple “key” → “value” mapping

□ The files are quicker to parse

□ The file size will be smaller

□ You can include a schema that provides constraints on the file contents
5. WEB TECHNOLOGIES 25

5.1.4 Dolly's Tea Room


https://isaaccs.org/eq/prog_gui_03

Here is part of the web page for Dolly’s Tea Room.

Dolly’s Tea Room


Welcome to Dolly’s Tea Room, where we serve:

• 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

5.1.6 Advice for Tim


https://isaaccs.org/eq/prog_gui_05

▶ 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?

⃝ You can only add one CSS declaration to an inline style


⃝ The property to change the text colour should be text-color not color
⃝ The <h1> tag doesn’t require a closing tag
⃝ Inline styles are a bad idea because you have to edit the style for every
element separately

5.3.1 Scraping the barrel


https://isaaccs.org/eq/prog_gui_01

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.

□ A loop that stops when variable a < variable b


□ Output the value of variable a to the screen
□ Define two variables and give each a starting value
□ End the loop
□ Subtract the value of b from a
□ A loop that runs until variable a >= variable b
28 5. WEB TECHNOLOGIES

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

▶ Write one line of code to go at each underlined position to generate the


output shown.
1 <style >
2 h3 {
3 color : green ;
4 }
5
6 # large_text {
7 font -size: 60px;
8 border -style: dotted ;
9 border -width: 2px;
10 width: 300 px;
11 }
12 </style >
13
14 <h1 >Cricket </h1 >
15
16 ____________________________________________
17
18 <ol >
19 <li >Ball </li >
20 <li >Bat </li >
21 <li >Stumps </li >
22 </ol >
23
24 <p>When someone gets out , you shout </p>
25
26 ____________________________________________
32 5. WEB TECHNOLOGIES

5.3.4 HTML fail


https://isaaccs.org/eq/prog_gui_08

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 .

There are two mistakes in the code.

▶ Which two lines contain errors?

Line and line

▶ Rewrite the code and resolve the two errors.


5. WEB TECHNOLOGIES 33

5.3.5 Scriptly come dancing


https://isaaccs.org/eq/prog_gui_04

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.

6.1.1 Performance upgrade


https://isaaccs.org/eq/sys_arch_15

▶ 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

6.1.2 Fetch operation


https://isaaccs.org/eq/sys_arch_16

▶ Select one statement that describes one operation that happens in the
fetch phase of the fetch-decode-execute cycle.

⃝ The instruction held in the current instruction register (CIR) is split


into operand and opcode.

⃝ The result of the instruction is stored in a general-purpose register or


the accumulator.

⃝ The arithmetic and logic unit (ALU) carries out the instruction.

⃝ The address of the next instruction to be executed is copied to the


memory address register (MAR).

6.1.3 Embedded systems


https://isaaccs.org/eq/gcse_sys_21

An embedded system is a computer system dedicated to a specific task (or


set of tasks). Embedded systems, just like general purpose computers, take
input, run processes, and produce output. The emebdded system combines
the processor, memory, and input/output devices into a single unit.
Most modern day devices and appliances contain embedded systems, as they
need some level of computational processing.
▶ Which of the options listed below would not be suitable for an embedded
system?

⃝ Laptop

⃝ Central Heating

⃝ Medical Equipment

⃝ Digital clock

⃝ Microwave

⃝ Vending Machine
36 6. SYSTEMS ARCHITECTURE

6.1.4 Find the odd one out


https://isaaccs.org/eq/gcse_sys_06

▶ Which one of the below is not an example of an embedded system?

⃝ Car anti-lock braking system (ABS)

⃝ Car navigation system

⃝ Smartphone with a navigation app

⃝ Dishwasher

6.1.5 A fetching problem


https://isaaccs.org/eq/gcse_sys_14

▶ During the fetch stage of the fetch-decode-execute cycle, a program in-


struction is fetched from the main memory. What is the name of the com-
ponent that connects the processor to main memory?

⃝ Register

⃝ ALU

⃝ Bus

⃝ Control unit

6.1.6 Clock speed


https://isaaccs.org/eq/gcse_sys_15

▶ 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?

□ More instructions can be executed per second

□ More cycles are completed per second

□ Programs take less time to run

□ Data needs to be fetched from RAM less often


6. SYSTEMS ARCHITECTURE 37

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

6.1.8 The decode stage


https://isaaccs.org/eq/gcse_sys_17

▶ During the decode stage of the fetch-decode-execute cycle, which com-


ponent of the CPU is used to send signals to other components on what
needs to be done to execute the instruction?

⃝ Main memory (RAM)

⃝ Arithmetic and logic unit (ALU)

⃝ Control unit (CU)

⃝ Memory data register (MDR)

6.1.9 A stage of the instruction cycle


https://isaaccs.org/eq/sys_arch_07

▶ At which stage of the fetch-decode-execute cycle does the following oper-


ation occur?
Operation: The control unit identifies the type of instruction that
is kept in the current instruction register (CIR).
38 6. SYSTEMS ARCHITECTURE

6.1.10 Storing instructions and data


https://isaaccs.org/eq/gcse_sys_19

The term Von Neumann architecture is used to refer to any computer


system where an operation to fetch an instruction and an operation to fetch
data cannot occur at the same time because they share a common bus.
▶ Which of these statements about von Neumann architecture are correct?
(Select all that apply)

□ The memory address register holds the address in main memory that
is currently being read or written.

□ Instructions and data are held in separate units of main memory.

□ It uses registers to help prevent slowing down the fetch-decode-execute


cycle.

□ 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.

6.1.11 Fetch, decode and execute


https://isaaccs.org/eq/gcse_sys_20

▶ Which of the following statements best describes the fetch-decode-execute


cycle?

⃝ The fetch-decode-execute cycle is a process that the CPU repeats con-


tinuously in order to execute instructions.

⃝ The fetch-decode-execute cycle ensures improves the security of a com-


puter system.

⃝ The fetch-decode-execute cycle uses the the arithmetic logic unit (ALU)
to connect the registers to the main memory.

⃝ The fetch-decode-execute cycle uses a bus to store the data.


6. SYSTEMS ARCHITECTURE 39

6.1.12 Select the correct component


https://isaaccs.org/eq/gcse_sys_01

▶ Which one of the following CPU components is used to reduce how long
the processor has to wait for data and instructions?

⃝ Cache

⃝ Arithmetic and logic unit (ALU)

⃝ Bus

⃝ Control unit (CU)

6.1.13 Decode stage processes


https://isaaccs.org/eq/gcse_sys_02

▶ 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.

⃝ The instruction to be executed is fetched from the main memory to


the CPU.

6.1.14 Purpose of the control unit


https://isaaccs.org/eq/sys_arch_01

▶ Which of the functions below is performed by the control unit during the
fetch-decode-execute cycle?

⃝ Store intermediate results of calculations

⃝ Generate regular clock pulses to synchronise components

⃝ Decode a processed instruction to determine its type

⃝ Carry out arithmetic and/or logical operations


40 6. SYSTEMS ARCHITECTURE

6.1.15 Main memory characteristics


https://isaaccs.org/eq/sys_arch_02

▶ Which of the sentences below is a characteristic of the main memory?

⃝ The contents of a memory location are erased after they are read

⃝ The memory locations can be accessed in any order

⃝ The I/O controllers can directly access every memory location

⃝ The time it takes to access a memory location depends on its address

6.1.16 Von Neumann vs Harvard


https://isaaccs.org/eq/sys_arch_03

▶ Which of the sentences below is a characteristic of the von Neumann


architecture?

⃝ It is commonly used in modern embedded systems

⃝ It uses separate buses for instructions and data

⃝ It keeps instructions and data in different memory stores

⃝ It is used extensively in modern general-purpose computers

6.1.17 Characteristics of cache


https://isaaccs.org/eq/sys_arch_04

▶ Which of the sentences below is a characteristic of cache?

⃝ Cache sits between the main memory and secondary storage

⃝ Cache stores the most frequently used instructions and data

⃝ Cache is erased every time its components are read

⃝ Cache is a cheap but slow type of memory


6. SYSTEMS ARCHITECTURE 41

6.1.18 Processor performance


https://isaaccs.org/eq/sys_arch_06

▶ Which of the below statements describes a way that can be used to improve
processor performance?

⃝ Use a multicore computer (instead of one core) to allow for parallel


processing
⃝ Use a data bus with a width (number of parallel lines) that is half the
word size
⃝ Decrease the clock speed so that more instructions can be executed
per second
⃝ Reduce the size of Level 1 cache memory to avoid duplication of data

6.1.19 A type of processing


https://isaaccs.org/eq/sys_arch_13

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?

6.1.20 Little boxes


https://isaaccs.org/eq/sys_hard_10

▶ John von Neumann proposed a general purpose computer made up of


three boxes. Which of the following statements provides a correct definition
of a ‘von Neumann machine’?

⃝ A processor, main memory, and secondary storage linked by a system


bus
⃝ A processor, clock, and main memory linked by a system bus
⃝ A processor, cache, and main memory linked by a system bus
⃝ A processor, main memory, and I/O controllers linked by a system bus
42 6. SYSTEMS ARCHITECTURE

6.1.21 A purpose of CIR


https://isaaccs.org/eq/sys_arch_09

▶ What is the role of the CIR in the fetch-decode-execute cycle?

⃝ 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

6.1.22 Take the RISC


https://isaaccs.org/eq/sys_arch_10

▶ Which of the following statements is correct about RISC processors?

⃝ Their instructions are reduced to simple operations which facilitates


the use of pipelining
⃝ They are not very commonly used because they are expensive to design
and produce
⃝ Their instruction set consists of a small amount of specialised instruc-
tions
⃝ They consist of complex circuitry that requires more power to operate

6.1.23 Status register with a purpose


https://isaaccs.org/eq/sys_arch_12

▶ 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.

⃝ Indicates if a calculation has produced an overflow error.


⃝ Handles the interrupt that may occur due a hardware failure.
⃝ Add the carry bit produced during the calculation of adding two num-
bers.
⃝ Ensure that if a negative number is produced, it is not used as a divisor.
6. SYSTEMS ARCHITECTURE 43

6.1.24 Missing labels


https://isaaccs.org/eq/sys_arch_11

▶ The following diagram represents a well known computer architecture.


The labels have not yet been added to identify the components, along with
the label of the architecture itself. Identify the architecture and select the
correct labels to complete the diagram.

A B

G Havard architecture G Havard architecture


A Output devices A Input devices
B Input devices B Output devices
C Processor C Processor
D Instruction memory D Instruction memory
E Data memory E Data memory
F Secondary Storage F Secondary Storage
C D

G Von Neumann architecture G Von Neumann architecture


A Input devices A Input devices
B Output devices B Output devices
C Processor C Processor
D Instruction memory D Instruction memory
E Data memory E Data memory
F Address bus F Address bus
44 6. SYSTEMS ARCHITECTURE

6.3.1 The MAR value


https://isaaccs.org/eq/sys_arch_14

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

6.3.2 CPU performance


https://isaaccs.org/eq/gcse_sys_07

Matthew is a web designer who uses processor-intensive applications (e.g.


Adobe Photoshop). He wants to buy a new laptop and has the following
options.
▶ Which one is the best choice for him?

⃝ Clock speed = 4,600 MHz Cores = 4 Cache = 8 MB


⃝ Clock speed = 3.5 GHz Cores = 6 Cache = 10 MB
⃝ Clock speed = 3.6 GHz Cores = 2 Cache = 4 MB
⃝ Clock speed = 1.2 GHz Cores = 4 Cache = 2 MB

6.3.3 Address bus width


https://isaaccs.org/eq/sys_arch_05

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

6.3.4 Prepare for processing


https://isaaccs.org/eq/gcse_sys_18

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 all need to be loaded into the processor at once so it


can read them

□ The instructions are loaded into main memory from secondary storage

□ The data required for the instructions has been loaded into main
memory

6.3.5 Instruction cycle


https://isaaccs.org/eq/sys_arch_08

▶ Number the operations below in the order they are performed during the
fetch stage of the fetch-decode-execute cycle.

□ The fetched instruction is saved in the MBR/MDR


□ The contents of the MAR are used to access the correct location in
memory

□ At the same time, the contents of the PC are incremented by one


□ The fetched instruction is transferred to the processor using the
data bus

□ The contents of the MBR/MDR are copied to the CIR


□ The contents of the PC are copied to the MAR
46 6. SYSTEMS ARCHITECTURE

6.3.6 Getting what you pay for


https://isaaccs.org/eq/gcse_sys_22

A civil engineer needs to use applications that require a high specification


computer system (e.g. AutoCAD). She has only a basic laptop computer
and its configuration is not good enough to run the applications, which
are processor intensive. She has decided to buy a more powerful desktop
computer and there are a few options available.
In general terms, the higher the clock speed, the more instructions a com-
puter can process per second. However, other factors relating to the system’s
architecture, such as cache and the number of cores, should be considered.
▶ Consider the options below and select the specification that will best
match her needs to run processor-intensive applications.

⃝ 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.

7.1.1 Optical storage


https://isaaccs.org/eq/gcse_sys_13

▶ Select three of the following statements about optical storage that are
true:

□ Optical media isn’t easily portable due to the internal moving parts

□ A laser beam burns tiny pits onto the disc

□ A CD-ROM is a type of optical media

□ Optical media can only be read-only memory

□ Optical media has a limited amount of storage capacity compared to


other types of storage

□ Optical media is organised in groups of circular discs called platters

7.1.2 How many video files?


https://isaaccs.org/eq/gcse_sys_08

Pamela has a 128GB USB flash drive that is 60% full.


▶ How many video files can she store on the flash drive if each file is 25.6MB?
Assume 1kB = 1000 bytes.

47
48 7. MEMORY AND STORAGE

7.1.3 Which type of storage?


https://isaaccs.org/eq/gcse_sys_04

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?

7.1.4 Hard drive disadvantage


https://isaaccs.org/eq/gcse_sys_05

▶ Which one of the statements below describes a disadvantage of magnetic


hard drives (HDDs)?

⃝ It is significantly slower to access data stored on a hard drive than on


a solid state disk because the hard drive has moving parts, such as the
read/write head and the rotating platters.

⃝ Hard drives can be difficult to manufacture.

⃝ 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.

7.1.5 Keep it safe


https://isaaccs.org/eq/sys_hard_03

▶ A musician wants to keep a single permanent copy of a composition on a


CD. Which of the three CD formats should she choose?
7. MEMORY AND STORAGE 49

7.1.6 How much space?


https://isaaccs.org/eq/gcse_data_26

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?

7.1.7 Data storage units in order


https://isaaccs.org/eq/gcse_data_18

▶ 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

Marik’s total internal back-up storage phone capacity is 50 GB.


▶ How much free space is left of Marik’s back-up storage phone capacity?

⃝ 44,500,000,000 bytes

⃝ 5,000,500,000 bytes

⃝ 5,000,000,000 bytes

⃝ 5,500,000,000 bytes

7.1.9 How many photos?


https://isaaccs.org/eq/sys_hard_01

A photographer uses a digital camera that captures images with an average


file size of 5.6MB. She has purchased an external 500GB SSD to store her
work.
▶ How many photographs (of average size) will she be able to store? Round
your answer to the nearest whole number.
7. MEMORY AND STORAGE 51

7.3.1 The memory needed


https://isaaccs.org/eq/sys_mem_stor_01

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

7.3.2 The purpose of RAM


https://isaaccs.org/eq/gcse_sys_11

▶ Select the statement that describes a purpose of Random-access memory


(RAM).

⃝ CD-RWs are made up of RAM so that they can be rewritable.


⃝ RAM is used to store the BIOS which is used when the computer is
started.
⃝ RAM is used to store instructions and data that the processor can
directly access.
⃝ The hard disk drive (HDD) is made up of RAM so that data can be
permanently stored.
52 7. MEMORY AND STORAGE

7.3.3 I need that data fast


https://isaaccs.org/eq/sys_hard_06

Data can be stored in many different places within a computer system.


▶ Number the storage components listed below in order of speed of access,
from fastest (1) to slowest (4).
You can assume that the speed of each device is typical of its class.

□ 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

□ ROM is a type of primary memory

□ Main memory is always volatile

□ RAM is volatile memory

□ Virtual memory uses secondary storage to store data from the RAM

□ The contents of ROM are lost when power is switched off


7. MEMORY AND STORAGE 53

7.3.5 RAM or ROM?


https://isaaccs.org/eq/gcse_sys_03

▶ Number the statements below into order to create one paragraph about
the characteristics of RAM and then the characteristics of ROM.

□ the CPU is currently working with because


□ it is very useful for storing instructions and data
□ when the computer is switched on.
□ RAM
□ is a non-volatile type of memory and
□ is a volatile type of memory and
□ ROM
□ it is used to store software that doesn't need to be changed
□ such as the code needed to load the Operating System
□ it can be read from and written to.
8 Hardware
Hardware is the word used to describe the physical parts of a computer
system. Hardware can refer to core internal components such as the CPU,
or external devices known collectively as peripherals. Peripherals might
include input and output devices, as well as external storage such as a re-
movable hard drive. Specialist types of hardware required for a network are
discussed in the Network hardware (Chapter 3) topic.

8.1.1 Barcode correction (part 1)


https://isaaccs.org/eq/sys_hard_11

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

• Append this number to the end of the sequence

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

8.1.2 Barcode correction (part 2)


https://isaaccs.org/eq/sys_hard_12

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

8.1.3 Let's take a fingerprint


https://isaaccs.org/eq/sys_hard_02

Biometric systems allow people to be identified by one or more physical


characteristics.
▶ Why is your iris more reliable than a fingerprint for identification pur-
poses?

⃝ Fingerprints are more easily copied.


⃝ Fingerprints contain too much data to be processed quickly.
⃝ Fingerprints cannot be scanned if the person is sweating.
⃝ Fingerprints are not always unique.
56 8. HARDWARE

8.3.1 Which printer?


https://isaaccs.org/eq/sys_hard_07

Abdel [A] works as a school photographer. When he has taken a student’s


picture, he prints out an order form with a proof copy of the photo for the
student to take home.
Briony [B] works as a designer. She uses specialist drawing software to
create large-scale drawings of her designs for the production team.
Cema [C] is a teacher. She produces worksheets for her students that are
printed by the reprographics department.

▶ 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).

9.1.1 Some types of software


https://isaaccs.org/eq/sys_os_04

▶ System software is used as an interface between the hardware and user


applications. From the options below, select all examples that are types of
system software.

□ Email software

□ Data compression software

□ Disk defragmenters

□ File managers

□ Debuggers

□ Backup software

9.1.2 Source code


https://isaaccs.org/eq/sys_os_06_new

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

9.1.3 Application software


https://isaaccs.org/eq/sys_os_01

Software can be categorised according to its role in the operation of a com-


puter system. Here are some examples of tasks you might wish to perform.
▶ For which of these tasks would you use application software?

□ Checking for a virus within a folder on a hard disk

□ Producing a graph of ice cream sales over a year

□ Drawing a logo for a magazine

□ Sending a photo to a user of a social media platform

□ Monitoring the fan speed of a processor when playing a computer game

□ Setting up the default operation of speakers on a desktop PC

□ Keeping records about customers who visit a shop in order to email


promotions at a later date

□ Navigating to a landmark in a particular town

□ Encrypting the contents of a USB flash drive

□ Uninstalling software from a tablet device

9.1.4 It could be helpful


https://isaaccs.org/eq/sys_os_02

▶ Four categories of system software are operating systems, utilities, lib-


rary programs and translators. Which of the following definitions applies to
utility software?

⃝ Software that converts code written by a programmer into a form that


can be executed by a computer system.

⃝ Software that manages hardware, software, and resources, and provides


services for other software.

⃝ Software that improves the security or performance of a computer sys-


tem.

⃝ Shared repositories of code that can be used by other programs.


9. SOFTWARE 59

9.1.5 Benefits of open source software


https://isaaccs.org/eq/sys_os_10

▶ Which of the following is an advantage of using open source software?

⃝ The original developers manage software updates


⃝ The software is guaranteed to be updated regularly
⃝ The developers of the software provide technical support
⃝ You can easily switch to another piece of software

9.1.6 Types of software


https://isaaccs.org/eq/sys_soft_01

▶ Three categories of software are: general purpose software, program trans-


lators, and utility software. Software in which category is responsible for
reorganising files on a hard disk and encrypting data on storage devices?

⃝ Utility software
⃝ General purpose software
⃝ Program translators

9.3.1 Custom made


https://isaaccs.org/eq/sys_os_03

▶ A restaurant uses a bespoke system that allows the employees to quickly


learn it and become effective team members with minimal training. Based
on the above text, select all the statements that describe the benefits of
having a bespoke software:

⃝ The restaurant will be able to commercialise the source code created


for them, regardless of permission from the software developer.
⃝ The restaurant won’t encounter any serious problems or bugs as the
software has been thoroughly tested.
⃝ The restaurant will spend less money by having a bespoke software
made for them.
⃝ The restaurant’s system was custom made in accordance with the user
specification and needs.
10 Operating systems
The operating system is the most fundamental piece of system software.
All other software requires an operating system in place in order to operate.
The operating system manages the operations that are common to different
pieces of software running on the same system, such as memory manage-
ment, scheduling, and interrupts.

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:

⃝ Multitasking operating system


⃝ Distributed operating system
⃝ Embedded operating system
⃝ Real-time operating systems
⃝ Multiuser operating system

10.1.2 What are drivers?


https://isaaccs.org/eq/sys_os_08

▶ Fill in the missing words.

Device drivers are specialist pieces of that are created by


manufacturers of devices.

They allow the to interact with the device that it needs to


control. Specific functions within the drivers are called .

60
10. OPERATING SYSTEMS 61

10.1.3 Don't interrupt me!


https://isaaccs.org/eq/sys_os_05

An interrupt is a signal to the processor that a high-priority event has oc-


curred and immediate action is required. To make this possible, the processor
must stop what it is doing and service the interrupt.
▶ Number the following steps in order to describe what happens when the
processor receives an interrupt.

□ Continue the original process


□ Determine the interrupt service routine to run
□ Complete the current fetch-decode-execute cycle
□ Restore the register values
□ Service the interrupt
□ Save the registers to memory
10.1.4 BIOS
https://isaaccs.org/eq/sys_os_07

Here are some tasks that may be performed by a computer system.


▶ Tick the tasks the BIOS is responsible for

□ Keeping track of the system time

□ Compiling programs that the computer system must run

□ Configuring the operating parameters of the CPU at boot time

□ Testing the hardware that is connected as the computer boots

□ Knowing where files are stored on a hard disk

□ Running code when interacting with hardware devices


62 10. OPERATING SYSTEMS

10.3.1 Me first!
https://isaaccs.org/eq/sys_os_11

A scheduling algorithm determines the order in which an operating system


will execute processes. How quickly a process will finish depends on the size
of the job and the scheduling algorithm used.
Some jobs are sent to be processed. The times shown are in minutes.

Arrival time Job Time to complete


0:00 A 5:00
2:30 B 2:00
3:10 C 1:00

▶ 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:

First come, first served: Shortest time remaining:


11 High- and low-level languages
Most programming languages that you will have heard of are high-level lan-
guages. Python and C# are examples of high-level languages that are widely
used in education and in the workplace. A high-level language is one that
is user-oriented in that it has been designed to make it straightforward for
a programmer to convert an algorithm into program code.
A low-level language is machine-oriented. Low-level programs are ex-
pressed in terms of the machine operations that must be performed to carry
out a task. This makes writing programs more difficult, as the algorithm
must be specified in terms of the capabilities and specifications of the pro-
cessor. Low-level languages are named for the processor (or processor family)
that they are designed for, and are often referred to as assembly language
or machine code.

11.1.1 Can't touch this


https://isaaccs.org/eq/sys_proglang_08

A program written in a low-level language is described as non-portable.


▶ What does that mean?

⃝ The program cannot be saved to a disc


⃝ The program can only run on one machine
⃝ The program can only run on the processor type it was written for
⃝ The program cannot be copied

11.1.2 Find the hexadecimal


https://isaaccs.org/eq/sys_proglang_09

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

11.1.3 Low-level characteristic


https://isaaccs.org/eq/sys_proglang_11

▶ Which one of the following is a characteristic of low-level languages?

⃝ Low-level languages are always written in binary sequences.


⃝ Addressing modes are used to determine how to interpret the operand.
⃝ Low-level languages are portable across different processor types.
⃝ Well known low-level languages include C#, Python and Java.

11.1.4 Types of operands


https://isaaccs.org/eq/sys_proglang_10

▶ What can an operand represent?

⃝ Data
⃝ Data or a memory location
⃝ Data and a memory location
⃝ Memory location

11.1.5 What will the output be?


https://isaaccs.org/eq/sys_proglang_05_ocr

▶ Below is a program in assembly language. What will the output be after


the three values 15, 30, 25 are entered as input data?
1 INP
2 STA first
3 INP
4 ADD first
5 OUT
6 INP
7 SUB first
8 OUT
9 HLT
10 first DAT 0

The output will show and then


11. HIGH- AND LOW-LEVEL LANGUAGES 65

11.3.1 Bits for addressing mode


https://isaaccs.org/eq/sys_proglang_02

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?

11.3.2 Drawbacks of assembly languages


https://isaaccs.org/eq/sys_proglang_03

▶ Which of these are disadvantages of assembly languages compared to


high-level languages? Tick all that apply.

□ Translated programs are not portable between computers with differ-


ent architectures

□ It takes a lot of lines of code to write complex programs

□ The programmer cannot add comments to their code

□ There is no way to implement selection or iteration statements

11.3.3 High-level advantages


https://isaaccs.org/eq/sys_proglang_06

▶ Which of these is not an advantage of a high-level language compared to


a low-level language?

⃝ They are suited to particular problems

⃝ They make it possible to fully optimise coded solutions

⃝ They are easier to write programs with

⃝ They are easier for humans to understand


66 11. HIGH- AND LOW-LEVEL LANGUAGES

11.3.4 Operand with direct addressing


https://isaaccs.org/eq/sys_proglang_04

The following diagram shows the format of a machine code instruction:

Basic Operation Addressing mode Operand


0 0 1 1 0 0 1 0 0 1
ADD 010012 = 910

▶ How many different memory locations can a programmer access using


direct addressing?

11.3.5 Assemble the output


https://isaaccs.org/eq/sys_proglang_12

▶ Karishma has written a program in assembly language and has given it to


her classmates to try out. Trace the program and work out what the final
value of R2 will be at the end of the program.
It may be useful to write down the values of R0, R1 and R2 whilst tracing the
program.
1 start LDA R0
2 BRZ end
3 SUB R1
4 STA R0
5 LDA R2
6 ADD R0
7 STA R2
8 BRA start
9 end LDA R2
10 OUT
11 HLT
12
13 R0 DAT 8
14 R1 DAT 2
15 R2 DAT 10

Answer:
11. HIGH- AND LOW-LEVEL LANGUAGES 67

11.3.6 It's a jumble


https://isaaccs.org/eq/sys_proglang_01_ocr

Here is a program written in a high-level language:


1 x = 10
2 while x > 0
3 x = x-1
4 end while

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.

12.1.1 Stages of compilation


https://isaaccs.org/eq/sys_trans_10

▶ 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

▶ Which of the following statements correctly describes what an interpreter


does?

⃝ 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

12.2.1 Create an AST


https://isaaccs.org/eq/sys_trans_07

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

12.2.2 Lexical analysis


https://isaaccs.org/eq/sys_trans_02

During lexical analysis, a compiler is tokenising the following lines of code:


1 user = (" mathematician ")
2 pi = 3.142
3 OUTPUT ("Pi = ", pi)

An list of tokens used in the process is:

• 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

12.2.3 Executable code


https://isaaccs.org/eq/sys_trans_03

There are many stages in the process of creating an executable file.


▶ Put the following stages into the correct order.

□ Object code
□ Compiler
□ Source code
□ Linker
□ Executable file

12.2.4 Object code characteristics


https://isaaccs.org/eq/sys_trans_09

▶ What is object code?

⃝ Code produced by an interpreter


⃝ Code produced when using the object-oriented programming paradigm
⃝ Another name for a program produced in a low-level language
⃝ Code produced by a compiler or assembler
13 Boolean logic
Computers are made up of digital circuits. Each component in a circuit has
an input voltage that can be evaluated as True or False, or 1 or 0. Boolean
logic is a way of describing the circuits inside a computer, and the same
concept can be represented by a logic circuit diagram, a truth table, or a
Boolean expression.
At a more advanced level, you will study more complex logic gates, although
all circuits can ultimately be derived from the combination of a small subset
of basic gates. Using a formal notation for describing the combination of
logical operations will allow you to apply standard rules to simplify complex
Boolean expressions. You will explore some standard circuits in detail, such
as a full adder, which allows arithmetic addition, and a D-type flip-flop
circuit, which is a very basic unit of memory.

13.1.1 Order!
https://isaaccs.org/eq/sys_bool_21

Boolean operators have an order of precedence which is taken into account


when an expression is evaluated. Some operators have equal precedence.
▶ The groups below contain sets of operators with equal precedence. Num-
ber the groups into order so that the group with the highest precedence is
1, and the group with the lowest precedence is 4.

□ BRACKETS
□ OR, NOR, XOR
□ NOT
□ AND, NAND

72
13. BOOLEAN LOGIC 73

13.1.2 The XOR gate (exclusive OR)


https://isaaccs.org/eq/gcse_bool_10

▶ The following symbol represents an XOR gate (also known as Exclusive


OR).

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

13.1.3 Truth table


https://isaaccs.org/eq/sys_bool_01

▶ 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

13.1.4 Truth tables


https://isaaccs.org/eq/sys_bool_02

▶ 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

13.1.5 It's a gate


https://isaaccs.org/eq/sys_bool_22

▶ 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

13.1.6 Choose a truth table


https://isaaccs.org/eq/gcse_bool_01

▶ 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

13.1.7 Which gate is it?


https://isaaccs.org/eq/gcse_bool_08

▶ Which logic gate does the truth table below represent?


⃝ NOR
INPUT INPUT OUTPUT
0 0 1 ⃝ NOT
0 1 0
1 0 0 ⃝ NAND
1 1 0
⃝ XOR
78 13. BOOLEAN LOGIC

13.3.1 Four NANDies


https://isaaccs.org/eq/sys_bool_20

▶ 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

13.3.2 What am I doing (1)?


https://isaaccs.org/eq/sys_bool_23

Boolean expressions can be manipulated using basic Boolean identities and


laws. The following expressions are equivalent, which means that they im-
plement that same Boolean logic:
(X ∨ Y ) ∧ (Y ∨ R) ∧ (X ∧ Y ) =
(X ∨ Y ) ∧ (X ∧ Y ) ∧ (Y ∨ R)
▶ What is the name of the law that has been applied?

⃝ Associative

⃝ Distribution

⃝ Commutative

⃝ Absorption
13. BOOLEAN LOGIC 79

13.3.3 What am I doing (2)?


https://isaaccs.org/eq/sys_bool_24

Boolean expressions can be manipulated using basic Boolean identities and


laws. The following expressions are equivalent, which means that they im-
plement that same Boolean logic: A ∧ (B ∧ ¬C) = (A ∧ B) ∧ ¬C
▶ What is the name of the law that has been applied?

⃝ Distribution
⃝ Absorption
⃝ Commutative
⃝ Associative

13.3.4 What am I doing (3)?


https://isaaccs.org/eq/sys_bool_25

Boolean expressions can be manipulated using basic Boolean identities and


laws. The following expressions are equivalent, which means that they im-
plement that same Boolean logic: (A ∧ B) ∨ ((A ∧ B) ∧ (B ∨ C)) = A ∧ B
▶ What is the name of the law that has been applied?

⃝ Distribution
⃝ Associative
⃝ Absorption
⃝ Commutative

13.3.5 What am I doing (4)?


https://isaaccs.org/eq/sys_bool_26

Boolean expressions can be manipulated using basic Boolean identities and


laws. The following expressions are equivalent, which means that they im-
plement that same Boolean logic: (A ∧ B) ∨ (¬A ∧ B) = B ∨ (A ∧ ¬A)
▶ What is the name of the law that has been applied?

⃝ Associative
⃝ Absorption
⃝ Commutative
⃝ Distribution
80 13. BOOLEAN LOGIC

13.3.6 What am I doing (5)?


https://isaaccs.org/eq/sys_bool_27

Boolean expressions can be manipulated using basic Boolean identities and


laws. The following expressions are equivalent, which means that they im-
plement that same Boolean logic:
(x ∨ y) ∧ (x ∨ ¬y) = (x ∧ x) ∨ (x ∧ ¬y) ∨ (y ∧ x) ∨ (y ∧ ¬y)
▶ What is the name of the law that has been applied?

⃝ Distribution
⃝ Commutative
⃝ Associative
⃝ Absorption

13.3.7 Interpret a truth table


https://isaaccs.org/eq/gcse_bool_05_v2

▶ Select the correct Boolean expression for the given truth table.

INPUTS OUTPUT ⃝ Q = NOT(A AND B)


A B Q
0 0 1 ⃝ Q = (NOT A) OR B
0 1 1 ⃝ Q = A AND (NOT B)
1 0 1
1 1 0 ⃝ Q = NOT (A OR B)

13.3.8 De Morgan's laws (1)


https://isaaccs.org/eq/sys_bool_28

Some Boolean expressions can be manipulated using De Morgan’s laws. The


expression below can be tackled in this way.
¬(¬A ∨ ¬(B ∧ A))
▶ Which of the following options shows a correct application of De Morgan’s
laws?
⃝ A ∧ ¬B ∧ ¬A
⃝ A∧B∧A
⃝ A∧B∨A
⃝ ¬A ∨ ¬(B ∧ A)
13. BOOLEAN LOGIC 81

13.3.9 De Morgan's laws (2)


https://isaaccs.org/eq/sys_bool_29

Some Boolean expressions can be manipulated using De Morgan’s laws. The


expression below can be tackled in this way: ¬(¬B ∧ ¬(¬B ∧ A))
▶ Which of the following options shows a correct application of De Morgan’s
laws?

⃝ ¬B ∧ A ∨ B
⃝ ¬B ∨ A ∨ B
⃝ ¬B ∨ A ∧ B
⃝ B∧A∨B

13.3.10 Find the output


https://isaaccs.org/eq/gcse_bool_02
▶ What is the output (D) of the circuit below when all its inputs (A, B, C)
are True?

A B C D
1 1 1

Output:

13.3.11 Is it true?
https://isaaccs.org/eq/sys_bool_34

Boolean expressions can be manipulated using basic Boolean identities and


laws. A Boolean identity is a statement of equivalence where the expression
on the left of the equals sign has the same logic as the expression on the
right.
▶ Which of the following identities is not True?

⃝ A ∧ ¬A = 0
⃝ A ∧ ¬A = 1
⃝ A ∨ ¬A = 1
⃝ A∨0 = A
82 13. BOOLEAN LOGIC

13.3.12 Choose a logic circuit diagram


https://isaaccs.org/eq/gcse_bool_03

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

13.4.1 Lots of gates


https://isaaccs.org/eq/sys_bool_04

▶ Construct the correct Boolean expression for this circuit diagram:

13.4.2 Simplify the expression 1


https://isaaccs.org/eq/sys_bool_05

Simplify this Boolean expression:


(A ∨ B) ∧ (B ∨ B) ∧ (B ∨ A)
▶ The expression simplifies to:

⃝ True (1)
⃝ A
⃝ False (0)
⃝ B

13.4.3 Simplify the expression 2


https://isaaccs.org/eq/sys_bool_06

Using the laws of Boolean algebra, simplify this Boolean expression:


B ∧ (A ∨ A) ∨ B ∧ ¬A
▶ The expression simplifies to:

⃝ A
⃝ False (0)
⃝ True (1)
⃝ B
84 13. BOOLEAN LOGIC

13.4.4 Simplify the expression 3


https://isaaccs.org/eq/sys_bool_07

Using the laws of Boolean algebra, simplify this Boolean expression:


¬(¬(A ∧ B)) ∨ A ∨ B ∨ C
▶ The expression simplifies to:

⃝ A∨B∨C
⃝ ¬C
⃝ (A ∧ B) ∨ C
⃝ False (0)

13.4.5 Simplify the expression 4


https://isaaccs.org/eq/sys_bool_08

Using the laws of Boolean algebra, simplify this Boolean expression:


¬(A ∨ ¬B) ∧ (¬¬A ∧ C) ∧ ¬(C ∧ A)
▶ What does the expression simplify to?

⃝ ¬A ∧ B ∨ C
⃝ False (0)
⃝ A∧B∨C
⃝ A ∧ B ∨ ¬C

13.4.6 Simplify it (1)


https://isaaccs.org/eq/sys_bool_30

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

13.4.7 Simplify it (2)


https://isaaccs.org/eq/sys_bool_31

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

13.4.8 Simplify it (3)


https://isaaccs.org/eq/sys_bool_32

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

13.4.9 Simplify it (4)


https://isaaccs.org/eq/sys_bool_33

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

13.4.10 Simplify the Karnaugh map 1


https://isaaccs.org/eq/sys_bool_09

The truth table for a Boolean expression has been put into the Karnaugh
map below.

▶ Select the simplest Boolean expression to represent the given Karnaugh


map

⃝ A∨B
⃝ A∧B
⃝ A⊻B
⃝ ¬A ∨ ¬B
13. BOOLEAN LOGIC 87

13.4.11 Simplify the Karnaugh map 2


https://isaaccs.org/eq/sys_bool_10

The truth table for a Boolean expression has been put into the Karnaugh
map below.

▶ Select the simplest Boolean expression to represent the given Karnaugh


map

⃝ (B ∧ ¬D) ∨ (A ∧ ¬B)
⃝ A ∨ (B ∧ ¬D)
⃝ (¬C ∧ ¬D ∧ B) ∨ (A ∧ ¬B) ∨ (C ∧ ¬D ∧ B)
⃝ (A ∧ ¬B) ∨ (B ∧ C)
88 13. BOOLEAN LOGIC

13.4.12 Simplify the Karnaugh map 3


https://isaaccs.org/eq/sys_bool_41

A Karnaugh map has been drawn as shown below.

▶ Select the simplest Boolean expression to represent the given Karnaugh


map.

⃝ B ∨ (A ∧ ¬C)
⃝ B ∨ ¬C
⃝ B ∨ (A ∧ ¬B)
⃝ B ∨ (A ∧ ¬B ∧ ¬C)
13. BOOLEAN LOGIC 89

13.4.13 Simplify the Karnaugh map 4


https://isaaccs.org/eq/sys_bool_42

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

13.4.14 Simplify the Karnaugh map 5


https://isaaccs.org/eq/sys_bool_43

A Karnaugh map has been drawn as shown below and the two blocks of 1s
have been correctly identified.

▶ Which of the following options shows the correctly simplified Boolean


expression for the map?

⃝ (A ∧ B) ∨ (C ∧ D)
⃝ (¬A ∧ ¬B) ∨ (¬C ∧ ¬D)
⃝ (¬A ∧ ¬B) ∧ (¬C ∧ ¬D)
⃝ ¬A ∨ ¬B ∨ ¬C ∨ ¬D
13. BOOLEAN LOGIC 91

13.4.15 Simplify the Karnaugh map 6


https://isaaccs.org/eq/sys_bool_46

A Karnaugh map has been drawn as shown below.

▶ Which of the following options shows the correctly simplified Boolean


expression for the map?

⃝ (A ∧ ¬B ∧ D) ∨ (¬A ∧ ¬B ∧ D)
⃝ ¬B ∨ D
⃝ ¬B ∧ D
⃝ A ∧ ¬B ∧ D
92 13. BOOLEAN LOGIC

13.4.16 This is alarming!


https://isaaccs.org/eq/sys_bool_11

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.

• The evening time (E) is set to True when it is 6.00pm.


• The person detector (P ) is set to True when someone is in the building.
• The manual switch (M ) is set to True when the alarm is turned on
manually.

▶ 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

13.4.17 The lender


https://isaaccs.org/eq/sys_bool_13

A library system needs to indicate if a user is allowed to borrow a book. The


decision is based on several criteria.

• 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 following inputs represent the listed conditions:


1 D - TRUE if there is an unpaid fine on the account
2
3 M - TRUE if the account has 6 or more books on loan
4
5 S - TRUE if the account belongs to an A level student
6
7 W - TRUE if the book was requested more than 4 weeks ago

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

13.4.18 Boolean expression


https://isaaccs.org/eq/sys_bool_14

A student is asked to answer a question regarding Boolean expressions. To


complete the question, the student should know that a Boolean expression
always produces a Boolean value. The expression is made up of a combina-
tion of Boolean variables and logical operators.
The question provides a circuit diagram as shown below.

Figure 13–1: The given circuit diagram

The student has also been given Boolean expressions for some parts of the
circuit:

Boolean expressions for individual gates


G = ¬(A ∨ B)
E = ¬A
D =B∨C
F =E∧D

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

⃝ Q = (¬A ∧ (B ∨ C)) ∨ ¬(A ∨ B)


13. BOOLEAN LOGIC 95

13.4.19 More than one way!


https://isaaccs.org/eq/sys_bool_16

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

13.4.20 Express it correctly


https://isaaccs.org/eq/sys_bool_15

A Boolean expression can often be expressed using different logic, often in


much simpler form.
▶ Three of the following Boolean expressions are correct (in that the left
part has the same logic as the right part). Select the three correct options.

□ A∨1=1

□ A ∧ (A ∨ B) = A

□ A ∧ ¬A = 1

□ A ∨ B = ¬¬A ∧ ¬B

□ A ∧ (A ∨ B) = B

□ A∧1=1

13.4.21 A full adder


https://isaaccs.org/eq/sys_bool_17

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).

Input Input Input Output Output


A B C D E F G H
0 0 0 0 0 0 0 0

0 0 1 0 0 0 0 0
0 1 1 0 1 0 1 0
1 1 1 0 1 0 1 1

Input Input Input Output Output


A B C D E F G H
0 0 0 0 0 0 0 0

0 0 1 1 0 0 0 1
0 1 1 0 1 0 1 0
1 1 1 0 1 0 1 1

Input Input Input Output Output


A B C D E F G H
0 0 1 0 0 0 0 0

0 0 0 1 0 0 0 1
0 1 0 0 1 0 1 0
1 1 0 0 1 0 1 1

Input Input Input Output Output


A B C D E F G H
0 0 0 0 0 0 0 1

0 0 1 1 0 0 0 0
0 1 1 0 1 0 1 1
1 1 1 0 1 0 1 0
98 13. BOOLEAN LOGIC

13.4.22 The right steps


https://isaaccs.org/eq/sys_bool_18

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

• application of De Morgan’s law

• distributive law

• use of identity X ∧ X = X [twice]

• use of identities X ∧ ¬X = 0 and X ∨ 0 = X

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

□ use of identities X AND NOT X = 0 and X OR 0 = X

□ application of De ’Morgans law

□ distributive law

□ use of identity X OR X = X

□ use of identity X AND X = X [twice]


13. BOOLEAN LOGIC 99

13.4.23 De Morgan's 1st Law


https://isaaccs.org/eq/sys_bool_19

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

13.4.24 Tell the truth!


https://isaaccs.org/eq/sys_bool_35

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

13.4.25 Light it up (part 1)


https://isaaccs.org/eq/sys_bool_36

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.

• The switch (S) returns 1 when the switch is set on

• The light sensor (L) returns 1 when it is light outside

• The rain sensor (R) returns 1 when it is raining

▶ Complete the Boolean expression that will allow the garden lights (G) to
come on.
13. BOOLEAN LOGIC 101

13.4.26 Light it up (part 2)


https://isaaccs.org/eq/sys_bool_37

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.

• The switch (S) returns 1 when the switch is set on

• The light sensor (L) returns 1 when it is light outside

• The rain sensor (R) returns 1 when 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

13.4.27 Naughty or nice?


https://isaaccs.org/eq/sys_bool_winter_11

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.

Label Variable Description


A Belief Believes in Santa Claus
B Helpful Often helps others
C Traditional Leaves carrots and mince pies every year
D Generous Brings snacks and treats to share with everyone
E Selfish Does not ever share their possessions
F Dishonest Takes credit for other people’s work

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 )

▶ Simplify this equation as far as possible to help Santa out!


13. BOOLEAN LOGIC 103

13.4.28 Find truth table values


https://isaaccs.org/eq/gcse_bool_04

▶ 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

13.4.29 Wire this up!


https://isaaccs.org/eq/gcse_bool_07

▶ Which of the circuits below represents the following Boolean expression?


=(A�B)�(C+B)

A B

C D

Answer:

13.4.30 Express it well


https://isaaccs.org/eq/sys_bool_38

Consider the truth table below.

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)

13.4.31 One and one


https://isaaccs.org/eq/sys_bool_40

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

13.4.32 Are the lights on?


https://isaaccs.org/eq/sys_bool_winter_02

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!

• The light sensor (L) is set to TRUE when it is dark.


• Robbie’s phone (R) is set to TRUE when it is away from home.
• Alex’s phone (A) is set to TRUE when it is away from home.

▶ 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.

14.1.1 Network forensics


https://isaaccs.org/eq/gcse_net_19

▶ Which one of the statements below correctly describes network forensics?

⃝ Network forensics is a piece of hardware or software that monitors


incoming and outgoing traffic to and from the network.

⃝ Network forensics is when data sent over a network is encrypted, to


prevent brute-force attacks.

⃝ Network forensics is used to identify where a hack has come from, how
the hack was achieved, and what data might have been stolen.

⃝ Network forensics is often referred to as ethical hacking. Ethical hack-


ers attempt to access a network to identify any potential security
breaches.

107
108 14. MALICIOUS CODE

14.1.2 Defence Against the Dark Arts


https://isaaccs.org/eq/net_sec_05

Malware refers to malicious software, and describes programs designed


to cause damage to computer systems, corrupt or change files, steal data,
or cause disruption to services. There are several types, including viruses,
worms, and trojans.
▶ Select all of the statements about malware that are true.

□ A virus can only be caught by clicking on a malicious link or attach-


ment.

□ A worm cannot open a back door to enable remote control of a com-


puter.

□ Trojans look like legitimate software, such as free games, emojis, or


utility programs, but they contain malware that installs itself at the
same time.

□ Antivirus software can only remove viruses, not worms or trojans.

□ Worms can spread autonomously, for example, by emailing themselves


to everyone in your address book.

14.1.3 DDoS
https://isaaccs.org/eq/net_sec_06

The aim of some types of malware is to cause a distributed denial-of-service


attack.
▶ What does a distributed denial-of-service attack do?

⃝ A worm spreads around a network, consuming all resources until the


system is disabled.

⃝ Floods a website with traffic from multiple infected computers until


the website is unable to function properly.

⃝ Shares your private encryption key on a platform called a ‘public key


infrastructure’ so others can see it.

⃝ Tries every possible password in order to break into a website.


14. MALICIOUS CODE 109

14.1.4 Code reviews


https://isaaccs.org/eq/net_sec_07

Malware exploits vulnerabilities in code. These can be found and rectified


by a code review.
▶ Which of these best describes a code review?

⃝ 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.

14.3.1 Avoiding malware


https://isaaccs.org/eq/cyb_mal_01

▶ Select four options that describe appropriate measures to minimise mal-


ware risks.

□ Use of firewall

□ Receive and share files only with users on a local area network

□ Maintain and update anti-virus software

□ Use biometric authentication to log in to your computer

□ Choose secure passwords

□ Use defragmentation software often

□ Only open emails without attached files

□ Perform regular computer scans


110 14. MALICIOUS CODE

14.3.2 Booking all seats


https://isaaccs.org/eq/cyb_mal_02

▶ A student uses malicious software to bombard a server with thousands of


‘legitimate’ bookings for the gym, requesting to book all seats at the same
time, so no one else would be able to book it. Select the option that contains
the type of attack caused by the student.

⃝ Worm attack
⃝ Trojan attack
⃝ Social engineering attack
⃝ Denial-of-service attack

14.3.3 Security threats


https://isaaccs.org/eq/gcse_net_09

A brute-force attack aims to find the credentials used to authenticate users


on a network.
▶ Which method would be most suitable to recommend to prevent a brute-
force attack?

⃝ Encryption
⃝ Strict user access levels
⃝ Strong passwords
⃝ A firewall

14.3.4 Eavesdropping
https://isaaccs.org/eq/gcse_net_04

▶ Eavesdroppers ‘listen in’ to transmitted data on a network or between


networks. Which is the most effective method of preventing them stealing
data?

⃝ Encryption
⃝ Firewall
⃝ Passwords
⃝ Anti-malware software
14. MALICIOUS CODE 111

14.3.5 It's all too much


https://isaaccs.org/eq/net_sec_08

Quality of code is essential to avoiding vulnerabilities that can be exploited


by malware. One code quality issue is a type of memory fault, where a data
structure is not large enough for certain values of data to be passed into
it. Malware can exploit this by making data spill out of the field and into
nearby memory, overwriting program instructions.
▶ What is the name for this type of error?

14.4.1 SQL injection


https://isaaccs.org/eq/cyb_sec_06

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.

15.1.1 Accepted Passwords


https://isaaccs.org/eq/prog_concepts_11

A website uses the following rules to determine if a password can be used.


The password must be:
At least 8 characters long AND contain 3 out of the following 4 character
types:

• A lowercase letter
• An uppercase letter
• A number
• A symbol

OR

• At least 16 characters long


▶ Which of these passwords can be used on this site?

□ saveEarth89
□ @1234/221B+24601!
□ fRiEnDenter
□ horsebatterycomputerstaple
□ pAsw0rd
□ aA1,aA1,

112
15. NETWORK SECURITY 113

15.1.2 Security of network components


https://isaaccs.org/eq/net_network_06

WiFi components introduce a security risk to computers that use them in


that the data can be intercepted and read.
▶ Which method should be used by wireless devices to ensure communication
is secure?

15.1.3 Limiting devices on a network


https://isaaccs.org/eq/net_network_12

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

15.1.5 Don’t do that


https://isaaccs.org/eq/cyb_sec_03

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.

□ An organisation’s AUP can be updated faster than national legislation.

□ All of these statements are correct reasons

15.3.1 Filter them out


https://isaaccs.org/eq/cyb_sec_02

A MAC address is a unique identifier given to a network interface card.


MAC address filtering is a technique that is sometimes used to help secure
a network. However, this approach to network security has limitations.
▶ Which of the following statements is false?

⃝ MAC addresses are irrelevant if a computer has an IP address.

⃝ MAC addresses can be obtained by intercepting network packets.

⃝ A computer can have multiple MAC addresses.

⃝ MAC addresses can be spoofed.


15. NETWORK SECURITY 115

15.3.2 Legal responsibility


https://isaaccs.org/eq/cyb_sec_04

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?

⃝ Have access level


⃝ Back up data daily
⃝ Encrypt data
⃝ Install a firewall
16 Managing security threats
Many people use computer systems on a daily basis, for everyday tasks such
as buying new clothes, messaging our friends and family, or collaborating
with colleagues at work. It is important to both companies and individuals
that their computer systems are kept secure, and that the people using them
are authorised to do so. A variety of methods can be used to check that a
computer system is only being accessed and used in authorised ways. These
methods include firewalls, encryption, biometric security, and two-
factor authentication.

16.2.1 Enemy of the state


https://isaaccs.org/eq/net_sec_02

▶ 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.

17.1.1 Why hex?


https://isaaccs.org/eq/data_numbases_14

▶ 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 take up less storage in main memory.

⃝ They are easier for humans to work with than long binary numbers.

⃝ They are the only way that colour codes can be represented.

⃝ They allow larger numbers to be represented.

117
118 17. REPRESENTATION OF NUMBERS

17.1.2 The maximum denary number


https://isaaccs.org/eq/data_numbases_37

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?

17.1.3 Adding two binary numbers


https://isaaccs.org/eq/gcse_data_29

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.4 From denary to binary


https://isaaccs.org/eq/data_numbases_38

▶ Sometimes it is necessary to convert between number bases. If you convert


the denary (base-10) number 156 to an 8-bit binary (base-2) number, what
would the result be? Write your answer in binary format.

17.1.5 From denary to hex


https://isaaccs.org/eq/data_numbases_39

▶ Convert the denary (base-10) number 212 to a hexadecimal (base-16)


number. Write your answer in hexadecimal format.
120 17. REPRESENTATION OF NUMBERS

17.1.6 From hex to denary


https://isaaccs.org/eq/data_numbases_40

▶ Convert the hexadecimal (base-16) number 2F to a denary (base-10)


number. Write your answer in hexadecimal format.

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.

17.1.8 Denary to binary (1)


https://isaaccs.org/eq/data_numbases_16

▶ Convert the value +2810 to an 8-bit two’s complement binary number.

⃝ 11100100

⃝ 011100

⃝ 00011100

⃝ 11100000
17. REPRESENTATION OF NUMBERS 121

17.1.9 Denary to binary (2)


https://isaaccs.org/eq/data_numbases_17

▶ Convert the value −4910 to an 8-bit two’s complement binary number.

17.1.10 Binary to denary (1)


https://isaaccs.org/eq/data_numbases_18

▶ Convert the value 001010112 to a denary (base 10) number. The binary
value is encoded as an 8-bit two’s complement number.

17.1.11 Binary to denary (2)


https://isaaccs.org/eq/data_numbases_19

▶ 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

17.1.12 What's the range?


https://isaaccs.org/eq/data_numbases_11

▶ Signed integers can be stored in two’s complement form. What is the


range of values that can be stored using 8 bits in two’s complement?

⃝ +256 to -256
⃝ +128 to -128
⃝ +127 to -128
⃝ +255 to -256

17.1.13 Put the numbers into order (1)


https://isaaccs.org/eq/data_numbases_03

The integers shown below are represented using two’s complement.


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.
▶ Put the numbers into order from smallest to largest.

□ 01111111

□ 01001110

□ 10000000

□ 11001110

□ 11111111
17. REPRESENTATION OF NUMBERS 123

17.1.14 Putting base-two and base-two together


https://isaaccs.org/eq/gcse_data_07

▶ What is the result of the binary addition?

0 1 1 0 1 1 1 1
+ 0 0 1 1 1 0 0 1

17.1.15 What colour is this?


https://isaaccs.org/eq/gcse_data_03

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

17.1.17 Warm colours


https://isaaccs.org/eq/gcse_data_12

Colours on a web page are usually represented in binary by 24-bit codes,


i.e. combining 8 bits for a shade of red (R), 8 bits for a shade of green (G),
and 8 bits for a shade of blue (B). These long sequences of binary digits
can be hard to read, so lookup tables are created which use human-readable
descriptions of the colours to index their RGB values, making them more
user-friendly.
By way of example, the lookup table below shows four warm colour codes in
RGB, 24-bit code binary and hexadecimal. Warm colours generally contain
a significant amount of red, mimicking sunlight.
Red is defined by its RGB value of (255,0,0) and its 24-bit binary code value
is therefore represented in binary as 1111111100000000000000002
In hexadecimal, the same colour can be represented by only 6 hexadecimal
digits so the colour red is depicted as FF000016
Three of the hexadecimal representations are missing from the warm colours
table below.
▶ Circle the correct list (Red has already been given, as above) of colours
in hexadecimal, from the options below, to complete the Hexadecimal table
column.

Colour Name RGB Binary Hexadecimal


Red (255,0,0) 1111111100000000000000002 FF000016
Deep Pink (255,20,147) 1111111100010100100100112 ?
Moccasin (255,228,181) 1111111111100100101101012 ?
Coral (255,127,80) 1111111101111111010100002 ?

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

17.1.18 Count the ones


https://isaaccs.org/eq/gcse_data_09

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

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the 8-bit unsigned binary integer 01010101 to a denary number.

17.1.20 Convert it 2
https://isaaccs.org/eq/gcse_data_21

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the 8-bit unsigned binary integer 10010011 to a denary number.
126 17. REPRESENTATION OF NUMBERS

17.1.21 Convert it 3
https://isaaccs.org/eq/gcse_data_22

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the 8-bit unsigned binary integer 00110000 to a denary number.

17.1.22 Convert it 4
https://isaaccs.org/eq/gcse_data_23

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the denary number 77 to binary.

17.1.23 Convert it 5
https://isaaccs.org/eq/gcse_data_24

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the denary number 100 to binary.
17. REPRESENTATION OF NUMBERS 127

17.1.24 Convert it 6
https://isaaccs.org/eq/gcse_data_25

An unsigned binary integer can be used to represent a positive whole number.


▶ Convert the denary number 129 to binary.

17.1.25 Total score


https://isaaccs.org/eq/gcse_data_15

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 =

▶ What is the total of Kalpak’s test marks in binary?

⃝ 01100111

⃝ 01101001

⃝ 01100101

⃝ 00100101

▶ What is the total of Kalpak’s test marks in denary?


128 17. REPRESENTATION OF NUMBERS

17.1.26 Bonus time


https://isaaccs.org/eq/gcse_data_16

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 =

▶ Pick the correct answer from the options provided.

⃝ 111000102
⃝ 111001002
⃝ 111100102
⃝ 111101002

▶ What is the total of Agneta’s bonus, in denary?

17.1.27 Which one is the smallest?


https://isaaccs.org/eq/data_numbases_04_v2

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

17.3.1 Binary addition


https://isaaccs.org/eq/data_numbases_36

▶ What is the result of the addition of 110101112 + 111100002 in denary?

⃝ 1C7

⃝ 455

⃝ 111000111

⃝ 199

17.3.2 Which one is the largest?


https://isaaccs.org/eq/data_numbases_01_v2

▶ Select the largest number from the options below.

Number base Value



Decimal 670

Number base Value



Hexadecimal 5C2

Number base Value



Binary 1001000100

Number base Value



Hexadecimal 1B9
130 17. REPRESENTATION OF NUMBERS

17.3.3 Take away


https://isaaccs.org/eq/data_numbases_20

▶ What is the result of subtracting 000101002 from 010101012 ? Both binary


values are encoded as 8-bit two’s complement numbers. Express your answer
as an 8-bit two’s complement binary number.

17.3.4 That's average


https://isaaccs.org/eq/gcse_data_13

To calculate the arithmetic mean (average) value of a given set of numbers


you calculate the sum of values and divide it by the number of values. For
example: (10 + 12 + 14 + 16) / 4 = 13
The expression used above is written in denary, or base 10. The following
expression has been written using numbers from different number bases, the
subscript denotes the number base used. Convert each number to denary
and then calculate the mean:
(100101102 + F516 + 7D16 + 101101002 ) / 4 = ?
▶ Give the answer in denary.
17. REPRESENTATION OF NUMBERS 131

17.3.5 Which square are you


https://isaaccs.org/eq/gcse_data_11

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:

Number base Value



Hexadecimal E1

Number base Value



Hexadecimal A9

Number base Value



Binary 11000100

Number base Value



Binary 100100001

17.3.6 Left or right?


https://isaaccs.org/eq/gcse_data_08

▶ 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

17.3.7 ASCII study time


https://isaaccs.org/eq/gcse_data_17

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).

• Uppercase letters A-Z are represented by the ASCII character codes


6510 to 9010
• Lowercase letters a-z are represented by the ASCII character codes:
9710 to 12210

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

Word 2 = 10000112 11011112 10910 11210 11710 11101002 11001012 11410

Word 3 = 8310 9910 11010012 10110 11011102 9910 11001012


17. REPRESENTATION OF NUMBERS 133

17.4.1 Fixed point binary to denary (1)


https://isaaccs.org/eq/data_numbases_21

▶ 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 )

⃝ 0.900390625 (or 461


512 )

⃝ 7.203125 (or 7 13
64 or
461
64 )

⃝ 461 (or 461


1 )

17.4.2 Fixed point binary to denary (2)


https://isaaccs.org/eq/data_numbases_22

▶ Convert the binary number 0011010101012 to denary. It is represented


in unsigned fixed point form with 6 places before the binary point and 6
places after the binary point. Write your answer as an unsigned decimal
number (e.g.3.75).

17.4.3 Fixed point binary to denary (3)


https://isaaccs.org/eq/data_numbases_23

▶ 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.

⃝ −12.4375 (or −12 16


7
or − 199
16 )

⃝ −51.5625 (or −51 16


9
or − 825
16 )

⃝ −13.5625 (or −13 16


9
or − 217
16 )

⃝ −3.109375 (or −3 64
7
or − 199
64 )
134 17. REPRESENTATION OF NUMBERS

17.4.4 Fixed point binary to denary (4)


https://isaaccs.org/eq/data_numbases_24

▶ Convert the binary number 101011101102 to denary. It is represented


in two’s complement fixed point form with 6 places before the binary
point and 5 places after the binary point. Write your answer as a signed
decimal number (e.g. +3.75).

17.4.5 Denary to fixed point binary (1)


https://isaaccs.org/eq/data_numbases_25

▶ 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

17.4.6 Denary to fixed point binary (2)


https://isaaccs.org/eq/data_numbases_26

▶ Convert the denary number 2 32


9 73
(or 32 or 2.28125 as a decimal) to binary,
encoding the number as an unsigned fixed point number with 4 places
before the binary point and 5 places after the binary point. Write your
answer as a 9-bit binary number without a binary point (e.g. 111110000).
17. REPRESENTATION OF NUMBERS 135

17.4.7 Denary to fixed point binary (3)


https://isaaccs.org/eq/data_numbases_27

▶ 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

17.4.8 Denary to fixed point binary (4)


https://isaaccs.org/eq/data_numbases_28

▶ Convert the denary number −11 83 (or 91


8 or −11.375 as a decimal) to bin-
ary, encoding the number as an fixed point two’s complement number
with 5 places before the binary point and 4 places after the binary point.
Write your answer as a 9-bit binary number without a binary point (e.g.
111110000),

17.4.9 Denary to fixed point binary (5)


https://isaaccs.org/eq/data_numbases_29

▶ Convert the denary number − 64 3


(or −0.046875 as a decimal) to bin-
ary, encoding the number as an fixed point two’s complement number
with 4 places before the binary point and 6 places after the binary point.
Write your answer as a 10-bit binary number without a binary point (e.g.
1111100001).
136 17. REPRESENTATION OF NUMBERS

17.4.10 Denary to fixed point binary (6)


https://isaaccs.org/eq/data_numbases_30

▶ Convert the denary number − 64 6


(or −0.09375 as a decimal) to binary, en-
coding the number as an fixed point two’s complement number with 4
places before the binary point and 6 places after the binary point. Write your
answer as a 10-bit binary number without a binary point (e.g. 1111100001).

17.4.11 Floating point binary to denary (1)


https://isaaccs.org/eq/data_numbases_31

The binary number shown below is represented as a normalised floating


point number with an 8-bit mantissa and a 4-bit exponent. The mantissa
and exponent are both stored using two’s complement.

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.

17.4.12 Floating point binary to denary (2)


https://isaaccs.org/eq/data_numbases_32

The binary number shown below is represented as a normalised floating


point number with an 8-bit mantissa and a 4-bit exponent. The mantissa
and exponent are both stored using two’s complement.

mantissa exponent
1 . 0 0 1 0 1 0 0 1 1 1 1
17. REPRESENTATION OF NUMBERS 137

▶ Which of the following options shows the correct denary representation of


the number?

⃝ −1.6875
⃝ +0.578125
⃝ −0.421875
⃝ −27, 648

17.4.13 Floating point binary to denary (3)


https://isaaccs.org/eq/data_numbases_33

The binary number shown below is represented as a normalised floating


point number with an 8-bit mantissa and a 4-bit exponent. The mantissa
and exponent are both stored using two’s complement.

mantissa exponent
0 . 1 0 1 0 0 0 0 1 0 1 1

▶ Convert the floating point number into denary.Write your answer as a


signed decimal number, e.g. +3.75.

17.4.14 Denary to floating point binary (1)


https://isaaccs.org/eq/data_numbases_34

▶ Convert the denary number + 16 5


(or +0.3125 as a decimal) to binary,
encoding the number as a normalised floating point number with an
8-bit mantissa and a 4-bit exponent. The mantissa and exponent use two’s
complement. Write your answer as a 12-bit binary number with the binary
point (e.g. 0.11100011101),
138 17. REPRESENTATION OF NUMBERS

17.4.15 Denary to floating point binary (2)


https://isaaccs.org/eq/data_numbases_35

The denary number − 64 9


(or −0.140625 as a decimal) has been converted
to binary, and is held as a normalised floating point number with an
8-bit mantissa and a 4-bit exponent. The mantissa and exponent use two’s
complement.
▶ Which of the following options shows the correct binary representation of
the number?

mantissa exponent

1.0111000 0010

mantissa exponent

1.0111000 1110

mantissa exponent

1.1101110 0000

mantissa exponent

0.1001000 1110

17.4.16 Flying home for the holidays


https://isaaccs.org/eq/data_numbases_winter_05

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

17.4.17 What's normal?


https://isaaccs.org/eq/data_numbases_13_v2

▶ 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

17.4.18 Convert to denary


https://isaaccs.org/eq/data_numbases_12

The binary number shown below is represented as a floating point number


with a 10-bit mantissa and a 4-bit exponent. The mantissa and exponent
are both stored using two’s complement.

mantissa exponent
1 . 0 0 0 0 1 0 1 0 0 0 1 0 1

▶ Convert the floating point number into denary.


140 17. REPRESENTATION OF NUMBERS

17.4.19 Convert into binary


https://isaaccs.org/eq/data_numbases_07_v2

▶ Select the correct binary number representation of the decimal number


-16.7510 .
The binary number representation used is normalised two’s complement
floating point, with 8 bits for the mantissa and 4 bits for the exponent.

mantissa exponent

1.0111101 0101

mantissa exponent

1.0111101 1011

mantissa exponent

101111.01 0000

mantissa exponent

110000.11 0000

17.4.20 Find the sum


https://isaaccs.org/eq/data_numbases_06_v2

▶ 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.

18.1.1 ASCII Representation


https://isaaccs.org/eq/data_rep_12

Each character in the English alphabet can be converted into a corresponding


ASCII numeric code. Numeric digits can also be represented in ASCII.
The codes for numeric digits, lowercase letters and uppercase letters run in
sequences, so if you know the ASCII code for the start of the sequence you
can calculate any other code. The numeric codes are converted to binary so
they can be stored and processed by computer systems.
The letter ‘A’ has the ASCII code 65, ‘a’ has the ASCII code 97 and 0 has
the ASCII code 48.
▶ How would the string Dg6 be represented in binary if each character is
stored as a 7-bit ASCII code? Write your answer as a set of codes separated
by commas, e.g. 0101011, 1010101, 0110111

141
142 18. REPRESENTATION OF TEXT

18.3.1 ASCII count up


https://isaaccs.org/eq/gcse_data_01

▶ 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

18.3.2 Unicode variable-width encoding


https://isaaccs.org/eq/data_text_02

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

18.3.3 Never roll your own crypto


https://isaaccs.org/eq/prog_string_08

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 '

The message Divya sent to her friend looks like this:


109 101 101 116 32 97 116 32 49 48 44 32 98 114 105 110 103 32 99 104
111 99 111 108 97 116 101
Unfortunately, someone was able to decipher the message by writing a pro-
gram to convert each ASCII code back into a character.
▶ What was the message?

18.3.4 ASCII or Unicode?


https://isaaccs.org/eq/data_rep_01

▶ Select all the statements that are correct.

□ There is a Unicode character set that uses only 8 bits per character.

□ Unicode does not include character codes for ideograms.

□ ASCII is useful for representing characters from languages other than


English.

□ Unicode can be used to represent up to 256 different characters.

□ Standard ASCII uses 7 bits to represent each 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.

19.1.1 Extra colours


https://isaaccs.org/eq/gcse_data_10

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.

19.3.1 How many kilobytes?


https://isaaccs.org/eq/gcse_sys_09

▶ 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

19.3.2 A colourful problem


https://isaaccs.org/eq/gcse_data_27

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.

▶ How many pixels does the image have in total?

▶ To represent 9 different colours, what is the minimum colour depth needed?


Give your answer in bits.

▶ What is the total file size (excluding any metadata)? Give your answer
in bits.

▶ What is the total file size (excluding any metadata) in bytes?


146 19. REPRESENTATION OF IMAGES

19.3.3 How many bytes?


https://isaaccs.org/eq/gcse_data_02

▶ What is the minimum file size in bytes for a 16 x 32 bitmapped graphic


which uses 8 colours?

19.3.4 Too much data?


https://isaaccs.org/eq/gcse_data_28

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

□ Date and time

□ Flash
19. REPRESENTATION OF IMAGES 147

19.3.5 Minimum file size


https://isaaccs.org/eq/data_rep_11

Bitmap images are made up of a grid of pixels. A pixel represents the


smallest addressable part of a bitmap image and each pixel is represented by
a colour code. The number of bits allocated to the colour code is referred to
as colour depth. The higher the number of pixels within an image and the
greater the colour depth, the more space you need to store it.
▶ What is the correct way to calculate the minimum file size of a bitmap
image in bytes?

⃝ 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.

20.1.1 Should I MIDI it?


https://isaaccs.org/eq/data_sound_01

▶ Select the statement about MIDI that is correct:

⃝ Synthesised music is often produced using MIDI.

⃝ MIDI can be used to record analogue sound.

⃝ A MIDI file consists of the sound signal and a list of instructions.

⃝ You can record music using MIDI but you can’t synthesise music using
MIDI technology.

20.3.1 Giga for a gig


https://isaaccs.org/eq/gcse_data_06_v2

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

20.3.2 Double trouble


https://isaaccs.org/eq/gcse_data_19

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).

20.3.3 How many megabytes?


https://isaaccs.org/eq/gcse_sys_10

▶ 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.

21.1.1 It's no loss


https://isaaccs.org/eq/data_compr_07

▶ Why might a developer choose a lossy method for file compression?

⃝ The file contains data that has no commercial value.


⃝ The file contains data that has lots of repeated patterns.
⃝ The file contains data of which an approximation of the original is good
enough.
⃝ The file contains data that is made up of simple sequences of letters
and numbers.

21.1.2 Lossless dictionary


https://isaaccs.org/eq/data_compr_09

Dictionary-based compression methods are lossless.


▶ What is the correct definition of a lossless compression method?

⃝ A method where the decompressed file has an identical binary form to


the original uncompressed file
⃝ A method where data that is discarded during compression is re-
created by a sophisticated algorithm
⃝ A method where the user cannot tell the difference between the original
uncompressed file and the decompressed file
⃝ A method where the binary values of the original uncompressed file
and the decompressed files are different, but the decoded data appears
to be the same

150
21. COMPRESSION 151

21.1.3 A total loss


https://isaaccs.org/eq/data_compr_03

▶ Which of the following statements describe lossless compression methods?


Tick all that apply.

□ A method where blocks of pixels are replaced with a single value


□ A method where a run of binary codes is replaced by a single code and
the number of repetitions of the code in the run
□ A method where binary patterns are identified and replaced with codes,
and a dictionary of the codes is also stored
□ A method where information that is not useful to humans is discarded

21.3.1 A rose by any other name


https://isaaccs.org/eq/data_compr_01

The bitmap image below will be compressed using RLE.

Row 6 is compressed as B1, P7, B1, R4, C1, B1, W1


▶ How will row 11 be compressed?
152 21. COMPRESSION

21.3.2 Ill-suited
https://isaaccs.org/eq/data_compr_02

Figure 21–2: A shady corner

▶ Why is an image of a real-life subject not suitable for compression using


run length encoding (RLE)?

⃝ The image doesn’t have enough different colours.


⃝ The image is too large.
⃝ The image has too much detail.
⃝ The image is not a bitmap.
21. COMPRESSION 153

21.3.3 How much can I save?


https://isaaccs.org/eq/data_compr_04

The bitmap image shown uses a colour depth of 3 bits.


The image will be compressed using run length encoding (RLE). Assume
that a run is able to span multiple rows (for example, the initial run of
white pixels has a run size of 17) and that the repetitions are stored as an
8-bit binary number.
▶ Give an example of a binary code that could be used to represent the
colour pink.

▶ 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

21.3.4 It's grown!


https://isaaccs.org/eq/data_compr_08

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.

▶ Calculate the size of the original, uncompressed file in bits.


21. COMPRESSION 155

21.4.1 Flowers for Dorian


https://isaaccs.org/eq/data_compr_05

Consider the following passage of text from The Picture of Dorian Gray by
Oscar Wilde.

The artist is the creator of beautiful things. To reveal art and


conceal the artist is art’s aim. The critic is he who can translate
into another manner or a new material his impression of beautiful
things. The highest as the lowest form of criticism is a mode of
autobiography. Those who find ugly meanings in beautiful things
are corrupt without being charming. This is a fault. Those who
find beautiful meanings in beautiful things are the cultivated.
For these there is hope. They are the elect to whom beautiful
things mean only Beauty. There is no such thing as a moral or an
immoral book. Books are well written, or badly written. That
is all.

The passage is encoded in standard 16-bit Unicode and compressed using


a simple dictionary-based method, where each word is replaced by an 8-bit
code.
▶ How many bytes are needed to store the word “Beauty” in uncompressed
form?

▶ 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

21.4.2 Step counter


https://isaaccs.org/eq/data_compr_06

The pseudocode below implements a version of run length encoding.


1 FUNCTION rle( text_string )
2 current_token = text_string [0]
3 compressed = current_token
4 counter = 1
5 FOR i = 1 TO LEN( text_string ) - 1
6 next_token = text_string [i]
7 IF next_token != current_token THEN
8 compressed = compressed + STR( counter )+
next_token
9 counter = 1
10 ELSE
11 counter = counter + 1
12 ENDIF
13 current_token = next_token
14 NEXT i
15 compressed = compressed + STR( counter )
16 RETURN compressed
17 ENDFUNCTION

▶ Complete the trace table by ‘dry running’ the algorithm with an input
value of “ABBBAA”.

current_token compressed counter i next_token


21. COMPRESSION 157

21.4.3 The missing link


https://isaaccs.org/eq/data_compr_10

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

1 FUNCTION rle( text_string )


2 current_token = text_string [0]
3 compressed = current_token
4 counter = 1
5 FOR i = 1 TO LEN( text_string ) - 1
6 next_token = text_string [i]
7 IF next_token != current_token THEN
8 compressed = compressed + STR( counter ) +
next_token
9 __________________________
10 ELSE
11 __________________________
12 ENDIF
13 current_token = next_token
14 NEXT i
15 compressed = compressed + STR( counter )
16 RETURN compressed
17 ENDFUNCTION
22 Encryption
Encryption techniques are used to keep data and communications secret
from interceptors. Ciphers such as the Caesar cipher have been used for
centuries to encrypt and decrypt messages using a shared secret known
as a key. Other cipher techniques are asymmetric, which means that the
sender and recipient each use different keys to encrypt and decrypt their
messages.
At a more advanced level, you will learn that key generation for pub-
lic/private key cryptography can provide the answer to secure key ex-
change. You will also explore the Vernam cipher, a theoretically perfect
cipher in which each character is encrypted using its own key.

22.1.1 Encryption
https://isaaccs.org/eq/gcse_net_07

Encryption is the process of scrambling data so that it is no longer under-


standable. An encryption algorithm and a key is used to encrypt the data
by the sender and decrypt the data by the receiver. A common encryption
algorithm is the Caesar cipher.
▶ In a Caesar cipher with a +5 key, what would the word “exciting” be
once encrypted?

⃝ jglrcrwp

⃝ jchnynsl

⃝ jcinymsl

⃝ nhlrcrxp

22.1.2 Et tu, Brute?


https://isaaccs.org/eq/data_encrypt_02

Caesar’s friend Brutus is desperate to know what type of sandwich Caesar


has ordered. He has decided to use ‘brute force’ to decrypt the message.
▶ What is the maximum number of keys that he would have to try out?

158
22. ENCRYPTION 159

22.1.3 Don't tell the gamemaster!


https://isaaccs.org/eq/net_sec_03

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.

□ Ewan encrypts with his own private key.


□ Kasia decrypts with Ewan's public key.
□ Kasia decrypts with her own private key.
□ Ewan encrypts with Kasia's public key.
□ Ewan and Kasia publish their public keys.
□ Ewan sends the ciphertext message to Kasia.
22.1.4 Caesar's sandwich
https://isaaccs.org/eq/data_encrypt_01

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

22.2.1 Web authentication


https://isaaccs.org/eq/cyb_sec_05

A is an electronic document that authenticates a message


sender or a website and includes a serial number, expiry date, the holder‘s
name, and the holder’s public key. It will be ‘signed’ by an issuer, so its
authenticity can be verified.
▶ Select the concept that correctly matches the statement above.

⃝ patching
⃝ keyloggers
⃝ digital certificate
⃝ captcha

22.2.2 It's a surprise


https://isaaccs.org/eq/data_encrypt_winter_03

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?

⃝ Misha’s private key


⃝ Misha’s public key
⃝ Her own public key
⃝ Her own private key

22.2.3 Ordered chaos


https://isaaccs.org/eq/data_encrypt_09

Alma wants to send a message to Byron using an encryption method that


involves public and private keys.
▶ Which key does she use to encrypt the message?

⃝ Her own public key


⃝ Byron’s private key
⃝ Her own private key
⃝ Byron’s public key
22. ENCRYPTION 161

22.2.4 Fingerprint evidence


https://isaaccs.org/eq/data_encrypt_03v2

Carrying out a frequency analysis on the letters within a piece of ciphertext


can reveal a ‘fingerprint’ of the secret message. However, there are several
limitations of this technique to a codebreaker.
▶ Which of the following is most likely to cause a problem?

⃝ Repeated occurrences of irregular or uncommon words could skew the


results.

⃝ The message may be written in a different language.

⃝ There may be insufficient text to reveal any useful information.

⃝ Lots of short words can make the process of analysis time-consuming.

22.2.5 Trial and error


https://isaaccs.org/eq/data_encrypt_04

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

22.3.1 Illegal access


https://isaaccs.org/eq/data_encrypt_10

▶ In the UK, are the authorities (e.g. the police and MI5) allowed to demand
encryption keys?

⃝ Yes, if you have been charged with a criminal offence.


⃝ Yes, as long as the authorities have the relevant permissions.
⃝ No, this is not allowed under GDPR (the General Data Protection
Regulation).
⃝ No, this is an infringement of our civil liberties.
22.4.1 Aran's problem
https://isaaccs.org/eq/data_encrypt_05

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 plaintext contains only uppercase letters and spaces

• The ciphertext must contain only uppercase letter and spaces

• 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

1 plain_text = INPUT (" Enter the message ")


2 key = INPUT (" Enter the amount to shift ")
3 cipher_text = ""
4
5 FOR i = 0 TO LEN( plain_text ) - 1
6 IF plain_text [i] == " " THEN
7 cipher_text = cipher_text + plain_text [i]
8 ELSE
9 ascii_code = key + ASC( plain_text [i])
10 IF ascii_code > 90 THEN
11 ascii_code = #### [CODE MISSING ]
12 letter = CHR( ascii_code )
13 cipher_text = cipher_text + letter
14 ENDIF
15 NEXT i
16
17 PRINT ( cipher_text )

▶ What is the missing statement on line 11?

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.1.1 Foreign Correspondent


https://isaaccs.org/eq/data_dbs_01

▶ Which of the following options provides the correct definition of a foreign


key?

⃝ An attribute that is part of a composite primary key


⃝ An attribute that is used to link to another table through a matching
value in a primary key field
⃝ An attribute that uniquely identifies a record in a table
⃝ An attribute that is specified as a search field so is used to build an
index to speed up searching

23.2.1 Benefits of a database


https://isaaccs.org/eq/data_dbs_02

There are many benefits of using a database system to store data.


▶ Which of these statements is NOT a benefit of using a well-defined and
normalised database?

⃝ Elimination of deletion anomalies


⃝ Elimination of redundant data
⃝ Elimination of update anomalies
⃝ Elimination of duplicated data
166 23. DATABASE CONCEPTS

23.2.2 Relations
https://isaaccs.org/eq/data_dbs_03

Vanessa is an artist who creates collages. Each original piece of work is


displayed in her gallery. She does not sell the original work but customers
can purchase high-quality signed copies; a sale records the purchase of an
individual print. There is a limit to how many copies will be sold and each
copy is numbered (e.g. print 20 of 75). Behind the scenes there is a database.
The table definitions for the database are as follows:
tblCollage (<u
class ="text -decoration -skip -none">CollageId </u>,
Description , ProductionYear , Limit)

tblSale (<u class ="text -decoration -skip -none">CollageId ,


PrintNumber </u>, SaleDate , Cost , CustomerId )

tblCustomer (<u>CustomerId </u>, LastName , FirstName , Email)

▶ What is the degree of relationship between collage and sale?

⃝ There is no direct relationship

⃝ One-to-one

⃝ One-to-many

⃝ Many-to-many

23.2.3 Concurrent problems


https://isaaccs.org/eq/data_dbs_09

Most databases have many users and allow concurrent access to tables.
▶ Which of the following situations will cause a problem (tick all that apply):

□ Two users trying to read the same record

□ Two users trying to update the same record

□ One user trying to delete a record while someone else is reading it

□ One user trying to read a record while someone else is updating it


23. DATABASE CONCEPTS 167

23.4.1 A dog's dinner


https://isaaccs.org/eq/data_dbs_07

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 target emails at owners of a specific breed


of dog.

□ 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.

24.1.1 Expansion plans


https://isaaccs.org/eq/data_dbs_08

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?

⃝ UPDATE tblClass SET MaxPlaces = 15;

⃝ UPDATE tblClass SET MaxPlaces = 15 WHERE ClassType = “basic


agility” OR ClassType = “advanced agility”;

⃝ UPDATE tblClass SET MaxPlaces = 15 WHERE (ClassType = “basic


agility” OR “advanced agility”) AND MaxPlaces = 10;

⃝ UPDATE tblClass SET MaxPlaces = 15 WHERE MaxPlaces = 10;

168
24. SQL 169

24.1.2 Insertion challenge


https://isaaccs.org/eq/data_dbs_06

Vanessa is an artist who creates collages. Each original piece of work is


displayed in her gallery. She does not sell the original work but customers
can purchase high-quality signed copies. There is a limit to how many copies
will be sold and each copy is numbered (e.g. print 20 of 75). Behind the
scenes there is a database. The table definitions for the database are as
follows:
tblCollage (CollageId, Description , ProductionYear , Limit )
tblSale (CollageId, PrintNumber, SaleDate , Cost , CustomerId )
tblCustomer (CustomerId, LastName , FirstName , Email)

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.

□ INSERT INTO TABLE tblCollage


□ VALUES (12765, ‘Santorini ’seascape, 2020, 25)
□ (CollageId, Description, ProductionYear, Limit)
□ INSERT INTO tblCollage
□ (Description, ProductionYear, Limit)
□ VALUES (12765, Santorini seascape, 2020, 25)
170 24. SQL

24.1.3 Print owners


https://isaaccs.org/eq/data_dbs_04

Vanessa is an artist who creates collages. Each original piece of work is


displayed in her gallery. She does not sell the original work but customers
can purchase high-quality signed copies. There is a limit to how many copies
will be sold and each copy is numbered (e.g. print 20 of 75). Behind the
scenes there is a database. The table definitions for the database are as
follows:
tblCollage (CollageId, Description , ProductionYear , Limit)
tblSale (CollageId, PrintNumber, SaleDate , Cost , CustomerId )
tblCustomer (CustomerId, LastName , FirstName , Email )

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.

1 SELECT tblSale .CollageId , tblSale . PrintNumber ,


tblCustomer .LastName , tblCustomer .FirstName ,
tblCustomer . Email
2 FROM tblSale , tblCustomer , tblCollage
3 WHERE ___________________________________
4 AND tblCollage . CollageId = tblSale . CollageId
5 AND tblCollage . ProductionYear = ‘’2019
6 ORDER BY tblCustomer . LastName
24. SQL 171

24.3.1 How much did she sell?


https://isaaccs.org/eq/data_dbs_05

Vanessa is an artist who creates collages. Each original piece of work is


displayed in her gallery. She does not sell the original work but customers
can purchase high-quality signed copies. There is a limit to how many copies
will be sold and each copy is numbered (e.g. print 20 of 75). Behind the
scenes there is a database. The table definitions for the database are as
follows:
tblCollage (CollageId, Description , ProductionYear , Limit )
tblSale (CollageId, PrintNumber, SaleDate , Cost , CustomerId )
tblCustomer (CustomerId, LastName , FirstName , Email)

This is the data for one of the records in the table that records sales:

CollageId PrintNumber SaleDate Cost CustomerId


201 12 2019-11-23 235.00 12654

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.

□ AND tblSale.SaleDate >= ‘’2019-01-01


AND tblSale.SaleDate <= ‘’2019-12-31

□ SELECT tblSale.CollageId, tblSale.PrintNumber, tblSale.SaleDate,


tblSale.Cost, tblCustomer.LastName, tblCustomer.Email

□ ORDER BY tblSale.SaleDate
□ WHERE tblCustomer.CustomerId = tblSale.CustomerId
□ FROM tblSale, tblCustomer
172 24. SQL

24.3.2 Wrong customer


https://isaaccs.org/eq/data_dbs_11

Vanessa is an artist who creates collages. Each original piece of work is


displayed in her gallery. She does not sell the original work but customers
can purchase high-quality signed copies. There is a limit to how many copies
will be sold and each copy is numbered (e.g. print 20 of 75). Behind the
scenes there is a database. The table definitions for the database are as
follows:
tblCollage (CollageId, Description , ProductionYear , Limit)
tblSale (CollageId, PrintNumber, SaleDate , Cost , CustomerId )
tblCustomer (CustomerId, LastName , FirstName , Email )

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

□ INSERT INTO tblCustomer (CustomerId , LastName ,


FirstName , Email )
VALUES (75 , 'Patel ', 'David ', 'david@mymail .com ')

□ SET
UPDATE tblCustomer
LastName = 'Patel ', FirstName = 'David ', Email =
'david@mymail .com '
WHERE CustomerId = 74

□ INSERT INTO tblSale (CollageId , PrintNumber , SaleDate ,


Cost , CustomerId )
VALUES (7, 12, 2020/06/01 , 100, 75)
174 24. SQL

24.4.1 A poll on climate change


https://isaaccs.org/eq/data_dbs_14

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 question is “Which is a higher risk of climate change?”.

• The poll options are: extreme temperatures and sea level rise.

Referential integrity is in force between tblPoll.PollId (primary key) and


tblOption.PollId (foreign key).
Select the correct SQL statements and put them into the correct order so as
to create the records for the poll in the database. They do not all need to
be used.

□ INSERT INTO tblPoll (PollId, QuestionText, IsActive, PublishedDate)


VALUES (1, 'Which is a higher risk of climate change?', 'True',
'2021/10/01')

□ UPDATE tblPoll
SET QuestionText = 'Which is a higher risk of climate change?'
SET OptionText = 'extreme temperatures', 'sea level rise'
WHERE PollId = 1

□ INSERT INTO tblOption (OptionId, PollId, OptionText)


VALUES (2, 1, 'sea level rise')
24. SQL 175

□ INSERT INTO tblOption (OptionId, PollId, OptionText)


VALUES (1, 2, 'sea level rise')

□ INSERT INTO tblOption (OptionId, PollId, OptionText)


VALUES (1, 1, 'extreme temperatures', 'sea level rise')

□ INSERT INTO tblOption (OptionId, PollId, OptionText)


VALUES (1, 1, 'extreme temperatures')
176 24. SQL

24.4.2 SELECT poll results


https://isaaccs.org/eq/data_dbs_16

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

24.4.3 SELECT active polls


https://isaaccs.org/eq/data_dbs_15

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.

25.1.1 Primitive types


https://isaaccs.org/eq/dsa_datastruct_26

▶ An integer is an example of a primitive data type. Which of the following


data types are also primitive?

□ Queue

□ Boolean

□ String

□ List

□ Character

□ Stack

179
180 25. DATA STRUCTURES

25.1.2 Student 13
https://isaaccs.org/eq/gcse_prog_19

A record is a data structure that can be used to store multiple pieces of


data that relate to the same thing. Unlike in an array, the fields contained
within a record structure do not all have to be of the same data type. See
the example below:
1 StudentRecord = RECORD
2 student_id : Integer
3 first_name : String
4 last_name : String
5 class_id : String
6 enrolled : Boolean
7 ENDRECORD

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

25.2.1 Who are the participants?


https://isaaccs.org/eq/prog_concepts_08

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?

25.2.2 Dynamic advantage


https://isaaccs.org/eq/dsa_datastruct_01

▶ Which of these is an advantage of a dynamic data structure?

⃝ It makes efficient use of memory, using only as much memory as it


needs

⃝ It will overflow if it exceeds its allocated memory

⃝ The memory allocation is fixed so there is no need to check size when


adding and removing data items

⃝ It allocates memory to pointers to keep track of where things are


182 25. DATA STRUCTURES

25.2.3 How do I look?


https://isaaccs.org/eq/dsa_datastruct_13

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:

1. change colour to blue

2. undo

3. undo

4. change size to 14

▶ How will the text be formatted at the end of the sequence of operations?

⃝ colour — blue; style — Georgia; emphasis — normal; align — right;


size — 14

⃝ colour — black; style — Arial; emphasis — italic; align — right; size


— 12

⃝ colour — blue; style — Arial; emphasis — italic; align — right; size


— 14

⃝ colour — black; style — Georgia; emphasis — italic; align — right;


size — 14
25. DATA STRUCTURES 183

25.2.4 All change


https://isaaccs.org/eq/dsa_datastruct_14

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.

⃝ peek, push 59, pop, push 91, pop, pop, push 1


⃝ push 1, pop, push 59, pop, push 91, pop, peek, pop, push 17
⃝ pop, push 59, pop, push 91, pop, peek, pop, push 1
⃝ peek, pop, pop, pop, push 1, push 59, pop, push 19, peek
184 25. DATA STRUCTURES

25.2.5 We like to queue


https://isaaccs.org/eq/dsa_datastruct_02

The following diagram is an abstraction of a linear queue.


The front pointer (black) points to the start of the queue. The rear pointer
(grey) points to the end of the queue.
Dan is at the front of the queue in position 0.
The following names are enqueued in the order given:

• 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

25.2.6 Queue jumping


https://isaaccs.org/eq/dsa_datastruct_03

The following diagram is an abstraction of a priority queue. Teachers have


higher priority than students in the queuing system. Dan, a student, is at
the front of the queue in position 0.
The front pointer (black) points to the start of the queue.
The rear pointer (grey) points to the end of the queue.

Adam (Teacher), Sasha (Student), and Mohammed (Teacher) are added to


the queue (enqueued) in the order given.
▶ To which position will front point after all the names have been added?

▶ 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

25.2.7 Stacking books


https://isaaccs.org/eq/dsa_datastruct_05

The following diagram is an abstraction of a stack. The stack currently


contains three items (names). The pointer to the top of the stack is shown,
currently pointing to position 2.

The following operations are carried out in the order given:

• push Harry • peek


• pop • pop
• push Luna • pop

▶ 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

25.2.8 Effective hashing algorithm


https://isaaccs.org/eq/dsa_datastruct_07

▶ Which of these criteria are necessary for an effective hashing algorithm?


(tick all that apply)

□ Must minimise collisions


□ Must leave no slots empty
□ Must always generate the same hash key from the same hash value
□ Must generate a good spread over the problem space

25.2.9 Tree classification


https://isaaccs.org/eq/dsa_datastruct_08

▶ Which of these properties will prevent a graph being classified as a rooted


tree?

⃝ There is a unique cycle between two nodes.


⃝ There is only one path between two nodes.
⃝ The root node has more than two children.
⃝ It has an even number of leaves.

25.2.10 A better list?


https://isaaccs.org/eq/dsa_datastruct_21

A graph can be represented using an adjacency matrix or an adjacency list.


▶ Under which circumstances would it be more appropriate to use an ad-
jacency list (instead of an adjacency matrix)? Select all of the statements
that apply.

□ When nodes will be removed frequently


□ When new edges will be added frequently
□ When edges will be removed frequently
□ When new nodes will be added frequently
□ When the presence or absence of edges will be tested frequently
□ 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
188 25. DATA STRUCTURES

25.2.11 Piece of cake


https://isaaccs.org/eq/dsa_datastruct_winter_09

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.

Figure 25–3: The festive cake


25. DATA STRUCTURES 189

▶ 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?

25.2.12 Nothing to pop


https://isaaccs.org/eq/dsa_datastruct_06

▶ The following statements, in structured English, form the algorithm for


the pop operation on a stack. Number them into the correct order.

□ Else return the data item indexed by stack_pointer


□ Check if the stack is empty
□ If stack empty, display error and return / halt
□ Decrement stack_pointer by one
190 25. DATA STRUCTURES

25.2.13 A better matrix?


https://isaaccs.org/eq/dsa_datastruct_22

A graph can be represented using an adjacency matrix or an adjacency list.


▶ Under which circumstances would it be more appropriate to use an ad-
jacency matrix (instead of an adjacency list)? Select all of the statements
that apply.

□ When new edges will be added frequently

□ When the presence or absence of edges will be tested frequently

□ When new nodes will be added frequently

□ When nodes will be removed frequently

□ 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

□ When edges will be removed frequently

25.2.14 Is it a tree?
https://isaaccs.org/eq/dsa_datastruct_23

A tree is a type of graph with some specific properties.


▶ Which of the following statements is true when used to help define a ‘tree’?

⃝ A tree has no cycles.


⃝ A tree can be unconnected.
⃝ A tree has one node designated as the root.
⃝ A tree is directed.
25. DATA STRUCTURES 191

25.3.1 Times tables


https://isaaccs.org/eq/dsa_datastruct_27

Benji has written an algorithm that calculates the multiples of a given num-
ber. The algorithm:

• Prompts the user to enter a number

• Calculates the multiples of the number

• Stores the multiples in an array

• Returns the array

The pseudocode for the algorithm is shown below.


1 FUNCTION times_tables ()
2 ARRAY table [10]
3 base = INPUT (" Enter a number : ")
4 FOR count = 0 TO 9
5 table[ count] = ( count + 1) * base
6 NEXT count
7 RETURN table
8 ENDFUNCTION

▶ 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

25.3.2 The length of an array


https://isaaccs.org/eq/dsa_datastruct_28

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?

25.3.3 Dinosaur records


https://isaaccs.org/eq/gcse_prog_07_v2

Josh wants to write a program to catalogue different dinosaur stats. He is


using a record data type to store the data, and he has set it up like this:
1 Dinosaur = RECORD
2 dino_id : Integer
3 name: String
4 food: String
5 ENDRECORD

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

25.3.4 Baby words array


https://isaaccs.org/eq/gcse_prog_06

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

25.3.5 The name of the track


https://isaaccs.org/eq/gcse_prog_16

Sergiu wants to create a system to catalogue his music collection. To get


started, he has defined:

• a record structure - MusicRecord - for storing the information about a


specific track
• an array of records - album - to store the details for all of the tracks on
a specific album

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

25.3.6 Extracting a record


https://isaaccs.org/eq/gcse_prog_17

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

A username is generated automatically for each volunteer so that they can


log in to the charity’s system. The format of the username is the last name
followed by the first name without any spaces.
▶ Which one of the following choices would generate the correct username
for Raj Whelan?

⃝ volunteer1.last_name + volunteer1.first_name

⃝ volunteer1.first_name + volunteer1.last_name

⃝ last_name + first_name

⃝ first_name + last_name
196 25. DATA STRUCTURES

25.4.1 Nursery food


https://isaaccs.org/eq/dsa_datastruct_11

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 }

These dictionaries are stored in the list children.


At the start of each day, the nursery kitchen needs a printed list of the
children who are present and their dietary requirements, for example:
Nadia — vegetarian
Assume that the today() function returns the current day of the week as a
string.

▶ Fill in the missing code to create the report for the kitchen.

1 FOR c = 0 TO LEN( children )


2 child = _________________________
3 FOR i = 0 to LEN( child [" days_present "])
4 IF _________________________ == today () THEN
5 PRINT ( child ['name '] + " - " + child['dietary '])
6 ENDIF
7 NEXT i
8 NEXT c
25. DATA STRUCTURES 197

25.4.2 Adjacency list 1


https://isaaccs.org/eq/dsa_datastruct_18

A graph can be directed or undirected. It can also be weighted or un-


weighted. Below is an example of a directed, unweighted graph used to
represent the connections between seven nodes.

▶ Which of the following options represents an adjacency list for the given
graph?

A B

Nodes Adjacency list Nodes Adjacency list


1 0; 1; 1; 1; 0; 0; 0 1 1; 2; 3; 4
2 0; 0; 0; 0; 1; 0; 0 2 2; 5
3 0; 1; 0; 0; 0; 1; 0 3 2; 3; 6
4 0; 0; 0; 0; 0; 0; 0 4
5 0; 0; 0; 0; 0; 0; 0 5
6 0; 0; 0; 0; 0; 0; 1 6 6; 7
7 0; 0; 0; 0; 0; 0; 0 7
C D

Nodes Adjacency list Nodes Adjacency list


1 1; 0; 0; 0; 1; 1; 1 1 2; 3; 4
2 1; 1; 1; 1; 0; 1; 1 2 5
3 1; 0; 1; 1; 1; 0; 1 3 2; 6
4 1; 1; 1; 1; 1; 1; 1 4
5 1; 1; 1; 1; 1; 1; 1 5
6 1; 1; 1; 1; 1; 1; 0 6 7
7 1; 1; 1; 1; 1; 1; 1 7
198 25. DATA STRUCTURES

25.4.3 Helping to enqueue


https://isaaccs.org/eq/dsa_datastruct_12

Niamh is planning to use a queue as a data structure in her software project.


She is designing the algorithm to enqueue data onto a linear queue based on
an array.
▶ Can you help her by putting the structured English statements (shown
below) into the correct order?
In the statements, rear is a pointer to the end of the queue and maxsize is
the maximum size of the queue.

□ 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"

25.4.4 Delivery route planner


https://isaaccs.org/eq/dsa_datastruct_17

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

25.4.5 Rental properties


https://isaaccs.org/eq/dsa_datastruct_16

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.

▶ An adjacency matrix is used to store the data. Which of the tables


represents the graph data shown in the figure?
25. DATA STRUCTURES 201

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

25.4.6 Reverse order


https://isaaccs.org/eq/dsa_datastruct_15

A local highways agency is developing a program to simulate a new section


of road. A queue will be used to store vehicles that are queuing at a junction.
The new road will be quite narrow and if there is a blockage at the junction
the vehicles will need to turn round one at a time starting at the end of the
queue. This will create a new queue (heading in the opposite direction) that
will be a reverse of the original queue. For example:

Original queue:

Car 1 Car 2 Van 1 Car 3


FRONT REAR

Reversed queue:

Car 3 Van 1 Car 2 Car 1


FRONT REAR

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

Consider an alphanumeric key that is made up of any five letters or numbers.


An example would be 1SAAC.
A hash function calculates hash values as follows:

• each character in the key is converted to its ASCII decimal numeric


code (i.e. A will be converted to 65)

• the numeric codes are summed to give a total

• the total is divided by the number of slots in the hash table using
modular division

• the result is the hash value

▶ If a hash table has 55 slots (buckets) what hash value will be generated
for the key value 1SAAC?
204 25. DATA STRUCTURES

25.4.8 Going round in circles


https://isaaccs.org/eq/dsa_datastruct_04

The following diagram is an abstraction of a queue. The queue will be


implemented using a static array and circular queue methods are used to
make efficient use of space. The front pointer (black) points to the start of
the queue. The rear pointer (grey) points to the end of the queue. Dan is at
the front of the queue in position 0. A series of operations occur as follows:

• enqueue Nigel, • enqueue Germaine,


• enqueue Anil, • dequeue,
• enqueue Sasham, • dequeue,
• dequeue, • enqueue Tom,
• enqueue Jordan, • enqueue Ben,
• dequeue, • dequeue,
• enqueue Aayna, • enqueue Amar

▶ 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

25.4.9 Tree traversal


https://isaaccs.org/eq/dsa_datastruct_09

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)

1 FUNCTION traverse (node)


2 IF node.data == None THEN
3 RETURN
4 ELSE
5 traverse (node.left)
6 traverse (node.right )
7 PRINT(node.data)
8 ENDIF
9 ENDFUNCTION

▶ Select the correct results of tracing the pseudocode.

⃝ 36, 43, 32, 75, 82, 93, 84, 81, 50


⃝ 36, 43, 32, 50, 81, 75, 84, 82, 93
⃝ 32, 36, 43, 50, 75, 81, 82, 84, 93
⃝ 50, 32, 43, 36, 81, 75, 84, 82, 93
206 25. DATA STRUCTURES

25.4.10 Traversing a graph


https://isaaccs.org/eq/dsa_datastruct_19

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.

▶ Consider a breadth-first and a depth-first traversal of the graph shown,


starting from the node labelled A, in what order will the nodes be visited?
When you trace each traversal and need to make a decision between neigh-
bouring nodes, choose the node with the letter value closest to the beginning
of the alphabet.

⃝ • 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

25.4.11 The friendship graph


https://isaaccs.org/eq/dsa_datastruct_20

A group of students have decided to create a list of their respective friends


within the group. Each student has been allocated a number, and the friend-
ship connections between five members of the group can be represented with
the adjacency list shown below:

Members Friends with


0 1, 2, 3, 4
1 0, 3
2 0, 3, 4
3 0, 1, 2, 4
4 0, 2, 3

▶ Which of the following graphs illustrates the data stored in the adjacency
list?

A B

C D
208 25. DATA STRUCTURES

25.4.12 Find the children


https://isaaccs.org/eq/dsa_datastruct_24

A binary tree can be implemented as an array of records. The record for


each node will contain:

• The data

• A left child pointer

• A right child pointer

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.

Index Data Left Right


0 1 1 2
1 4 4 5
2 3 Null 3
3 8 6 Null
4 12 Null Null
5 6 7 8
6 2 Null Null
7 10 Null Null
8 5 Null Null

▶ 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

25.4.13 It's a hash


https://isaaccs.org/eq/dsa_datastruct_29

A hash function is an algorithm that converts a hash key to a hash value. A


simple example of a hash function is represented by the pseudocode shown
below:
1 FUNCTION hash_it (hash_key , number_of_slots )
2 hash_value = hash_key MOD number_of_slots
3 RETURN hash_value
4 ENDFUNCTION

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

Key Hash value Key Hash value


31971 1 31971 666
43219 4 43219 900
56342 8 56342 1173
96756 7 96756 2015
C D

Key Hash value Key Hash value


31971 51 31971 3
43219 67 43219 19
56342 86 56342 38
96756 84 96756 36
210 25. DATA STRUCTURES

25.4.14 Collision between keys


https://isaaccs.org/eq/dsa_datastruct_31

A simple example of a hash function is represented by the pseudocode shown


below:
1 FUNCTION hash_it (hash_key , number_of_slots )
2 hash_value = hash_key MOD number_of_slots
3 RETURN hash_value
4 ENDFUNCTION

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?

⃝ All of the keys hash to the same value


⃝ None of the keys hash to the same value
⃝ The keys 1974, 1971 and 1979 hash to the same value
⃝ The keys 9459, 1979, 6579 hash to the same value

25.4.15 Odd one out


https://isaaccs.org/eq/dsa_datastruct_25

▶ Data structures can be static or dynamic. In this respect, which of the


following statements is not correct?

⃝ A static array cannot be resized at run time.


⃝ The elements of a dynamic linked list can be accessed directly by index.
⃝ A dynamic data structure is a collection of data in memory that can
grow or shrink in size at run time.
⃝ A static array uses an allocation of contiguous (one after another)
locations in main memory.
25. DATA STRUCTURES 211

25.4.16 Where's Rudolph?


https://isaaccs.org/eq/dsa_datastruct_winter_01

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:

• Array D stores the data (the name of the reindeer)


• Array L stores the left ‘pointer’ (index numbers)
• Array R stores the right ‘pointer’ (index numbers)

▶ 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.

26.1.1 Straight down the line


https://isaaccs.org/eq/dsa_search_01

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.

⃝ [393, 783, 656, 143, 727]


⃝ [“Blue”, “Green”, “Purple”, “Teal”, “Yellow”]
⃝ [“TN-0094”, “TN-0184”, “TN-0412”, “TN-0905”, “TN-0939”]
⃝ [1, 38, 41, 56, 64, 78]

212
26. SEARCHING ALGORITHMS 213

26.1.2 How many halves?


https://isaaccs.org/eq/dsa_search_04

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

26.1.3 Birds on a binary search tree


https://isaaccs.org/eq/dsa_search_12

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?

▶ The tree illustrated in figure 1 is an example of a balanced tree. For a


balanced tree, with n nodes, what is the time complexity in Big O notation
of the binary tree search algorithm?

⃝ O(logn)
⃝ O(n2 )
⃝ O(n logn)
⃝ O(n)
216 26. SEARCHING ALGORITHMS

26.1.4 New Year's Eve


https://isaaccs.org/eq/dsa_search_winter_07

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?

26.1.5 Maximum comparisons


https://isaaccs.org/eq/dsa_search_19

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

26.3.1 Flagging you down


https://isaaccs.org/eq/dsa_search_02

Consider the pseudocode implementation below:


1 FUNCTION linear_search (data_set , item_sought )
2 index = -1
3 i = 0
4 found = False
5 WHILE i < LEN( data_set ) AND found == False
6 IF data_set [i] == item_sought THEN
7 index = i
8 found = True
9 ENDIF
10 i = i + 1
11 ENDWHILE
12 RETURN index
13 ENDFUNCTION

Linear search can be a very inefficient algorithm because, in some versions, it


iterates through the whole of the list even when the item has already found.
▶ In this more efficient version of the algorithm, which variable is used to
terminate the loop when the item has been found?

Consider the following list:


data = [262, 764, 301, 220, 471, 900, 139, 779, 439, 190]
▶ What would be returned from the following statement?
linear_search(data, 471)
218 26. SEARCHING ALGORITHMS

26.3.2 Searching an array of records


https://isaaccs.org/eq/dsa_search_11

Bronwin wants to create a program that will search an array of student


names and return True if a given student has volunteered for the Year 7
Open Evening. She is considering whether to use a linear search or a
binary search for this purpose.
Each item of the array is a record with three fields:

• 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.

The first three elements of the array are:


‘[[’ST201, ‘Simon ’Brown, True], ‘[’ST202, ‘Kate ’Morris, False], ‘[’ST203,
‘Alicia ’Huston, False]]
▶ In relation to the use of a linear search or binary search to find an item
in an array of records, which of the following statements is correct?

⃝ 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

26.3.3 Stuck in the middle


https://isaaccs.org/eq/dsa_search_03

▶ Here is the binary search function, fill in the statement to calculate the
midpoint.

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 = _____________________________
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
27 Sorting algorithms
Sorting data is an essential data management task. You may need to display
information in a specific order, or you may need to sort your data to make
it quicker to search for something within the data set. There are many
standard algorithms that can be used to sort data, such as bubble sort and
merge sort. At a more advanced level, you will learn that these sorting
algorithms can be implemented in code in a variety of ways. 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.

27.1.1 The purpose of temp


https://isaaccs.org/eq/dsa_search_05

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

▶ Explain the purpose of the temp variable in the algorithm.

⃝ 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

27.1.2 One step before the last


https://isaaccs.org/eq/dsa_search_07

You have the following array in your program:


words = ["Purple", "Yellow", "Green", "Red", "Blue", "Magenta"]
You want to use merge sort to put these items into alphabetical order by
using the recursive method of splitting the list into sublists and merging the
sublists .
▶ How will the sublists that need to be merged look one step before the
list is sorted?

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

List 1 List 2 List 3



Purple Yellow Green Red Blue Magenta

27.1.3 Sorting prime numbers


https://isaaccs.org/eq/dsa_search_13

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?

⃝ [73, 43, 23, 67, 47, 79, 83, 89, 97]

⃝ [43, 23, 97, 67, 47, 73, 79, 83, 89]

⃝ [73, 43, 23, 83, 67, 47, 79, 89, 97]

⃝ [43, 23, 73, 67, 47, 79, 83, 89, 97]


222 27. SORTING ALGORITHMS

27.1.4 Maximum bubbles


https://isaaccs.org/eq/dsa_search_14

Michael is going to sort an array items that holds 5 random numbers


generated using a subroutine that produces random integers. As the numbers
are generated at runtime, it is not possible to guess how the unsorted array
will look.
The array is to be sorted into ascending order using the version of the bubble
sort algorithm shown in pseudocode below:

1 PROCEDURE bubble_sort ( items)


2 # Initialise variables
3 num_items = LEN(items )
4 temp = 0
5 pass_number = 1
6 swapped = True
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]) THEN
14 # Swap items
15 temp = items[index]
16 items[ index] = items[index + 1]
17 items[ index + 1] = temp
18 swapped = True
19 ENDIF
20 pass_number = pass_number + 1
21 NEXT index
22 ENDWHILE
23 ENDPROCEDURE

▶ What is the maximum number of swaps that might be carried out?

▶ What is the maximum number of passes that might be performed?


27. SORTING ALGORITHMS 223

27.1.5 How many times?


https://isaaccs.org/eq/dsa_search_15

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.

1 FUNCTION merge_sort (items )


2 # Base case for recursion :
3 # Recursion will stop when the list has been divided
into single items
4 IF LEN( items ) < 2 THEN
5 RETURN
6 ELSE
7 midpoint = (LEN( items) - 1) DIV 2 # Calculate
midpoint
8 left_half = items [0: midpoint ] # Create left half
list
9 right_half = items [ midpoint +1: LEN( items ) -1] #
Create right half list
10
11 merge_sort ( left_half ) # Recursive call on left half
12 merge_sort ( right_half ) # Recursive call on right
half
13
14 merge(items , left_half , right_half ) # Call
procedure to merge both halves
15 ENDIF
16 ENDFUNCTION

▶ How many times (including the first) will the function merge_sort be
called to sort the list?
224 27. SORTING ALGORITHMS

27.1.6 Getting hotter?


https://isaaccs.org/eq/dsa_search_16

A primary school is asking pupils to measure the outside temperature every


day at noon. The temperatures will be recorded and sorted into ascending
order.
The procedure will use a bubble sort algorithm to sort the following data,
stored in an array.
[28.2, 24.8, 21.3, 25.0, 23.4, 27.1, 25.0]
▶ At the end of which pass of the algorithm would the state of the
array be as shown below?
[24.8, 21.3, 25.0, 23.4, 27.1, 25.0, 28.2]

⃝ At the end of the third pass.

⃝ At the end of the first pass.

⃝ At the end of the fourth pass.

⃝ At the end of the second pass.

▶ How many swaps are needed in total to sort this array into ascending
order using bubble sort?

⃝ 10 swaps are performed to sort the array.

⃝ 11 swaps are performed to sort the array.

⃝ 9 swaps are performed to sort the array.

⃝ 6 swaps are performed to sort the array.

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:

List 1 List 2 List 3 List 4 List 5 List 6 List 7


14577 12434 12113 12566 12321 12707 10350

▶ What will Anil expect to see as a result of the next step (step 4) which
starts the merging of the seven sublists?

List 1 List 2 List 3 List 4



12434 14577 12113 12566 12321 12707 10350

List 1 List 2 List 3 List 4



14577 12434 12113 12566 12321 12707 10350

List 1 List 2 List 3 List 4



14577 12434 12566 12113 12707 12321 10350

List 1 List 2 List 3 List 4



14577 12113 12434 12566 12321 10350 12707

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 List 3



12113 12434 14577 12321 12566 12707 10350

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

27.2.1 Top of the class


https://isaaccs.org/eq/dsa_search_22_v2

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

□ 74, 68, 64, 49, 43, 70


□ 74, 70, 68, 64, 49, 43
□ 74, 68, 64, 43, 49, 70
□ 74, 64, 43, 68, 49, 70
□ 74, 43, 64, 68, 49, 70
27.2.2 Is it quicker?
https://isaaccs.org/eq/dsa_search_29_v2

The quick sort algorithm is a very efficient sorting algorithm. On average,


time complexity is O(n log n) which is the same as a merge sort. However,
in the best case merge sort outperforms quick sort. Despite this, the quick
sort is often favoured over merge sort.
▶ Which of the following statements provides the best reason for choosing
quick sort to sort your data?

⃝ Quick sort performs better than merge sort in the worst case.

⃝ Quick sort has better space complexity than merge sort.

⃝ Quick sort is easier to code than merge sort.

⃝ Quick sort will out perform merge sort if an optimal pivot value is
chosen.
27. SORTING ALGORITHMS 227

27.2.3 Insert into order


https://isaaccs.org/eq/dsa_search_26_v2

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

□ WHILE previous >= 0 and


items[previous] > item_to_insert

□ items[previous
items[previous]
+ 1] =

□ previous = previous - 1
□ items[previous
item_to_insert
+ 1] =

□ ENDWHILE
228 27. SORTING ALGORITHMS

27.2.4 Insert with care


https://isaaccs.org/eq/dsa_search_25_v2

A list of names needs to be ordered alphabetically (A to Z) and will be


processed using the insertion sort algorithm. The original unordered list
of names is as follows:
Mohammed, Gary, Katie, Anil, George, Kamila, Sej
At each stage of the process, the list will become more and more sorted.
▶ Which of the following options shows the state of the list as each name is
correctly positioned?

Gary, Mohammed, Katie, Anil, George, Kamila, Sej


Gary, Katie, Mohammed, Anil, George, Kamila, Sej
Anil, Gary, Katie, Mohammed, George, Kamila, Sej

Anil, Gary, George, Katie, Mohammed, Kamila, Sej
Anil, Gary, George, Kamila, Katie, Mohammed, Sej
Anil, Gary, George, Kamila, Katie, Mohammed, Sej

Gary, Katie, George, Kamila, Mohammed, Anil, Sej


Gary, George, Kamila, Katie, Anil, Mohammed, Sej
Gary, George, Kamila, Anil, Katie, Mohammed, Sej

Gary, George, Anil, Kamila, Katie, Mohammed, Sej
Gary, Anil, George, Kamila, Katie, Mohammed, Sej
Anil, Gary, George, Kamila, Katie, Mohammed, Sej

Anil, Gary, Mohammed, Katie, George, Kamila, Sej


Anil, Gary, Mohammed, Katie, George, Kamila, Sej
Anil, Gary, George, Mohammed, Katie, Kamila, Sej

Anil, Gary, George, Katie, Mohammed, Kamila, Sej
Anil, Gary, George, Kamila, Katie, Mohammed, Sej
Anil, Gary, George, Kamila, Katie, Mohammed, Sej

Gary, Mohammed, Katie, Anil, George, Kamila, Sej


Gary, Katie, Mohammed, Anil, George, Kamila, Sej
Anil, Gary, Katie, Mohammed, George, Kamila, Sej

Anil, Gary, George, Katie, Mohammed, Kamila, Sej
Anil, Gary, George, Katie, Kamila, Mohammed, Sej
Anil, Gary, George, Katie, Kamila, Mohammed, Sej
27. SORTING ALGORITHMS 229

27.2.5 Trace the pivot


https://isaaccs.org/eq/dsa_search_28_v2

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

The list to be sorted is: 43, 21, 2, 50, 3, 80, 35, 7, 64


▶ Which of the following pairs of items is the first pair to be swapped?

⃝ 50 and 7
⃝ 43 and 35
⃝ 80 and 35
⃝ 21 and 64

27.2.6 Count the moves


https://isaaccs.org/eq/dsa_search_06_v2

The following list of items must be sorted into ascending order.


67, 589, 166, 222, 300, 115, 352
This is how the list will look like at the beginning of the algorithm, stored
in an array.

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

27.2.7 Shifting markers


https://isaaccs.org/eq/dsa_search_08_ocr

The pseudocode for the quick sort algorithm is shown below.


1 FUNCTION quick_sort (items , start , end)
2
3 IF start >= end then # Base case
4 RETURN
5 ENDIF
6
7 pivot = items [start ] # Set pivot value to first item in
partition
8 low_mark = start + 1 # Set to second value in partition
9 high_mark = end # Set to last value on partition
10 finished = False
11
12 # Repeat until low and high values have been swapped as
needed
13 WHILE finished == False
14 WHILE low_mark <= high_mark AND items[ low_mark ] <=
pivot
15 # Move low mark
16 ______________________________
17 ENDWHILE
18 WHILE low_mark <= high_mark and items[ high_mark ] >=
pivot
19 # Move high mark
20 ______________________________
21 ENDWHILE
22 IF low_mark < high_mark THEN # Swap values at low
and high marks
23 temp = items[ low_mark ]
24 ______________________________
25 items[ high_mark ] = temp
26 ELSE
27 finished = True
28 ENDIF
29 ENDWHILE
30
31 # Swap pivot value and high marker
32 temp = items [start ]
33 ______________________________
34 items[ high_mark ] = temp
35
36 # Recursive call on left partition
27. SORTING ALGORITHMS 231

37 quick_sort (items , start , high_mark - 1)


38
39 # Recursive call on right partition
40 quick_sort (items , high_mark + 1, end)
41
42 ENDFUNCTION

▶ Fill in the four missing code statements (lines 16, 20, 24 and 33).

27.2.8 Choose a pivot


https://isaaccs.org/eq/dsa_search_30_v2

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?

⃝ The first value in the partition is being used.


⃝ The last value in the partition is being used.
⃝ A random value from the partition is being used
⃝ The value that lies in the middle of the partition is being used.
232 27. SORTING ALGORITHMS

27.3.1 Pick the correct statement


https://isaaccs.org/eq/dsa_search_09

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.

27.3.2 Blunder bubble


https://isaaccs.org/eq/dsa_search_21

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

16 items [index ] = items[index + 1]


17 items [index + 1] = temp
18 swapped = True
19 ENDIF
20 NEXT index
21 pass_number = pass_number + 1
22 ENDWHILE

There is a problem with the algorithm and it will not sort the data correctly.
▶ What is the problem?

⃝ The inner loop is running too many times.


⃝ The variable swapped has been initialized incorrectly.
⃝ The items are being compared in the wrong order.
⃝ The outer loop is running insufficient times.

Kofi has corrected the error in the pseudocode.


▶ What is the total number of swaps required to sort the array items
into descending order?

27.3.3 Complex times


https://isaaccs.org/eq/dsa_search_18

A bubble sort is used to sort a list of n items.


▶ What is the Big O notation of the time complexity of the bubble sort
algorithm?

⃝ 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

27.4.1 Inserting is complex


https://isaaccs.org/eq/dsa_search_27_v2

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.

27.4.2 The best sort?


https://isaaccs.org/eq/dsa_search_31_v2

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

27.4.3 Bubbling up?


https://isaaccs.org/eq/dsa_search_20_v2

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.

28.2.1 A better path


https://isaaccs.org/eq/dsa_search_32_v2

The A* path finding algorithm improves on the efficiency of Dijkstra’s al-


gorithm by introducing a heuristic element.
▶ Which of the following statements correctly describes the heuristic func-
tion?

⃝ The heuristic function provides an estimate of the cost of the path


between the start node and an interim node in the graph, and must
not under-estimate the costs.
⃝ The heuristic function provides an estimate of the cost of the path
between the start node and an interim node in the graph, and must
not over-estimate the costs.
⃝ The heuristic function provides an estimate of the cost of the path
between an interim node in the graph and the target node, and must
not over-estimate the costs.
⃝ The heuristic function provides an estimate of the cost of the path
between an interim node in the graph and the target node, and must
not under-estimate the costs.

236
28. PATHFINDING ALGORITHMS 237

28.2.2 Take a short cut


https://isaaccs.org/eq/dsa_search_24

The data for a graph is stored in an adjacency list as shown below.

Node Neighbours (node, weight)


A E,1 ; H,4
B D,4 ; F,2 ; H,2
C G,1 ; H,1
D B,4
E A,1 ; G,2
F B,2 ; G,2
G C,1 ; E,2 ; F,2
H A,4 ; B,2 ; C,1

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

28.2.3 Find the shortest path


https://isaaccs.org/eq/dsa_search_10

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).

Figure 28–4: Graph representing a university campus

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

11 Update the neighbour 's previous node to become


the current node

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

▶ What is the shortest path to G?

▶ What is the cost of the shortest path to G?


240 28. PATHFINDING ALGORITHMS

28.2.4 The visitor


https://isaaccs.org/eq/dsa_search_23

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.

Figure 28–5: Ali’s map.

▶ 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

28.2.5 Bag a bargain


https://isaaccs.org/eq/dsa_search_winter_08

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).

▶ What is the route?


28. PATHFINDING ALGORITHMS 243

28.2.6 Hurry up!


https://isaaccs.org/eq/dsa_search_33_v2

A delivery company makes uses of the A* algorithm to determine the fastest


route for a delivery van to reach a depot.

• Depots are stored as nodes in a graph.

• Road junctions are also stored as nodes and the weights represent the
cost of fuel to drive from node to node.

• The fuel consumption and cost is updated frequently by information


collected from each van’s navigation system.

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.

Node Neighbours (node, weight) Heuristic


A E,20 ; H,40 30
B D,45 ; F,20 ; H,60 35
C G,105 ; H,150 40
D B,45; G,10 10
E A,20 ; G,70 50
F B,20 ; G,60 45
G C,105 ; D,10; E,70 ; F,60 0
H A,40 ; B,60 ; C,150 100

A van needs to collect an item from Depot H and drop it at Depot G.


The value returned by the heuristic function provides an estimate of the
cost. The target node (G) is also shown in the table.
▶ What is the least amount of fuel needed for the driver to complete the
journey based on the current information? Write your answer as a single
integer value. It might be helpful to draw the graph rather than work directly
from the adjacency list.

▶ What is the route of the shortest path?


244 28. PATHFINDING ALGORITHMS

28.2.7 Where next?


https://isaaccs.org/eq/dsa_search_34_v2

A computer game uses the A* path finding algorithm to determine the


shortest path between the enemy and its target. All of the relevant game
components are stored as nodes in a graph and the weights represent the
distances between them, which are kept up to date as the game play pro-
gresses.
The path finding algorithm maintains a list of nodes yet to be visited; this
is called the unvisited list. At a particular point in the game, the state of
the list is as shown in the table below.
Unvisited list
node g-score f-score previous
C 75 80 B
H 30 140 E
L 90 95 B
N 60 75 K
P 35 85 K
R 85 90 J

▶ Which will it choose as the next node to visit?

⃝ 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.

29.2.1 Intractable problems


https://isaaccs.org/eq/dsa_cmplx_08

▶ What is an intractable problem?

⃝ 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

29.3.1 Time complexity of a binary search


https://isaaccs.org/eq/dsa_cmplx_04

▶ Which of the following is the time complexity of a binary search?

⃝ O(n)

⃝ O(log n)

⃝ O(n2 )

⃝ O(n log n)

29.3.2 Time complexity of a merge sort


https://isaaccs.org/eq/dsa_cmplx_05

▶ Which of the following is the time complexity of merge sort?

⃝ O(n)

⃝ O(n log n)

⃝ O(log n)

⃝ O(n2 )

29.3.3 Time complexity of a bubble sort


https://isaaccs.org/eq/dsa_cmplx_06

▶ Which of the following is the time complexity of a bubble sort?

⃝ O(log n)

⃝ O(n)

⃝ O(n2 )

⃝ O(n log n)
29. COMPLEXITY 247

29.4.1 Binary search


https://isaaccs.org/eq/dsa_cmplx_03

▶ What is the maximum number of comparisons that a binary search will


apply for an array of length 30.

29.4.2 Big O notation


https://isaaccs.org/eq/dsa_cmplx_01

▶ 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

29.4.3 Order of complexity


https://isaaccs.org/eq/dsa_cmplx_07

▶ 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).

30.1.1 Online piracy


https://isaaccs.org/eq/iot_legal_04

▶ Online piracy is the practice of downloading and distributing digital con-


tent without permission. What is the UK law that prevents people from
downloading games and distributing them without explicit consent?

⃝ The Copyright, Designs and Patents Act

⃝ The Stop Online Piracy Act

⃝ Computer Misuse Act

⃝ Data Protection Act

249
250 30. LEGISLATION

30.3.1 But it is such a cool game!


https://isaaccs.org/eq/iot_legal_03

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:

□ The website needs to be compliant with the Computer Misuse Act

□ The website needs to be compliant with the Data Protection Act

□ The website needs to be compliant with the General Data Protection


Regulation (GDPR)

□ The website needs to be compliant with the Copyright Designs and


Patents Act

30.3.2 Jail or no jail?


https://isaaccs.org/eq/net_sec_09

Computer-related legislation includes the Data Protection Act; the Copy-


rights, Designs and Patents Act; the Computer Misuse Act; and the Regu-
lation of Investigatory Powers Act. The Computer Misuse Act 1990 makes
certain activities, including ‘hacking’, illegal.
▶ Which statement best explains the legality of writing and distributing
malware?

⃝ Writing malware is not illegal, but using that malware to commit fur-
ther offences, such as fraud or extortion, is illegal.

⃝ Writing malware is a breach of the Computer Misuse Act 1990, which


is punishable by a maximum of 2 years in prison only.

⃝ Writing malware is only illegal if it results in threats to human life or


national security, in which case it is punishable by life imprisonment.

⃝ Writing malware is a breach of the Computer Misuse Act 1990, which


is punishable by a maximum of 2 years in prison, unless the malware
is used to commit fraud or extortion, for example, in which case the
maximum sentence becomes 10 years in prison.
30. LEGISLATION 251

30.3.3 It's the law


https://isaaccs.org/eq/net_sec_10

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.

⃝ This is illegal under the Computer Misuse Act.

⃝ This is illegal under the Regulation of Investigatory Powers Act.

⃝ This is not illegal.

▶ An individual makes unauthorised changes to the contents of a computer.

⃝ This is illegal under the Computer Misuse Act.

⃝ This is illegal under the Regulation of Investigatory Powers Act.

⃝ This is not illegal.

▶ The police demand that a suspect hands over keys to encrypted informa-
tion.

⃝ This is allowed under the Computer Misuse Act.

⃝ This is allowed under the Regulation of Investigatory Powers Act.

⃝ This is illegal.

▶ A company can gain access to their customers’ digital communications,


without informing the customer.

⃝ This is allowed under the Computer Misuse Act.

⃝ This is allowed under the Regulation of Investigatory Powers Act.

⃝ This is illegal.
252 30. LEGISLATION

30.3.4 Where is my USB flash drive?


https://isaaccs.org/eq/iot_legal_01

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:

⃝ The Copyright Designs and Patents Act


⃝ Computer Misuse Act
⃝ The Data Protection Act

30.3.5 You shouldn't even if you could!


https://isaaccs.org/eq/iot_legal_02

Robert works for a multinational company. The company has an organisa-


tional security policy, where the network management team is responsible
for ensuring that the employees only have the access privileges that are re-
quired for them to perform their jobs, and any unnecessary privileges are
restricted.
The privileges are classified in levels, where level 1 gives a basic access to
emails, the internet, and other services, and level 5 is only used by the
network administrators. The employees are not permitted to use or to access
any level of information outside their scope, which is why access privileges
are controlled in this way. Robert has level 3 privileges, whereas Marcos, his
colleague, has level 2 access.
On one occasion, Robert contravened the Data Protection legislation by leav-
ing his computer signed in and unattended, while he went to get a coffee.
30. LEGISLATION 253

Marcos used this opportunity to use Robert’s computer to extract informa-


tion that he was not permitted to access.
▶ Based on this scenario, select the computing legislation infringed by Mar-
cos.

⃝ The Data Protection Act


⃝ The Computer Misuse Act
⃝ No law was broken
⃝ Both legislations were broken
Programming fundamentals

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

▶ Which of the following statements relating to constants is true?

⃝ A constant is the same as a variable.

⃝ 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

31.1.2 True and False


https://isaaccs.org/eq/gcse_prog_20

In programming, you can make decisions using Boolean expressions that


evaluate as True or False inside conditional statements (IF, ELSEIF and ELSE).
This allows programs to respond differently to different input values.
Study the algorithm expressed in pseudocode below:
1 IF (X > 5) AND (Y < 7) THEN
2 PRINT (True)
3 ELSE
4 PRINT (False)
5 ENDIF

In this algorithm, a Boolean value (True or False) is printed depending on


the values of X and Y.
▶ Select the correct set of outputs for the values given for X and Y from the
options below.

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

31.1.3 Not in stock?


https://isaaccs.org/eq/gcse_prog_11

A fruit seller has created a program, shown in pseudocode below, to help


their customers check the level of fruit in stock.
1 PROCEDURE check_stock ()
2 fruit = INPUT (" What fruit would you like ?")
3 IF fruit == "Mango " THEN
4 level = "low"
5 ELSEIF fruit != " Banana " AND fruit != "Apple" THEN
6 level = "no"
7 ELSE
8 level = "good"
9 ENDIF
10 PRINT (" There is " + level + " stock ")
11 ENDPROCEDURE
▶ From the list of fruits that follows, select all the fruits which have a low
or good level of stock.

□ Apple
□ Peach
□ Orange
□ Banana
□ Mango

31.1.4 Which code will execute?


https://isaaccs.org/eq/gcse_prog_01

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

31.1.5 Your pizza is ready


https://isaaccs.org/eq/prog_pas_11

Anouska is writing a program to simulate the process of making a pizza.


The part of her program that is used to warm up the oven is shown in the
following pseudocode.
In the pseudocode the condition that controls the while loop is missing.

1 PROCEDURE warmer ( current_temperature , target_temperature )


2 PRINT (" warming up ..")
3 PRINT ( current_temperature )
4 WHILE #### missing code ####
5 current_temperature = get_oven_temperature ()
6 PRINT (".. ")
7 PRINT ( current_temperature )
8 ENDWHILE
9 PRINT (".. Oven ready .. ")
10 PRINT( target_temperature )
11 ENDPROCEDURE

▶ Select the while loop condition that will produce the output that is shown.

⃝ target_temperature - 2 > current_temperature

⃝ current_temperature < target_temperature - 1

⃝ target_temperature > current_temperature

⃝ current_temperature <= target_temperature


258 31. PROGRAMMING CONCEPTS

31.1.6 Select the variable


https://isaaccs.org/eq/prog_concepts_01

Read the description of each identifier in the table below and decide whether
the identifier denotes a variable or a constant.

Identifier Example value Purpose Variable / constant


To store a value to
be applied to all
tax 0.2
items sold via the
company website.
To be applied as an
accelerating force
gravity 9.8 to all objects in a
physics-based game
or simulation.
To store the current
score 10200 score of a player in
a quiz.
To be checked
whenever a user
submits a new
password to be
min_length 12 stored in a web-
site. All passwords
must have a min-
imum length of 12
characters.
31. PROGRAMMING CONCEPTS 259

31.1.7 Find the data type match


https://isaaccs.org/eq/prog_concepts_02

Read the description of each variable in the table below and decide on the
best data type to implement each variable.

Variable name Example value Purpose Data type


The age of an in-
years_of_age 27 dividual person in
years.
A telephone num-
telephone +441234567890
ber.
A random decimal
number 0.8923 number between 0
and 1.
A person’s date of
date_of_birth 2002-25-08
birth.
The temperature
temperature 24.7 recorded in degrees
Celsius every hour.

31.1.8 Weather advice


https://isaaccs.org/eq/prog_concepts_04

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

31.1.9 What is the output?


https://isaaccs.org/eq/prog_concepts_03

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)

▶ Write the value that will be displayed on the screen.


31. PROGRAMMING CONCEPTS 261

31.1.10 Find the missing condition


https://isaaccs.org/eq/prog_concepts_05_v2

The program below is used to determine whether a person is eligible for


admission to a professional course. A person will only be eligible if the
following is true:

• Their mark in Maths is 65 or higher, and they have at least 50 marks


in either Physics or Chemistry.
• Alternatively, they could have higher than 70 marks in Computer_Science,
but they cannot have lower than 50 marks in Maths.
• The Total in all four subjects has to be higher than or equal to 160
marks.

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

▶ Which of the below statements is the correct missing condition?

⃝ ((Maths >= 65 AND (Physics >= 50 OR Chemistry >= 50))OR (Computer_Science


> 70 AND Maths >= 50))AND Total >= 160

⃝ Maths >= 65 AND (Physics OR Chemistry >= 50)OR (Computer_Science


> 70 AND NOT(Maths < 50))AND Total >= 160

⃝ (Maths >= 65 AND Physics >= 50 OR Chemistry >= 50)OR (Computer_Science


> 70 AND NOT(Maths < 50)AND Total >= 160)

⃝ (Maths > 65 AND (Physics > 50 OR Chemistry > 50))AND (Computer_Science


>= 70 AND Maths > 50)OR Total >= 160
262 31. PROGRAMMING CONCEPTS

31.1.11 How many loops?


https://isaaccs.org/eq/prog_concepts_06

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

31.3.1 List the coordinates


https://isaaccs.org/eq/gcse_prog_02

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

31.3.2 A trace table


https://isaaccs.org/eq/gcse_prog_14

A student has designed an algorithm that is shown in pseudocode below.


The algorithm uses a condition-controlled loop.

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

The student traces the algorithm for a user input of 16.


▶ Which of the following options shows a trace table with the correct values?

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

31.3.3 Odd or even?


https://isaaccs.org/eq/gcse_prog_05

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

▶ What will be printed when i reaches 8 in the loop?

⃝ 8
⃝ blue
⃝ 0
⃝ red
266 31. PROGRAMMING CONCEPTS

31.3.4 Save the date!


https://isaaccs.org/eq/prog_concepts_09

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 Monday Tuesday Wednesday Thursday Friday


Week 1 C X X
Week 3 C X
Week 4 X X C C

Jacob Monday Tuesday Wednesday Thursday Friday


Week 1 C X X
Week 3 C X C
Week 4 X C

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

31.3.5 At what cost?


https://isaaccs.org/eq/prog_concepts_12

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?

31.3.6 No pudding for me


https://isaaccs.org/eq/prog_concepts_winter_04

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

1 bill = FLOAT( INPUT (" Enter amount of bill "))


2 people = INT(INPUT (" Enter number of people "))
3 pudding_eaters = INT(INPUT (" How many people had pudding ? "))
4 tip = bill * 0.125
5 total = bill + tip
6 units = ( people * 3) + pudding_eaters
31. PROGRAMMING CONCEPTS 269

7 basic = format (( total / units) * 3, 2)


8 extra = format (( total / units) * 4, 2)
9 PRINT (" If you had a pudding , you should pay £" + STR(extra))
10 PRINT (" If you did not have a pudding , please pay £" +
STR(basic))

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)?

31.3.7 Party time!


https://isaaccs.org/eq/prog_concepts_winter_06

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

31.3.8 Fibonacci calling


https://isaaccs.org/eq/prog_pas_13

In mathematics, the Fibonacci numbers form a sequence called the Fibonacci


sequence.
The first two numbers in the sequence are 0 and 1, then each subsequent
number is the sum of the previous two numbers in the sequence.
Each Fibonacci number can be represented as Fn where n is the position of
the number in the sequence. The first two numbers in the sequence can be
expressed as:
F1 = 0, F2 = 1
The numbers after F2 can then be expressed as:
Fn = Fn−1 + Fn−2 , where n > 1
For example:
F3 = F2 + F1 , which is 1 + 0. So F3 = 1
F4 = F3 + F2 , which is 1 + 1. So F4 = 2
F5 = F4 + F3 , which is 2 + 1. So F5 = 3
F6 = F5 + F4 , which is 3 + 2. So F6 = 5
Malika is designing a program to display the first n Fibonacci numbers and
has written the following pseudocode:
1 PROCEDURE calculate_fibonacci_sequence (n)
2 term_1 = 0
3 term_2 = 1
4 IF n == 1 THEN
5 print (" F1 = 0")
6 ELSEIF n == 2 THEN
7 PRINT (" F1 = 0")
8 PRINT (" F2 = 1")
9 ELSEIF n > 2:
10 PRINT (" F1 = 0")
11 PRINT (" F2 = 1")
12 FOR i = <<<missing value >>> TO n
13 next_term = term_1 + term_2
14 PRINT ("F" + STR(i) + " = " + STR( next_term ))
15 term_1 = term_2
16 term_2 = ### incomplete statement
17 NEXT i
18 ENDIF
19 ENDPROCEDURE
20
21 sequence_length = INPUT (" Enter the length of the Fibonacci
Number sequence to be displayed : ")
31. PROGRAMMING CONCEPTS 271

22 sequence_length = INT( sequence_length )


23 PRINT (" The sequence is ... ")
24 calculate_fibonacci_sequence ( sequence_length )

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

▶ Within the FOR loop, there is an incomplete statement. What should be


assigned to term2 ?

⃝ term_1
⃝ n
⃝ i
⃝ next_term
272 31. PROGRAMMING CONCEPTS

31.3.9 Find the value of the variable


https://isaaccs.org/eq/prog_concepts_07

The array puzzle has the following values assigned to it:


puzzle = [8, 9, 3, 5, 9, 3]
1 number = 9
2 answer = -1
3 FOR i = 0 TO LEN( puzzle ) - 1
4 IF puzzle [i] == number THEN
5 answer = i
6 ENDIF
7 NEXT i

number answer i number answer i

▶ What is the value of the variable answer once the code has finished ex-
ecuting?
31. PROGRAMMING CONCEPTS 273

31.3.10 Which number is this?


https://isaaccs.org/eq/prog_concepts_10

The variable number has a value of 78.


1 digit = 0
2 result = ""
3 WHILE number != 0
4 digit = number MOD 2
5 number = number DIV 2
6 result = STR( digit ) + result
7 ENDWHILE
8 PRINT( result )

▶ 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.

32.1.1 How many students?


https://isaaccs.org/eq/gcse_prog_18

In a college, two groups of students were created. All students in Group 1


are studying Economics and all students in Group 2 are studying Computer
Science. English and Maths are mandatory subjects, so Group 1 and Group
2 also study English and Maths.
Mr Patel (the English teacher) asked Mrs Smith (the Computer Science
teacher) how many students are there in Group 1 and 2 when the groups are
added together.
Mrs Smith loves to challenge people, so she gave the algorithm below as her
answer and told Mr Patel to use it to find the the number of students.

• group1 is an array of students with indexes from 0 to 17

• group2 is an array of students with indexes from 0 to 19

1 FUNCTION total_students (group1 , group2 )


2 total = LEN( group1 ) + LEN( group2 )
3 RETURN total
4 ENDFUNCTION

▶ What answer will be given by running the pseudocode provided by Mrs


Smith?

274
32. STRING HANDLING 275

32.1.2 Number plate substrings


https://isaaccs.org/eq/gcse_prog_03

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)

▶ What will Nitin’s program print out?

32.1.3 Locate the word


https://isaaccs.org/eq/prog_string_04

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

32.1.4 Board game stash


https://isaaccs.org/eq/prog_string_03

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

• The digits are entered in ascending order

• In English, the vowels are “a”, “e”, “i”, “o” and “u”

▶ What is the passcode to access Ross’s board game stash?

32.3.1 Compliment generator


https://isaaccs.org/eq/prog_string_01

Philip wants to create a program to generate compliments for his friends.


His program begins like this:
1 compliments = [" funny", "hard - working ", " clever ", " awesome "]
2 chosen_number = RANDOM_INT (0, LEN( compliments ) -1)
3 choice = compliments [ chosen_number ]
4 PRINT ("I think you are really ")

For example, one random output might be:


I think you are really hard-working
▶ What code should Philip insert to make the program display a random
compliment?
32. STRING HANDLING 277

32.3.2 Spelling Bee


https://isaaccs.org/eq/prog_string_02

Carmen is writing a Spelling Bee program. In a Spelling Bee, contestants


are given a word to spell, and they must say each letter and then repeat the
word. For example, given the word ‘dog’, a contestant would say:
Please enter the word to spell
> dog
The word is dog
d
o
g
dog

▶ Arrange the following program statements in the correct order to create


a program that would produce the above output. Assume that each output
statement displays on a new line. Not all statements are required.

□ PRINT("Please enter
the word to spell")

□ word = INPUT()

□ PRINT("The word is "


+ word)

□ 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

32.3.3 A piece of pizza


https://isaaccs.org/eq/prog_string_06

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.

□ PRINT("Enter the cost of the pizza: £")

□ cost = INPUT()

□ float_cost = FLOAT(cost)

□ per_person_cost = float_cost / 3.0

□ per_person_string = STR(per_person_cost)

□ PRINT("Each person must pay £" + per_person_string)

□ float_cost = INT(cost)

□ per_person_cost = FLOAT(per_person_cost)
32. STRING HANDLING 279

32.3.4 A capital case


https://isaaccs.org/eq/prog_string_07

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

32.3.5 A troublesome student


https://isaaccs.org/eq/prog_string_10

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

32.3.6 I can see you


https://isaaccs.org/eq/prog_string_09

Nadia has received a weird message:


I cAn sEe yOu NAdIa - hA Ha hA
Nadia suspects the message is from her friend Noah, who is messing around
instead of doing his Computer Science homework. To send a similar message
back to him, she writes a program that converts every other letter of the
phrase she enters into a capital.
Here is the program Nadia has written:
1 phrase = "Be quiet Noah"
2 finished = ""
3
4 FOR i = 0 TO LEN( phrase )
5 IF i MOD 2 == 0
6 finished = finished + phrase [i]
7 ELSE
8 finished = finished + CHR( ASC( phrase [i]) - 32)
9 ENDIF
10 NEXT i
11
12 PRINT ( finished )

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

32.4.1 Do you know the muffin man?


https://isaaccs.org/eq/prog_string_05

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.

33.1.1 Return a value


https://isaaccs.org/eq/gcse_prog_13

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

33.1.2 Split the bill


https://isaaccs.org/eq/gcse_prog_09

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?

⃝ She has forgotten to call the subroutine.


⃝ She has called the subroutine correctly, but has not displayed the re-
turn value.
⃝ She has put the arguments the wrong way round when calling the
subroutine.
⃝ She has got the bill calculation wrong.

33.1.3 Advantages of subroutines


https://isaaccs.org/eq/prog_sub_02

▶ Select the statement that is true.

⃝ If a subroutine is defined, then it must be executed at some point in


the program.
⃝ Subroutines are always defined by the user.
⃝ Procedures allow values to be returned to the procedure call.
⃝ Using subroutines always makes a program faster to execute.
⃝ A subroutine can be added to a library and re-used by different pro-
grams.
33. SUBROUTINES 285

33.1.4 Fix the calculator


https://isaaccs.org/eq/gcse_prog_10

George is writing a calculator program. The code he has written so far, is


shown in the following pseudocode:
1 PROCEDURE multiply (value_a , value_b )
2 PRINT ( value_a * value_b )
3 ENDPROCEDURE
4
5 PROCEDURE main ()
6 first = INPUT (" Enter the first number : ")
7 first = INT(first)
8 second = INPUT (" Enter the second number : ")
9 second = INT( second )
10 result = multiply (first , second )
11 PRINT (" The result is " + result )
12 ENDPROCEDURE

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

▶ Why does the program produce this output?

⃝ He has not specified a return value from the subroutine.


⃝ The print statement on line 2 caused an error.
⃝ He didn’t call the subroutine correctly.
⃝ He forgot to save the return value from the subroutine into a variable.
286 33. SUBROUTINES

33.1.5 Passing parameters by reference and by value


https://isaaccs.org/eq/prog_sub_04

▶ Read the statements about passing parameters either by value or by ref-


erence, and select the statement that is the odd one out:

⃝ Can benefit programming languages that do not support returning


multiple values.
⃝ A copy of the original value is made and passed to the parameter.
⃝ A pointer is used to retrieve and update the value of a variable.
⃝ The memory address of the original variable is used.

33.1.6 Calling subroutines


https://isaaccs.org/eq/prog_sub_01_v2

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

33.1.7 Subroutine Interface


https://isaaccs.org/eq/prog_sub_07_v2

1 PROCEDURE calcuLate_percentage (score , max_score )


2 percentage = ( max_score / 100) * score
3 PRINT ( percentage )
4 ENDPROCEDURE

▶ Choose the best statement to describe what is meant by a subroutine


interface, including an example from the pseudocode given.

⃝ A subroutine interface is the method which allows local variables to be


visible in all parts of a program. An example of an interface variable
is percentage.

⃝ A subroutine interface is the method of passing data in and out of a


subroutine through the use of parameters. For the subroutine above,
percentage is an example of a subroutine interface parameter.

⃝ A subroutine interface is the method of passing data in and out of a


subroutine through the use of parameters. For the subroutine above,
the subroutine interface is the parameters score and max_score.

33.1.8 Keeping it local


https://isaaccs.org/eq/prog_sub_10

▶ 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.

□ The value of a local variable is preserved in memory until the whole


program has stopped running.

□ Local variables reduce the overall complexity of debugging program


code

□ Local variable names can be repeated within different subroutines

□ When you use local variables, you do not have to worry that they will
be changed by code in other subroutines

□ Local variables allow data to be shared between subroutines


288 33. SUBROUTINES

33.1.9 Subroutines for a CRM


https://isaaccs.org/eq/prog_sub_11

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.

33.3.1 Stacking up trouble


https://isaaccs.org/eq/prog_recurs_01

▶ A stack frame is created whenever a subroutine is called. Which of the


following statements best describe the contents of a stack frame?

⃝ 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

33.3.2 Subroutines with multiple parameters


https://isaaccs.org/eq/prog_sub_03_v2

▶ 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 ()

33.3.3 Scope of local and global variables


https://isaaccs.org/eq/prog_sub_08_v2

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.3.4 Identify yourself


https://isaaccs.org/eq/prog_sub_12

Examine the following code:


1 PROCEDURE display_menu ()
2 PRINT ("1 - Weather ")
3 PRINT ("2 - Time ")
4 PRINT ("3 - Exit ")
5 ENDPROCEDURE

▶ What is the identifier of the subroutine shown?

▶ Which of these statements about a subroutine is false?

⃝ A subroutine is a named block of code

⃝ A subroutine identifier should reflect the purpose of the subroutine

⃝ Subroutines will run in the order they are defined

⃝ A subroutine should carry out a specific task

33.3.5 Badger mushroom


https://isaaccs.org/eq/prog_sub_13

Examine the following piece of code:


1 PROCEDURE badger ()
2 PRINT (" Badger ")
3 ENDPROCEDURE
4
5 PROCEDURE mushroom ()
6 PRINT (" Mushroom ")
7 ENDPROCEDURE
8
9 PROCEDURE song ()
10 FOR i FROM 1 TO 12
11 badger ()
12 next i
13 mushroom ()
14 mushroom ()
15 ENDPROCEDURE
33. SUBROUTINES 291

▶ How many subroutines are defined within this program?

▶ How many times is the subroutine badger called?

▶ How many times is the subroutine mushroom called?

▶ How many times is the subroutine song called?

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

33.4.2 Blast off!


https://isaaccs.org/eq/prog_sub_15

Destiny has written a program that uses recursion to generate a countdown


for a rocket launch.
1 PROCEDURE main ()
2 blast_off (5)
3 ENDPROCEDURE
4
5 PROCEDURE blast_off (n)
6 IF n == 0 THEN
7 PRINT (" Blast off !")
8 ELSE
9 PRINT (n)
10 blast_off (n -1)
11 ENDIF
12 ENDPROCEDURE

▶ How many times is the procedure blast_off called in this program?

⃝ 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.

34.1.1 Newline characters


https://isaaccs.org/eq/prog_files_02

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 ,

I am afraid Johnny was not able to bring his homework in


today as his dog has eaten it.

He is very sorry , and so is Kipper .

Kind regards ,’
Johnnys Mum

▶ How many newline characters are in the raw data of the text file?

293
294 34. FILE HANDLING

34.1.2 Identifying text files


https://isaaccs.org/eq/prog_files_01

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

▶ How many text files are stored in the folder?

34.1.3 Identifying binary files


https://isaaccs.org/eq/prog_files_06

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

34.3.1 Output data from a file


https://isaaccs.org/eq/prog_files_03

The contents of a text file called friends.txt are as follows:


Clare
Ben
Maria
Carmen
Neil

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.

34.3.2 File handling modes


https://isaaccs.org/eq/prog_files_04

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?

⃝ The data, but in binary format.


⃝ The data, as it was before she ran the program.
⃝ Her data has been duplicated.
⃝ No data.
296 34. FILE HANDLING

34.3.3 Writing multiple lines


https://isaaccs.org/eq/prog_files_05

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

34.3.4 A day at the zoo


https://isaaccs.org/eq/prog_files_07

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

1 zoo_data = OPEN_READ (" zooanimals .txt ")


2 all_data = zoo_data . READ_ALL ()
3 animal1 = all_data [5]
4 animal2 = all_data [8]
5 zoo_data . CLOSE ()
6
7 zoo_data = OPEN_APPEND (" zooanimals .txt ")
8 zoo_data . WRITE_LINE (" Gorilla ")
9 zoo_data . WRITE_LINE (" Eagle ")
10 zoo_data . WRITE_LINE (" Tasmanian devil ")
11 zoo_data . CLOSE ()
12
13 zoo_data = OPEN_READ (" zooanimals .txt ")
14 all_data = zoo_data . READ_ALL ()
15 animal3 = all_data [11]
16 zoo_data . CLOSE ()
17
18 PRINT ( animal1 )
19 PRINT ( animal2 )
20 PRINT ( animal3 )

▶ What will be output from the program?


298 34. FILE HANDLING

34.3.5 The shopping list


https://isaaccs.org/eq/prog_files_08

The contents of a file named ’shopping.txt’ is as follows:

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

⃝ 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.

35.2.1 One after another


https://isaaccs.org/eq/prog_recurs_05

Fibonacci numbers are a number sequence that starts:


0, 1, 1, 2, 3, 5, 8, 13, …
Each Fibonacci number is the sum of the previous two numbers.
A recursive subroutine has been written to output the nth Fibonacci num-
ber. For example, running the subroutine with the argument value 7, would
return 13 (as 13 is the 7th Fibonacci number).
▶ Fill in the gaps in the code

1 FUNCTION fibonacci (n)


2 IF n == 0 THEN
3 RETURN ___________________
4 ELSEIF n == 1 THEN
5 RETURN ___________________
6 ELSE
7 RETURN ___________________
8 ENDIF
9 ENDFUNCTION

299
300 35. RECURSION

35.2.2 Up and down


https://isaaccs.org/eq/prog_recurs_03

A recursive subroutine has been written as follows:


1 FUNCTION do_something (n)
2 IF n == 1 THEN
3 RETURN 0
4 ELSE
5 RETURN 1 + do_something (n DIV 2)
6 ENDIF
7 ENDFUNCTION

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

35.2.3 Needle in a haystack


https://isaaccs.org/eq/prog_recurs_08

A recursive subroutine has been written as follows:


1 FUNCTION power (n, exp)
2 IF exp == 0 THEN
3 RETURN 1
4 ELSE
5 RETURN n * power (n, exp -1)
6 ENDIF
7 ENDFUNCTION

▶ What is the base case in this subroutine?


302 35. RECURSION

35.3.1 Keep counting


https://isaaccs.org/eq/prog_recurs_10

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.

1 PROCEDURE search (surname , scores , first , last)


2 IF first > last THEN
3 PRINT (" Not found ")
4 ELSE
5 mid = (first + last) DIV 2
6 IF scores [mid ]. surname == surname THEN
7 PRINT ( scores [mid ]. score)
8 ELSEIF surname > scores [mid ]. surname THEN
9 first = mid + 1
10 search (surname , scores , first , last)
11 ELSE
12 last = mid - 1
13 search (surname , scores , first , last)
14 ENDIF
15 ENDIF
16 ENDPROCEDURE

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

surname scores first last mid

Answer:

35.4.1 What's the point?


https://isaaccs.org/eq/prog_recurs_07

▶ A recursive algorithm can always be written to use iteration (instead of


recursion). What are the advantages of using recursion? Select all that
apply.

□ There are usually fewer lines of code

□ Problems that are naturally expressed by recursion are easier to code

□ Recursive algorithms are easier to trace

□ Recursive algorithms use less memory


304 35. RECURSION

35.4.2 Round and round


https://isaaccs.org/eq/prog_recurs_02

A recursive subroutine has been written as follows:


1 FUNCTION do_something (x, y)
2 IF x == 1 THEN
3 RETURN y
4 ELSE
5 RETURN do_something (x-1, x+y)
6 ENDIF
7 ENDFUNCTION

▶ 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

35.4.3 A monkey puzzle?


https://isaaccs.org/eq/prog_recurs_06

A recursive subroutine has been written in high-level pseudocode, as follows:


1 PROCEDURE traverse (tree)
2 IF tree != Null THEN
3 traverse (tree. RightChild ())
4 PRINT(tree.node. get_value ())
5 traverse (tree. LeftChild ())
6 ENDIF
7 ENDPROCEDURE

▶ What variant of a standard algorithm does it implement?

35.4.4 This has value


https://isaaccs.org/eq/prog_recurs_09

A recursive subroutine has been written as follows:


1 FUNCTION sum_to_n (n:BYVAL )
2 IF n == 1 THEN
3 RETURN 1
4 ELSE
5 RETURN n + sum_to_n (n -1)
6 ENDIF
7 ENDFUNCTION

▶ Why must the argument be passed by value (and not by reference)?

⃝ A value is used so that the subroutine knows that n is a number

⃝ If a shared reference is used, you will encounter ‘stack overflow’

⃝ 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

35.4.5 Back and forth


https://isaaccs.org/eq/prog_recurs_04

A recursive subroutine has been written as follows:


1 FUNCTION do_something (n)
2 IF n != 0 THEN
3 do_something (n DIV 2)
4 PRINT (n MOD 2)
5 ENDIF
6 ENDFUNCTION

The subroutine must be passed a whole number as an argument (e.g. 57).


▶ What problem does this subroutine solve?

⃝ Converts a positive number to negative (2’s complement)


⃝ Converts a denary number into binary
⃝ Calculates the square root of a number
⃝ Rounds the number to 2 decimal places
36 Integrated Development Environments
(IDEs)
Many programmers use an integrated development environment (IDE),
which has a range of features designed to help the programmer develop their
program code. Most IDEs will include facilities such as syntax highlighting,
linting, and debugging tools such as breakpoints. It is common for an IDE
to allow code to be executed from inside the environment, with the help of
an external interpreter or compiler.

36.1.1 Beware the IDEs of March


https://isaaccs.org/eq/prog_softeng_11

Most programmers make use of an IDE when working on program code.


▶ Which of the following statements most accurately describes an IDE?

⃝ A text editor that can open binary files.


⃝ Development software that includes a source-code editor and may in-
clude a translator.
⃝ Software that checks that the code you have written is standards-
compliant.
⃝ Software that allows you to work collaboratively with other developers.

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

▶ Select one statement that describes why the principle of encapsulation


is important for the design of OOP programs.

⃝ It enables the creation of objects with specific states and behaviour.

⃝ It ensures that child classes can use the attributes and methods of the
parent class.

⃝ It allows child classes to behave differently to the parent class.

⃝ It ensures that any interaction with an object is only allowed via its
public interface.

308
37. OBJECT-ORIENTED PROGRAMMING 309

37.1.2 OOP concepts


https://isaaccs.org/eq/prog_oop_01

OOP is a programming paradigm that differs from procedural programming.


The statements that follow attempt to describe some core concepts of OOP
but only two of the statements are accurate.
▶ Select the two accurate statements from the list provided.

□ A child class can alter the behaviour of a method that it has inherited
from the parent class.

□ A class is a series of step-by-step instructions that solve a problem.

□ Multiple instances of a class can be created, each with different values


for its attributes.

□ To solve a problem, a program is divided into smaller parts called


subroutines.

□ A parent class inherits all of the attributes and methods of the child
classes that it has.

□ Access to the data of an object can be restricted using the personal


and public access modifiers.

37.1.3 Constructor method


https://isaaccs.org/eq/prog_oop_03

▶ What is a constructor method?

⃝ A method that is used to create a child class from the definition of a


parent class
⃝ A method that is used to set the values of private attributes outside
the class in which they were defined
⃝ A method that is used to get the values of public attributes outside
the class in which they were defined
⃝ A method that is used to instantiate an object, allowing for attributes
to be initialised if desired
310 37. OBJECT-ORIENTED PROGRAMMING

37.1.4 A neat rectangle


https://isaaccs.org/eq/prog_oop_12

Steve is learning object-oriented programming. He wants to write some code


that will draw a simple rectangle, so he has created a class called Rectangle,
with two attributes: height and width and a method draw.
The draw method will display a rectangle of stars of a given height and width.
For example, a rectangle of height 7 and width 10, will look like this:

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 ()

In the pseudocode shown above, a new Rectangle object is instantiated and


its draw method is called. However, the line of code that instantiates the
object has missing arguments.
▶ Can you identify what they should be?
312 37. OBJECT-ORIENTED PROGRAMMING

37.1.5 Interstellar
https://isaaccs.org/eq/prog_oop_09

Jemma has extended a game that


she is developing for her younger
brother that takes place in space. A
description of the Planet class that
she has defined in her program is
presented here.

The Galaxy class contains a planets


array that stores the objects of
type Planet that are used in
the game. It also contains a
show_habitable_planets method
that searches the planets array and
shows the number of planets that are
habitable.
1 CLASS Galaxy
2 PRIVATE Planet planets [15] # Array of type Planet
3
4 PUBLIC FUNCTION show_habitable_planets ()
5 total_habitable = 0 # Number of habitable planets
6 FOR count = 0 TO LEN( planets ) - 1
7 IF …………………………………… THEN # Missing code
8 total_habitable = total_habitable + 1
9 ENDIF
10 NEXT count
11 RETURN total_habitable
12 ENDFUNCTION
13 ENDCLASS

▶ 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

37.1.6 Spaced out


https://isaaccs.org/eq/prog_oop_08_v2

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.

⃝ mars = NEW Planet(mars.set_distance_sun(227.9), 2, True, 'red')


⃝ Planet = NEW mars(True, 2, 227.9, red)
⃝ mars = NEW Planet(227.9 million km, 2, True, red)
⃝ mars = NEW Planet(227.9, 2, True, 'red')
314 37. OBJECT-ORIENTED PROGRAMMING

37.2.1 Electric polymorphic cars


https://isaaccs.org/eq/prog_oop_11

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

37.3.1 Lonely rider


https://isaaccs.org/eq/prog_oop_10

Maxime is programming a horse riding simulation where a rider travels to


various historic castles in the UK with different breeds of horses. Each breed
of horse can travel at a different speed, for example, a Thoroughbred can travel
at 88 km/h, a QuarterHorse at 70 km/h, and an Appaloosa at 65 km/h. She has
created three classes for her program.

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.

1 PUBLIC FUNCTION travel_time ( target_castle , current_horse )


2 IF skill > 8 AND target_castle . get_barriers () == False
3 time_required = ________________________
4 ELSE
5 # It takes double the time
6 ENDIF
7
8 RETURN time_required
9 ENDFUNCTION

▶ Based on the implementation of the travel_time method, what is the


time required to reach the castle if the below set of objects are used in the
simulation? Give your answer as a number.
1 my_castle = new Castle (130 , True)
2
3 my_appaloosa = new Horse (65)
4
5 my_rider = new Rider (9)
318 37. OBJECT-ORIENTED PROGRAMMING

37.4.1 Access to attributes


https://isaaccs.org/eq/prog_oop_07_v2

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

37.4.2 Animal class


https://isaaccs.org/eq/prog_oop_05

Marina is programming an application that aims to help students revise for


their Biology lessons. A part of the definitions of the Animal and Frog classes
of the program is presented below.
1 CLASS Animal
2 PRIVATE habitat : String
3
4 PUBLIC FUNCTION get_habitat ()
5 RETURN habitat
6 ENDFUNCTION
7
8 PUBLIC PROCEDURE display_habitat ()
9 PRINT (" My natural habitat is " + get_habitat ())
10 ENDPROCEDURE
11 ENDCLASS
12
13 CLASS Frog EXTENDS Animal
14 PRIVATE secondary_habitat : String
15
16 PUBLIC FUNCTION get_secondary_habitat ()
17 RETURN secondary_habitat
18 ENDFUNCTION
19
20 PUBLIC PROCEDURE display_habitat ()
21 PRINT ("I am an amphibian , I live in the " +
get_habitat () + " and also in the " +
get_secondary_habitat ())
22 ENDPROCEDURE
23 ENDCLASS
▶ Select the statement that correctly describes OOP concepts that have
been applied in this example.

⃝ 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.

38.4.1 A GUI problem


https://isaaccs.org/eq/prog_gui_10

▶ Select all the statements which are true about a program with a GUI.
Half of the statements provided are false.

□ The order the code is executed in is determined by ‘events’ which are


triggered by functions

□ You should avoid using infinite loops with a GUI

□ You must have a mouse in order to use a GUI

□ The order the code is executed in is determined by ‘events’ which are


triggered by the user

□ You can select multiple items from a set of checkboxes

□ You can select multiple items from a set of radio buttons

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.

39.1.1 Unusual events


https://isaaccs.org/eq/prog_softeng_13

Sometimes, something can happen while a program is executing that causes


the program to crash. An exception handler may be used in this situation.
▶ What is an exception handler?

⃝ A procedure that will close down the program smoothly when an ex-
ception is encountered.

⃝ A procedure that will be called and run when an exception is en-


countered. Once the exception has been dealt with, normal program
flow resumes.

⃝ 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

39.1.2 It's not real


https://isaaccs.org/eq/prog_pas_08

Pseudocode is often used to express algorithms.


▶ Why is pseudocode used?

□ It allows all constructs that are commonly used to build programs to


be expressed.

□ It is really hard to write so it makes for very challenging exam ques-


tions.

□ It is a clear and unambiguous method of specifying the logic of an


algorithm.

□ It allows an algorithm to be expressed in a way that is independent of


any specific programming language.

39.3.1 How does it end?


https://isaaccs.org/eq/prog_pas_02

A programmer has specified a program in pseudocode. The method .length


returns the number of items in the list.
▶ If list 1 is [10, 2, 1, 7, 5] and list 2 is [11, 2, 3, 8, 5], what value will
be returned by the program when it is called as follows: exceeds (list1,
list2)?

1 FUNCTION exceeds (nums1 , nums2)


2 last = -1
3 FOR i = 0 TO LEN( nums1) - 1
4 IF nums1[i] < nums2[i] THEN
5 last = i
6 ENDIF
7 NEXT i
8 RETURN last
9 ENDFUNCTION

Answer:
324 39. PROGRAM DESIGN

39.3.2 Find the answer


https://isaaccs.org/eq/prog_pas_06_v2

A student has specified an algorithm using a flowchart. She wants to specify


the same algorithm using pseudocode.
▶ Write the pseudocode statements into the same order as that expressed
by the flowchart.

• 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

39.3.3 It's all Greek to me


https://isaaccs.org/eq/prog_pas_09

An ancient Greek mathematician wrote an algorithm to tackle a common


problem. This is his algorithm in pseudocode.
1 FUNCTION g(n1 , n2)
2 f = n1
3 WHILE n2 != 0
4 temp = n2
5 n2 = f MOD n2
6 f = temp
7 ENDWHILE
8 RETURN f
9 ENDFUNCTION

▶ 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

39.3.4 Trace the algorithm


https://isaaccs.org/eq/prog_pas_10

A student has written the following subroutine in response to a homework


challenge.
1 FUNCTION c(num)
2 out = ""
3 WHILE num > 0
4 r = STR(num MOD 2)
5 out = r + out
6 num = num DIV 2
7 ENDWHILE
8 RETURN out
9 ENDFUNCTION

▶ Dry run the algorithm for the call c(20).

num out r

▶ What value is returned?


328 39. PROGRAM DESIGN

39.3.5 I like to move it, move it


https://isaaccs.org/eq/prog_pas_04

A student is designing an algorithm to move all of the elements of an array


(numbers) by one place. Each element will move to the next (adjacent) slot
and the last element will be moved to the first position of the array.
For example, if numbers looks like this before processing:

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

The student has written the algorithm in pseudocode.


▶ What should she add at the places marked to ensure that her code works
as intended?

1 PROCEDURE move( numbers )


2 current = numbers [0]
3 FOR i = ______________ TO LEN( numbers ______________ )
4 temp = numbers [i]
5 numbers [i] = current
6 current = temp
7 NEXT i
8 numbers [0] = temp
9 ENDPROCEDURE

The method .length returns the number of items in the list.


39. PROGRAM DESIGN 329

39.3.6 Precondition
https://isaaccs.org/eq/prog_pas_03

A programmer has specified a program in pseudocode. The method .length


returns the number of items in a list.
1 FUNCTION tally (nums1 , nums2)
2 count = 0
3 FOR i = 0 TO (LEN( nums1) - 1)
4 IF nums1[i] < nums2[i] THEN
5 count = count + 1
6 ENDIF
7 NEXT i
8 RETURN count
9 ENDFUNCTION

▶ Which precondition must be specified for the program?

⃝ Both lists must be equal in length.


⃝ The values in both lists must be ordered low to high.
⃝ The values in both lists must be numbers.
⃝ List nums1 must be shorter or equal in length to nums2.
40 Testing
Before a piece of software can be used, it needs to be tested. Some testing
is done in an ad hoc way by the programmer as the program develops, and
is called debugging. Other testing is more structured and involves a test
plan being written and the software being tested with a variety of data to
check that the outputs are as expected. Black box testing only concerns
the inputs and outputs of a program, not how the internal parts of the
program work, whereas white box testing requires examining each line of
code in detail in order to check that the logic works as intended.

40.1.1 A white box


https://isaaccs.org/eq/prog_softeng_04

The statements below provide a definition of white box, black box, alpha,
and beta testing.
▶ Which of the statements best describes white box testing?

⃝ Testing functionality without knowledge of the inner workings of the


code
⃝ Testing algorithms to ensure that they do what they were designed to
do in all circumstances
⃝ Testing by the programmers prior to showing the system to the end
user
⃝ Testing by end users to ensure that the system meets requirements and
is functional

330
40. TESTING 331

40.1.2 What do you expect?


https://isaaccs.org/eq/prog_softeng_02

A student has been given the following specification for a subroutine to


calculate handling costs for a business.

Handling costs are calculated at 7.5% of the total cost of goods


ordered, rounded up to the nearest 50p. If the total cost of
goods ordered is under £5, a flat rate of 50p is charged. There
is a minimum order value of £2.

▶ 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

Test # Purpose Data


1 Test that the charge for handling costs 2.00 2.50 4.99 5.00
is calculated correctly 7.99 20.00

Data set B

Test # Purpose Data


1 Test that the charge for handling costs 2.00 2.50 5.00 5.01
is calculated correctly 7.99 20.00

Data set C

Test # Purpose Data


1 Test that the charge for handling costs 2.01 2.50 4.99 5.01
is calculated correctly 7.99 20.01

Answer:
332 40. TESTING

40.3.1 Make a prediction


https://isaaccs.org/eq/prog_softeng_08

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:

Test # Purpose Data Expected


results
1 Check that the conversion is carried 12.2 15.5 53.96 59.9
out correctly using typical data 26.7 45.0 80.06 113

The program code is as follows:


1 PROCEDURE convert ()
2 celsius = INT( INPUT (" Enter the temperature in degrees
Celsius : "))
3 fahrenheit = ( celsius * 9 / 5) + 32
4 PRINT ( fahrenheit )
5 ENDPROCEDURE

Only one of the tests worked as expected.


▶ Which piece of input data produced the predicted result?

⃝ 12.2
⃝ 15.5
⃝ 26.7
⃝ 45.0
40. TESTING 333

40.3.2 I'm on the edge


https://isaaccs.org/eq/prog_softeng_01

A student has written the following subroutine.


1 FUNCTION get_mark ()
2 valid = FALSE
3 WHILE valid == FALSE
4 mark = INT(INPUT (" Enter the student 's test mark "))
5 IF mark >= 1 AND mark <= 100 THEN
6 valid = TRUE
7 ELSE
8 PRINT (" That is not a valid test mark ")
9 ENDIF
10 ENDWHILE
11 RETURN mark
12 ENDFUNCTION

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

40.3.3 Entirely sizable


https://isaaccs.org/eq/prog_pas_12

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.

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 ?
4 a=100, b=100, c=10 a=100 ?
5 a=10, b=10, c=10 a=10 ?
6 a=10, b=20, c=20 b=20 ?

▶ 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

40.3.4 Not a factorial


https://isaaccs.org/eq/prog_softeng_12

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?

▶ Which line is the error on?

▶ What will be the (incorrect) return value of Diane’s program?


41 Software engineering principles
Software engineering is the systematic approach to the development of
software. The term is generally accepted to include all aspects of the practice
of developing a computer system to meet a user’s requirements. The Institute
of Electrical and Electronics Engineers (IEEE) describes software engineer-
ing as “the systematic application of scientific and technological knowledge,
methods, and experience to the design, implementation, testing, and docu-
mentation of software”.

41.1.1 How SMART are you?


https://isaaccs.org/eq/prog_softeng_06

A well-defined set of system requirements should be SMART.


▶ What does the acronym ‘SMART’ stand for?

⃝ Specific, Measurable, Achievable, Relevant, Time-bound

⃝ Stated, Measurable, Achievable, Relevant, Tested

⃝ Specific, Measurable, Achievable, Relevant, Tested

⃝ Stated, Measurable, Achievable, Relevant, Time-bound

41.1.2 Am I SMART?
https://isaaccs.org/eq/prog_softeng_07

A student has written some objectives for her software project.


▶ Which of the objectives below would be considered SMART?
The system must…

⃝ Be easy to use

⃝ Calculate the amount due

⃝ Format the invoice so that it is suitable for A4 printing

⃝ Save the customer data in a database

337
338 41. SOFTWARE ENGINEERING PRINCIPLES

41.1.3 Lifecycle
https://isaaccs.org/eq/prog_softeng_05

A traditional method of software development, e.g. the waterfall lifecycle,


is a sequential approach: each stage is carried out and completed before the
next begins. Some of the stages are listed below.
▶ Put them into linear order in line with the traditional sequential approach.

□ Testing
□ Feasibility study
□ Design
□ Development
□ Analysis

41.1.4 Which approach?


https://isaaccs.org/eq/prog_softeng_03

▶ What type of approach to software development is described by the fol-


lowing summary?

A prototype is created, then it is evaluated, and the feedback is


used to inform the next version. Any changes that have been
identified are made, and the process is repeated until the proto-
type becomes the final product.

⃝ RAD

⃝ Waterfall lifecycle

⃝ Spiral model

⃝ Extreme programming
41. SOFTWARE ENGINEERING PRINCIPLES 339

41.1.5 I'm not wasting time


https://isaaccs.org/eq/prog_softeng_10

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.

⃝ Using meaningful identifiers for subroutines


⃝ Avoiding the use of built-in functions
⃝ Making sure that each subroutine carries out one specific task
⃝ Using named constants where appropriate

41.3.1 Agility challenge


https://isaaccs.org/eq/prog_softeng_09

Many people think that an agile approach to systems development is better


than a traditional waterfall approach.
▶ Which of the following reasons could be used to justify an agile approach?
(Select one or more.)

□ Many users find it difficult to fully articulate their requirements at the


start of a project.

□ It allows any problems with the system requirements specification to


be picked up much earlier in the process.

□ It allows the end user to give feedback on parts of the system before
too much time is spent on developing them fully.

□ It always costs less than a waterfall (stage-by-stage) development ap-


proach.
Theory of Computation

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.

42.2.1 Data mining


https://isaaccs.org/eq/dsa_ctm_07

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.

⃝ Correlate customer characteristics and sales figures to identify the tar-


get audience of products
⃝ Analyse purchase habits to predict the likelihood of a customer return-
ing a product
⃝ Identify customer trends to inform the line of products and marketing
for the next season
⃝ Correlate the pay scale of the employees with their roles with a view
to investigating the gender pay gap

340
42. COMPUTATIONAL THINKING 341

42.2.2 Performance modelling


https://isaaccs.org/eq/dsa_ctm_08

Roberta is developing a massively multiplayer online (MMO) game that is


set in space.
▶ Select one way that performance modelling can be used for that purpose.

⃝ 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

⃝ Release an online survey to gather features that potential customers


would like to see in the game

⃝ Simulate a large number of users playing the game simultaneously to


stress test the system

42.2.3 Pipelining
https://isaaccs.org/eq/dsa_ctm_09

Emad is developing a program that simulates a football game. This involves


ensuring that actions are executed in the right order.
▶ Explain how software pipelining can be applied in the program by putting
the processes in order.

□ the process of the player tackling another player


□ which feeds into the player scoring a goal
□ which feeds into increasing the score of the team
□ feeds into the player getting the ball
□ which feeds into the player kicking the ball
342 42. COMPUTATIONAL THINKING

42.2.4 Visualisation
https://isaaccs.org/eq/dsa_ctm_10

Celeste is developing a depth-first tree-traversal algorithm. She uses a spe-


cific binary tree to test her code.
▶ Select one way that visualisation can be used to help her with this task.

⃝ Using an adjacency matrix to depict the tree helps with understanding


the order in which nodes are visited.

⃝ Programming the algorithm helps with clarifying how the algorithm


works as you go along.

⃝ Using a diagram to depict the tree makes it easier to understand how


the algorithm works.

⃝ 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

▶ A binary tree is used to store the names of dog breeds. A representation


of the tree is shown below.
42. COMPUTATIONAL THINKING 343

▶ Number the following statements in order to describe how backtracking


is used, in a left-to-right post-order traversal, to output the names from the
tree.

□ so it outputs “Bichon” and backtracks to “Collie”


□ it can’t go any further, so it outputs “Akita”
□ it can’t go any further, so it outputs “Havanese”
□ it outputs “Maltese” and backtracks to “Greyhound”
□ all the children of “Collie” have been visited
□ then, the algorithm backtracks to “Bichon”
□ from there, it visits and outputs “Fox Terrier”
□ it then backtracks to “Maltese”, and then visits “Pug”
□ all the children of “Bichon” have been visited
□ The algorithm will traverse the left subtree
□ and goes on to traverse the right subtree
□ until it reaches the next leaf, which is “Havanese”
□ so it outputs “Collie” and backtracks to “Greyhound”
□ it outputs “Greyhound” and stops.
□ then, it backtracks to “Collie” for the second time
□ until it reaches the first leaf, which is “Akita”
□ it outputs “Pug” and backtracks to “Maltese”
344 42. COMPUTATIONAL THINKING

42.4.2 It's all so abstract


https://isaaccs.org/eq/dsa_ctm_03

Abstraction is a fundamental skill in computational thinking.


▶ Which of the following is not an abstraction technique?

⃝ 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?

⃝ Binary search problem


⃝ Post-order tree-traversal problem
⃝ Breadth-first graph-traversal problem
⃝ Linear search problem

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy