Computer Science Answers
Computer Science Answers
Activity 1A
a) 51
b) 127
c) 153
d) 116
e) 255
f) 15
g) 143
h) 179
i) 112
j) 238
Activity 1B
a) 00101001
b) 01000011
c) 01010110
d) 01100100
e) 01101111
f) 01111111
g) 10010000
h) 10111101
i) 11001000
j) 11111111
Activity 1C
a) 01110010 (114)
b) 00111101 (61)
c) 01100000 (96)
d) 11110010 (−14)
e) 10001100 (−116)
Activity 1D
a) 01100010
b) 01101110
c) 1) 0000000
d) 1) 0110001
e) 00101011
f) 1) 00110011
g) 1) 00100101
h) 11110000
i) 10011111
j) 1) 00011100
Activity 1E
a) 1100 0011 C3
b) 1111 0111 F7
c) 0010 0111 1111 27F
d) 0100 1110 1110 4EE
e) 0001 1110 0001 1E1
f) 1000 1001 1110 89E
g) 0000 0100 1111 1110 (0)4FE
h) 0000 1110 1001 1100 (0)E9C
i) 1111 1111 0111 1101 FF7D
j) 0000 0110 0111 1010 1110 (0)67AE
Activity 1F
a) 0110 1100
b) 0101 1001
c) 1010 1010
d) 1010 0000 0000
e) 0100 0000 1110
f) 1011 1010 0110
g) 1001 1100 1100
h) 0100 0000 1010 1010
i) 1101 1010 0100 0111
j) 0001 1010 1011 0000
Activity 1G
1 a) 0010 0111 0001
b) 0101 0000 0000 0110
c) 0111 1001 1001 0000
2 a) 937
b) 7762
Activity 1H
a) 0000.01100110 0.66
b) 0001.00010111 1.17
c) 0001.01100011 1.63
Activity 1I
1 a) Lossless:
• All the data from the original file are reconstructed when the file is uncompressed.
• None of the original detail is lost – important for files where loss of data cannot be
tolerated.
Lossy
• The file compression algorithm eliminates unnecessary data.
• The original file cannot be reconstructed following uncompression.
• A lossy algorithm has to make a decision about which parts of the file are less important
and can be discarded.
b) Lossless – RLE (others exist)
Lossy – MPEG/JPEG, MP3/MP4 (and others exist)
2 a) Music is in analogue sound form initially. The microphone turns the sound into electrical
signals. These signals are digitised and sent to computer for storage.
b) Music is stored in lossy (MP3) format. This reduces the size of the file, thus reducing memory
requirements for storage and also allowing more tracks to be stored on a CD/MP3 device (for
example). File compression uses algorithms that utilise perceptual music shaping – this
essentially removes sounds the human ear can’t hear properly. For example, if two sounds are
played at the same time, only the louder one can be heard thus eliminating the softer sound;
also certain sounds outside normal human range are removed – this allows considerable
reduction in file size.
3 a) RLE – is a form of lossless file compression that reduces the size of a string of adjacent,
identical data. For example, repeated colours in a string of pixels in an image.
b)
• reduces the size of a string of adjacent and identical data
• a repeated string is encoded into two values
• one of the values represents the number of identical characters in the run
• the second value represents the code of the character in the run
•only effective with long run of repeated bits e.g. aaaaabbbbccddddd (assuming ASCII
coding used) is reduced to: 05 97 04 98 02 99 05 100 (8 bytes of data compared to 16
bytes in original string).
4 a) Bit-map
• made up of pixels (picture elements)
• image stored as an x-y two-dimensional matrix of pixels
Cambridge International AS & A Level Computer Science 3
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
• image may be scaled up or down but there may be loss of resolution (i.e. pixel density
decreases to a level where picture quality isn’t good).
Vector
• images are made up of 2D points that describe lines and curves and are then grouped into
geometric shapes
• properties such as line colour and style are part of image (these form part of a drawing list)
• easy to scale up with no loss of quality since dimensions of each object in the graphic are
not defined.
b)
• requires less processing power
• individual elements cannot be grouped together
• bit-map files are larger than vector graphic images
• most suitable for photos and scanned in images
Bit-map • at least 8 bits per pixel needed to code a colour image
image • resolution needs to be considered (number of pixels per row and
per column)
• possible to scale image up or down but pixel density may be
reduced resulting in loss of quality (pixilation)
• they rely on certain properties of the eyes; thus, a certain
amount of lossy file compression can be tolerated.
• contain a drawing list which contains attributes such as line
colour, line type, in-fill colours and so on
• dimensions of each object not stored (only defined in relation to
Vector each other; thus, scale up has no loss in quality)
graphics
image • to print out vector graphic image, it first needs to be converted
into bit-map image
• they are most suitable for geometric shapes
• very difficult to compress the file size.
Extension activity 1A
–32768, 16384, 8192, 4096, 2048,1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1
iv)
• file type (e.g. .bmp)
• file size
• image resolution
• colour depth (bits per pixel, e.g. 1, 4, 8, 16, 24, 32)
• type of compression being used.
v)
• edit start/stop time and duration of sound clip
• extract/delete/save part of a sound clip
• ability to alter frequency, amplitude and pitch of the sound clip
• fade in/fade out facility
• mix/merge multiple soundtracks or sound sources
• combine various sources at different volume levels
• removal of noise, for example, to enhance one particular sound in a clip
• conversion between audio file formats.
3 a)
• The amplitude of the sound wave is first determined at set time intervals (the sampling
rate).
• This gives an approximate representation of the sound wave.
• The sound wave is then encoded as a series of binary digits.
• Using a higher sampling rate or larger resolution will result in a more faithful
representation of the original sound source.
b)
• music compression algorithm uses lossy format
• perceptual music shaping is used therefore loss of sound quality not noticed
• music files are large therefore compression needed and lossy also gives greater
compression than lossless.
c) (i) run length encoding
• reduces size of a string of adjacent and identical data
• repeated string encoded into two values
• one value represents number of identical characters in a run
•second value represents code for each character in run.
(ii) assume grey = 85 and white = 255 then we have the RLE code:
3, 85, 2, 255, 4, 85, 9, 255, 4, 85, 2, 255, 1, 85, 2, 255, 2, 85, 2, 255, 1, 85
need 1 byte per pixel number of bytes = 1 x 8 x 4 = 32 for original diagram; RLE needs
22 bytes only
4 a) 60 = 00111100
27 = 00011011
–27 = 11100101
b 00111100
+ 00011011
= 01010111
c 00111100
+ 11100101
= 1) 00100001
d 01011001
+ 01100001
= 10111010 – gives negative result which is not possible when adding two positive numbers
5 a 0.52 = 00000000 . 0101 0010
0.83 = 00000000 . 1000 0011
add .02 and .03 together gives: 0101
now add 0.5 and 0.8 together and this gives 1101 (which doesn’t have a denary value)
thus we add 0110 to 1101 and this gives: 1) 0011
therefore we get 0011 with a carry of 1 giving final answer:
00000001 . 0011 1101 = 1.35
b (i) Hexadecimal – a number system using base 16.
(ii)
• memory dumps
• HTML
• assembly code instructions
(iii) 0111 1110 1111 0010
7 E F 2
6 a 95 = 1001 0101
b using two’s complement this becomes 00100011 + 10111100 = 11011111
(i.e. 35 – 68 = -33)
c 506 = 1 F A
They will require software to enable WiFi if accessing internet via wireless router.
Most devices will need a cell net provider (3G, 4G, 5G) and web browser.
b) Advantages
very small therefore very likely to be carrying it all the time
can also make calls or access internet on the move
can be used anywhere since they don’t need to be near a router.
Disadvantages
small screens can make reading web pages more difficult and more difficult to navigate
small/virtual keyboards can make typing slower and more error prone
web browsers (etc.) can drain the battery quickly
small memory size (most don’t allow memory expansion)
not all webpage features are compatible with smartphone OS
data transfer rates can be relatively slow.
Activity 2A
1 Client-server network
Works well with a small group of workers doing research.
It is possible to control network resources with good network security (essential when doing
research).
It is also important that data needs to be backed up on a central server so that all researchers
have access to the latest developments and data.
2 Peer-to-peer network
Group of consultants is probably small but it all depends on how secure the data needs to be.
If it is essential that it needs to be very secure, then they may need to consider client-server
networks instead
(Note: as long as the chosen network can be fully justified, there is often more than one possible
answer to the question).
Activity 2B
1 a) LAN:
Are networks that cover small geographical areas, for example, a building.
A typical LAN will consist of a number of computers and devices connected by
hubs/switches.
WAN:
Is a network which covers very large geographical area (e.g. whole country or continents).
Wans are formed from connecting number of LANs together by routers/gateways.
Due to vast distances, they use public communication links (such as telephone lines and/or
satellites).
MAN:
Is a network that covers smaller geographical area than a WAN.
They often connect devices in a number of buildings within a city (e.g. a university
campus).
b) Benefits:
sharing of resources such as printers
Cambridge International AS & A Level Computer Science 2
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
software licence for all the computers on a network is usually cheaper than licences for the
same number of stand-alone computers
ability to share files leads to more consistent/reliable data since all data accessed from a
central server
use of a network manager to ensure security and access rights and also to control external
links to, for example, the internet.
c) i) Thick client – a computer that doesn’t rely on processing being done by a server or other
computer; can operate online or offline.
ii) Thin client – a device needing access to the network for it to work e.g. a POS terminal at a
supermarket; depends on a more powerful computer to do the processing.
2 a) i) bus
(ii) star
iii) mesh
b) Bus
Advantages Disadvantages
easier to expand network failure of main cable results in
requires less cabling. failure of whole network
not very good under heavy load.
Star
Advantages Disadvantages
easier to upgrade if the central hub/switch fails, then
if one node or link fails, then the rest the whole network will be down
of the network can still function. high cost of cabling.
Mesh
Advantages Disadvantages
easier to detect network faults requires bulk cabling
has very good privacy and security
3 a) Public cloud – a storage environment where the customer/client and cloud storage provider are
different companies.
Private cloud – a storage provided by a dedicated environment behind a company firewall, the
customer/client and cloud storage provider are integrated and operate as a single entity.
b) Benefits:
Customer/client files stored on the cloud can be accessed any time, from any device,
anywhere in the world provided there is internet access.
There is no need for the customer/client to carry external storage devices around with them
or even use the same computer where the original files were stored.
Cloud storage provides user with remote and automatic back-up of data.
It offers almost unlimited storage capacity (at a cost).
c) Drawbacks:
There are well-known security aspects to consider.
If the internet is unstable/fails or the broadband connection is slow it may be
difficult/impossible to access files from the cloud storage facilities.
Costs can be high if a large amount of cloud storage is required.
There may be limited data transfer rates.
Potential for failure of the cloud storage company with unknown results.
4
Wireless networking Wired networking
It is easier to expand the networks and it Using cables produces a more reliable and
isn’t necessary to connect the devices stable network; wireless connectivity is
using cables. often subjected to interference.
This gives devices increased mobility
Data transfer rates tend to be faster and there
provided they are within range of the
won’t be any ‘dead spots’.
WAPs.
Setting up cabled networks tends to be
There is an increased chance of
cheaper overall in spite of the need to buy
interference from external sources.
and install cable.
Data is less secure than with wired
systems; it is easier to intercept radio However, cabled networks lose the ability
waves and microwaves than cables; it is for devices to be mobile; they must be close
essential to protect data transmissions enough to allow for cable connections.
using encryption (e.g. WEP, WPA2).
Having lots of wires can lead to a number of
Data transmission rate is still slower than hazards such as tripping hazards,
for cabled networks although it continues overheating of connections (leading to
to improve. potential fire risk) and disconnection of
cables during routine office cleaning.
Many devices (for example, smartphones)
Signals can be stopped by walls and there
are only set up for WiFi/Bluetooth
may be drop off points.
connectivity.
There may be legislation regarding which There may be building restrictions
signal frequencies may be used. preventing the laying of cables, etc.
(Note: a reasoned argument needs to be made based on which of the features of wired and
wireless networks from the above table were chosen by the candidate)
5 a) Bit streaming
a contiguous sequence of digital bits sent over a network/internet
requires high speed data transfer communications link
requires buffering
bits arrive at destination in the same order as they were sent.
b)
Buffers are needed since the rate that data is transmitted to the computer may be different
to the data transfer rate to the media player.
Buffers prevent movies ‘freezing’ if, for example, the broadband speed is slow.
c) On demand
digital files stored on a server in bit streaming format
link to encoded video is placed on the website server
user clicks on link to start the download of the video as required
video can be paused/fast forwarded/rewound.
Activity 2C
1 a)
standard telephone line used
line always open until receivers replaced on handset
line remains active even during a power cut
uses circuit switching (which allows line to remain open)
data (voice) transmitted in analogue (old system using copper cables) or digital (using
newer optical fibre networks)
data can transmit in both directions at the same time.
b)
internet connection only live whilst data is being sent/received (talking)
uses Voice over Internet Protocol (VoIP) which converts sound/video to digital packages
(encoding) before sending over the internet
VoIP uses packet switching (data is broken down into packets and then routed to the
destination by the fastest route and then reassembled in the correct order at the destination)
data undergoes file compression to reduce the amount of data being sent.
c) GEO
Geostationary Earth Orbit
provides long distance telephone and computer network communications
35 800 km above the Earth with orbital period of 24 hours.
MEO
Medium Earth Orbit
used by GPS networks
5000 to 12 000 km above the earth with orbital period between 2 to 8 hours.
LEO
Low Earth Orbit
used by mobile phone network operators
500 to 1500 km above the Earth with orbital period between 12 mins and 1 hour.
2 a) A: 00000000 00000000 00000000 00000000
B: 10000000 00000000 00000000 00000000
C: 11000000 00000000 00000000 00000000
b) A (upper): 127.255.255.255
01111111 11111111 11111111 11111111
B (upper): 191.255.255.255
10111111 11111111 11111111 11111111
C (upper): 223.255.255.255
11011111 11111111 11111111 11111111
Cambridge International AS & A Level Computer Science 6
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
… therefore may not be accessible from the internet since this uses common access points
which are open to all users.
c) i) Web browser
a software application for accessing information on www
allows user to view pages on different websites
allow location of websites by typing in the URL in the address bar.
(ii) ISP
a company that provides services to access and use the internet
company will charge a fee for the service provided
has equipment and telecommunication lines to allow internet connection
provides user with an IP address when connecting to the internet.
b)
2 a) i)
Copper cable uses pulses of electricity to transmit data …
… whereas fibre optic cables uses pulses of light to transmit data.
ii)
Copper cabling is much cheaper …
… and is a well-known technology if anything goes wrong.
Fibre optic cables are the cable of choice when sending data over long distances …
… this is because they offer the best data transfer rate and have a very high resistance to
external interference.
The main drawback is the high cost …
… but they do offer the smallest signal attenuation.
They have ~26 000 times the transmission capacity of twisted pair cables.
single mode fibre optic cables use a single mode light source and have a smaller central
core which results in less light reflection along the cable …
… the benefit of this is that the data can travel faster and further than with multi core
cables.
Multi core cables allow for a multi-mode light source; the construction causes higher
light reflections in the core.
Cambridge International AS & A Level Computer Science 9
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
b) i) low buffer value = 200 kiB = 200 × 1024 = 204 800 bits
high buffer value = 1.8 MiB = 1.8 × 1 048 576 = 1 887 437 bits
during first 2 seconds, incoming data = (1.5 × 1 048 576)/8 = 196 608 bits
and outgoing data is = (600 × 1024)/8 = 76 800 bits
therefore, data build up is (196 608 – 76 800) = 119 808 bits
therefore, low buffer mark is now (204 800 + 119 808) = 324 608 bits
ii) The buffer builds up as follows:
after 4 seconds: 444 416 bits
after 6 seconds: 564 224 bits
after 8 seconds: 684 032 bits
after 10 seconds: 803 840 bits
and produces a graph which shows high buffer value reached after about 30 seconds of bit
streaming:
35
30
25
20
15
10
0
0 500000 1000000 1500000 2000000 2500000
c)
A larger buffer is needed (e.g. 20 MiB).
The rate at which data is sent to the media player must increase.
5 a) i) Data collision is when two messages along same data channel sent at same time could
collide.
ii) CSMA/CD relies on fact that frames being sent cause voltage level changes.
iii)
When a collision is detected, the station stops transmitting the frame and transmits a
jam signal.
It then waits for a random time period before resending data frame.
b)
Activity 3A
1 a) i) RAM
temporary memory (contents can be changed)
can be written to/read from
used to store data, files, instructions, part of OS currently in use
volatile memory (contents lost when power turned off).
ROM
non-volatile memory (memory contents retained even when power is lost)
permanent memory (contents cannot be changed)
contents can only be read
used to store start up data (e.g. BIOS).
(ii) DRAM
needs to be constantly refreshed
less expensive to manufacture than SRAM
consumes less power than SRAM
higher storage capacity than SRAM
main memory is constructed from DRAM.
SRAM
no need to constantly refresh since it uses flip-flop circuits
has a faster data access time than DRAM
processor memory cache uses SRAM.
b) Magnetic
uses magnetic properties to store data
uses disk surfaces (coated in magnetic material)
disks rotate and data is read/written using a read/write head which floats above the disk
surface.
Optical
uses disks which are coated in light-sensitive material
data is read/written by red or blue laser light as disk rotates
no contact made with disk surface during read/write operation
DVD uses dual layering to increase data storage capacity.
Solid state
no moving parts
uses NAND/NOR chips to store data
relies on flow of electrons to control read/write operations
can’t overwrite data; data needs to be deleted first and new data is written in the same
location
uses a matrix with two transistors at each intersection
one transistor is floating gate
one transistor is control gate.
2 a) Inkjet printer
uses ink droplets which are ejected onto paper by piezoelectric or heat
paper advances line by line during printing as head moves across the page
ink is in liquid form and contained in cartridges.
Laser printer
uses static electricity to print characters/images
ink is in the form of a dry powder (known as toner)
uses an electrostatically charged drum where paper is charged and areas for printing have
opposite charge
ink is charged and only sticks to areas of paper with opposite charge
print is fixed to paper by passing paper over a heated drum.
b) i) Laser – colour leaflets which need to be produced quickly in their 100s.
Inkjet – one-off high-quality photographs.
ii) Laser – large capacity paper trays and high speed, high quality printing; ink cartridges
last much longer than inkjet before needing to be changed.
Inkjet – for one-off job, printing is just as quick as laser; better quality printing when
printing images.
3
preserves the valuable art works
allows many people to see the paintings since 3D replica can be produced as required
allows full investigation of a painting without any risk of damaging the original (e.g. close
view of brush strokes, amount of paint used on each part of canvass; allows the possibility of
authenticating a new painting).
4
the light sensor sends data to the ADC interface
this changes the data into digital and sends it to the microprocessor
the microprocessor samples the data every minute (or at some other frequency rate)
if the data from the sensor < value stored in memory …
… a signal is sent from the microprocessor to the street lamp
… and the lamp is switched on
the lamp stays switched for 30 minutes before the sensor readings are sampled again (this
prevents the lamp flickering off and on during brief heavy cloud cover for example)
if the data from the sensor >= value stored in memory …
… a signal is sent from the microprocessor to the street lamp
… and the lamp is switched off
the lamp stays switched off for 30 minutes before sensor readings are sampled again (this
prevents the lamp flickering off and on during heavy cloud cover for example).
Activity 3B
1 a)
A B X
0 0 1
0 1 0
1 0 0
1 1 1
b)
A B C X
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
c)
A B X
0 0 0
0 1 0
1 0 0
1 1 0
d)
A B C X
0 0 0 1
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 0
e)
A B C X
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 1
Activity 3C
a)
A B X
0 0 0
0 1 1
1 0 1
1 1 1
b)
A B C X
0 0 0 1
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0
c) (K = 1 OR L = 1) OR (K = 1 AND M = NOT 1) OR (M = 1)
K L M T
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
Cambridge International AS & A Level Computer Science 5
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
d) X = (A = 1 AND B = 1) OR (B = 1 AND C = 1)
A B C X
0 0 0 0
0 0 1 0
0 0 1 0
0 1 1 1
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 1
A B C R
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 1
Activity 3D
a) X = 1 if (R = NOT 1) OR (C = 1 AND T = NOT 1) OR (R =1 AND T = NOT 1)
R T C X
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0
G R W S
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 0
1 1 0 1
1 1 1 1
Activity 3E
1
A B C A B C A B
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
2 a)
A B C X
0 0 0 1
0 0 1 0
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 0
1 1 0 1
1 1 1 1
b)
A B X
0 0 0
0 1 1
1 0 1
1 1 0
3
A B X
0 0 1
0 1 0
1 0 0
1 1 0
Activity 3F
1 a)
b) the truth table will only generate a 0 when all inputs are 1
2 a)
b)
A B C X
0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0
c)
A B C D X
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 0 1 1 0
0 1 0 0 0
0 1 0 1 0
0 1 1 0 0
0 1 1 1 0
1 0 0 0 0
1 0 0 1 0
1 0 1 0 0
1 0 1 1 0
1 1 0 0 0
1 1 0 1 0
1 1 1 0 0
1 1 1 1 0
3
A B C X
0 0 0 1
0 1 1 1
0 0 0 1
0 1 1 1
1 0 0 1
1 1 1 1
1 0 0 1
1 1 1 0
Extension Activity 3A
a) RAM – store user settings, for example, time
ROM – store factory settings, for example, microwave frequencies
b) RAM – stores user settings, for example, temperature
ROM – store cooling logic, sensor readings, and so on
c) RAM – store directions sent from remote or programmed flight pattern
ROM – store factory setting such as radio frequencies
Extension Activity 3E
1 a) completes circuit between top and bottom conductive layer
b) use of keyboard buffers and interrupts
2 a) i) movement of wheels allows mouse to know its x-y position
ii) red light used to allow x-y direction/position to be monitored
b) USB is direct serial wired data connection with computer
wireless uses Bluetooth to communicate with computer
Extension Activity 3G
A B A.𝐁 𝐀.B A.𝐁 + 𝐀.B A+B 𝐀. 𝐁 (A + B).𝐀. 𝐁
0 0 0 0 0 0 1 0
0 1 0 1 1 1 1 1
1 0 1 0 1 1 1 1
1 1 0 0 0 1 0 0
Extension Activity 3H
NOR gate
b)
human eye has limited detection of different colour hues
depends whether or not tv is set up properly
over time screen output deteriorates
unnecessary to have such a range of colours
questionable advantage
(many other reasons to consider)
2 a) i)
can’t be changed by users
software loaded up automatically on powering up
always available
ii)
because many changes are made during the development stage
EPROM can be altered as required
ROM chip can’t be changed once written to
expensive to replace ROM chip each time a change/update is made
iii)
fast access for working memory
values can be written to RAM, for example, current score
iv)
possibility of saving to a memory stick
possibility of linking to larger screens
possibility of connecting to devices such as printers
b)
less expensive to build prototypes
other methods require new mould to be made every time design is changed
3 a) Control
Sensor data is used by the microprocessor or computer to decide if any action needs to be
taken to keep a process within correct parameters.
The output from the system affects next set of inputs.
Monitoring
Sensor data is used by the microprocessor or computer to check whether it is within
stored/set parameters.
If data is outside set parameters, a warning is sent to the user (on screen warning or sound).
The microprocessor/computer has no effect on what is being monitored/it simply ‘watches’
the process.
b)
b) RAM
loses contents when powered off/volatile
temporary memory (contents can be erased or changed)
stores files/part of OS/data/instructions currently in use
data can be read from/written to
often have larger capacity than ROM.
ROM
doesn’t lose contents on powering off/non-volatile
contents cannot be altered/permanent memory
read only memory
can be used to store, for example, BIOS, bootstrap.
c DVD
laser/optical media
phase changing recording
rotating disk and single spiral track (centre to outer rim)
uses dual layering
uses red laser (DVD) or blue laser (Blu-Ray DVD).
Flash memory
NAND-based solid state memory
no moving parts
uses matrix with two transistors at each intersection
one transistor is a floating gate
second transistor is a control gate
uses movement of electrons to control R/W operations
can’t overwrite data with new data; need to erase existing data and then write new data in
the same location.
6 a)
b)
A B C X
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
c) ((NOT A AND B) OR (NOT B OR C)) AND NOT C
(A . B + (B + C)) . C
Activity 4A
1 a) i) CIR – stores the current instructions being executed.
ii) MAR – stores the address of the memory location which is about to be accessed.
iii) PC – stores the address of the next instruction to be executed.
b) i) N = negative flag; set to 1 if result of calculation is negative
C = carry flag; set to 1 if there is a carry bit following a calculation
V = overflow flag; set to 1 if there is an overflow bit following a calculation
when two bytes are added together an arithmetic carry bit is generated from the most
significant bit position:
(Note: the carry bit is used for unsigned integers)
10000110
11001011 C 1
𝟏01010001
overflow occurs when 7 bits are used for the binary number and the 8th bit is a sign
bit; if +127 is the largest integer which can be stored then a sum > 127 will cause
overflow:
01110001
01011110 V 1
𝟏1001111
4 a) Fetch-execute cycle
is the basic operational process of a computer system
is the process whereby computer fetches (retrieves) a program instruction from memory
and determines what the instruction ‘means’
once decoded, the instruction is executed
makes use of buses and addresses to carry out the various functions/operations.
b) MAR [PC] (contents of PC copied into MAR)
PC [PC] + 1 (PC is incremented by 1)
MDR [[MAR]] (data stored at address shown in MAR is copied into MDR)
CIR [MDR] (contents of MDR copied into CIR)
5 fetches, immediate access store (IAS), program counter (PC), MAR, address bus, MDR, decoded,
executed, control signals, control bus, ALU, accumulator
2 Examples include, Intel Pentium and X86, AMD and X86, ARM and A32 or A64 or T32
3 Examples include, Intel i7 and X86, Qualcomm Octo (ARM) and A64
Activity 4B
1 a) i) 200
ii) 300
(iii) 50
b) i) CMP #5
ii) JPE 100
2 a)
Label Address
nomore 106
Number1 109
Number2 110
Number3 111
Number4 112
total 113
b)
CIR Opcode Operand ACC total 113
107 END 10 10
c) Subtracts number2 from number1, then add number3. Only add number4 if the result of
the first calculation is not equal to 10. Store the answer in total
3 a)
LDR #0 Set IX to 0
loop: LDX array Load the element of the array indexed by IX into ACC
END
#79
#68
#69
b)
Label Address
loop 103
array 113
counter 117
c)
CIR Opcode Operand ACC IX counter Output
100 LDM #0 0
102 LDR #0 0 0 0
104 OUT 67 0 0 C
105 INC IX 67 1 0
109 CMP #4 1 1 1
104 OUT 79 1 1 O
105 INC IX 79 2 1
109 CMP #4 2 2 2
104 OUT 68 2 2 D
105 INC IX 68 3 2
109 CMP #4 3 3 3
104 OUT 69 3 3 E
105 INC IX 69 4 3
109 CMP #4 4 4 4
Activity 4C
1 a) i) B10010000
ii) B00000000
b) i) OR #B1000
ii) XOR #B1
2 a) Arithmetic shifts preserve the sign bit of the number and logical shifts always fill with zeros.
b) No bits are lost during a shift, bits shifted out of one end of the register are introduced at the
other end of the register, for example an 8-bit register containing the binary value 10101111
shifted left cyclically 3 places would become 01111101.
2 a HDMI
allows output (audio and visual) from a computer to be connected to HDMI-enabled
monitor/tv
supports high definition and enhanced signals
it is a digital system which can support high definition televisions which require more data
and at a faster data transfer rate
can also protect against piracy by using authentication protocols
supports a refresh rate of 120 Hz.
VGA
supports 640×480 resolution with refresh rate of 60 Hz
analogue system which makes it easier to split the signals between more than one device.
USB
allows computers to communicate with peripherals
uses 4-wire shielded cables
devices are automatically detected when plugged into computer USB port
serial data transmission
industry standard to connect devices to a computer.
b Interrupts
data sent to printer buffer from computer
contents of buffer sent to printer and document starts to be printed
processor carries on with other tasks while printing continues in background
if printer runs out of paper, runs out of ink, paper jam (etc.) then it sends out an interrupt
signal
if interrupt sent out, message is displayed on computer screen requesting user to resolve
issue
once all the data from the buffer is printed, printer sends an interrupt signal to the processor
requesting more data
depending on its priority, interrupt is serviced
once interrupt is serviced, more data is sent to the printer buffer and the above stages are
repeated until all 1000 pages are printed out.
3 a i) ii) PC – stores address of next instruction to be executed
MDR – stores data in transit between memory and other registers
CIR – stores current instruction being executed
MAR – stores address of memory location which is about to be accessed
4 Logical shift – bits shifted out of the register are replaced with zeros, for example an 8-bit
register containing the binary value 10101111 shifted left logically 3 places would become
01111000
Arithmetic shift – the sign of the number is preserved, for example an 8-bit register containing
the binary value 10101111 shifted right arithmetically 3 places would become 11110101.
Arithmetic shifts can be used for multiplication or division by powers of two.
Cyclic shift – no bits are lost during a shift, bits shifted out of one end of the register are
introduced at the other end of the register, for example an 8-bit register containing the binary
value 10101111 shifted left cyclically 3 places would become 01111101
5
a) i) monitoring system
ii) there is no ‘control’ taking place
b) Pressure …If intruder steps on sensor, Infra-red …If beam cut by intruder
c) i) SENSORS COUNT VALUE ACC
B00001010 0 1 B00001010
B00000000
1
2 2
B00001010
B00000010
0
1 1
2
4 4
B00001010
B00000000
4
8 8
B00001010
B00001000
1
2 2
8
c) ii) #1
c) iii) CMP #8 instruction
CMP #128
c) CLI
programmer, analyst or technician
basically anybody who needs to have direct communication with a computer when
developing new software or problem-solving, for example.
GUI
the end-user who doesn’t need any great knowledge of how a computer works
a person who uses the computer to run software, play games or manipulate photographs,
for example.
4 Examples include: paper tape and punched cards to start-up computers (other methods are
accepted)
5
data sent to printer buffer from computer
contents of buffer sent to printer and document starts to be printed
processor carries on with other tasks while printing continues in background
if printer runs out of paper, runs out of ink, paper jam (etc.) then it send out an interrupt signal
if interrupt sent out, message is displayed on computer screen requesting user to resolve issue
once all the data from the buffer is printed, printer sends an interrupt signal to the processor
requesting more data
depending on its priority, interrupt is serviced
once interrupt is serviced, more data is sent to the printer buffer and the above stages are
repeated until all 1000 pages are printed out
Activity 5A
1 a) i) A computer needs an OS because
it provides platform on which programs can run
hardware devices are difficult to use without OS/hides complexity of hardware
it acts as an interface between users and hardware.
ii) Management tasks
process management
interrupt handling
file management
memory management
hardware management
software platform
security management
user interfaces.
b) i) DLL files
shared library files
code saved separately from main .exe files
code only loaded into memory as required at run time
DLL files can be made available to several apps at same time.
Activity 5B
1 a) i) An assembler translates programs written in assembly low-level languages and a
compiler translates programs written in a high-level language.
ii) A compiler produces an object program an interpreter doesn’t
b) See 5.2.2
2 a) a suite of programs used to write and test a computer program written in a high-level
programming language.
b) Source code editor used to write and edit programs. An interpreter used to run programs.
Runtime environment with debugger.
b Cookies
small files which are stored on a user’s computer
sent to a computer when the user visits a website
allow the website to know a user’s preferences and can make suggestions based on a user’s
previous searches
each time the user visits the website, they will be recognised and the user’s information
will be retrieved from a database making it much faster and easier to access the website
(e.g. baskets, user names, and so on).
c i) session cookies
used when buying online, for example
keep a user’s items in a ‘shopping basket’
cease to exist on a user’s computer when the web browser is closed or the website
session is terminated.
ii) permanent cookies
these cookies remember user login details (such as passwords)
remain in operation on the user’s computer even after the web browser is closed or the
website session is terminated
advantage is they remove the need to type in personal details every time a certain
website is visited
many countries have introduced laws to protect users and these cookies are supposed
to become deactivated after 6 months of inactivity.
iii) third party cookies
these cookies are created by a ‘third party’ to carry out market research into a user’s
buying habits and surfing habits
the user can delete or block such cookies by configuring their web browser
the disadvantage of blocking such cookies is that the website will no longer recognise
a user’s preferences.
5 It is possible to corrupt a memory stick if the correct withdrawal procedures are not followed.
Activity 6A
1 a, b, c three examples have been chosen … other answers are possible:
Phishing (risk to the security of stored data)
With phishing, the creator sends out legitimate-looking emails to target users …
… as soon as the recipient clicks on a link in the email or attachment …
… they are sent to a fake website or they are fooled into giving personal data in
response to the email.
The email often appears to come from a trusted source such as a bank or well-
known service provider.
The key aspect is that the recipient has to carry out a task (e.g. click on a link)
before the phishing scam can cause any harm.
The creator of the email can gain personal data such as bank account data or
credit card numbers from the user which can lead to fraud or identity theft.
They need an active host program on the ta.rget computer or an operating system
that has already been infected before they can run.
Running antivirus software in the background on a computer will constantly
check for virus attacks.
All antivirus software have the following common features:
They check software or files before they are run or loaded on a computer.
Antivirus software compares a possible virus against a database of known
viruses.
They carry out heuristic checking.
Any possible files or programs which are infected are put into quarantine which
…
… allows the virus to be automatically deleted or …
… allows the user to make the decision about deletion.
Antivirus software needs to be kept up to date since new viruses are constantly
being discovered.
Full system checks need to be carried out once a week, for example, since some
viruses lie dormant and would only be picked up by this full system scan.
2 Worms – this is a type of stand-alone virus that can replicate itself with the intention of spreading
to other computers; often uses networks to search out computers with weak security which are
prone to such attacks.
Logic bombs – these are code embedded in a program on a computer; when certain conditions are
met (For example, Friday 13th) they are automatically activated to carry out tasks such as deleting
files or start sending data to a hacker.
Trojan horses – these are malicious programs often disguised as legitimate software; they replace
all or part of the legitimate software with the intent of carrying out some harm to the user’s
computer system.
3 a first password is his date of birth
second password contains name of his pet dog
third password contains his name
b strong passwords should
contain upper case letters
contain lower case letters
contain numerical characters
contain other keyboard characters
contain at least 8 characters in length
not contain easy to guess words or numbers
be changed on a regular basis but not in sequence e.g. if existing password is AXtuLr0045
then the next one should not be AXtuLr0046 etc.
c
If the device John is using can be accessed by other people, it isn’t safe to store the
password on the device.
If it is saved on the shared device, the password is accessible to hackers etc.
d John should be suspicious because
the link may not be to a genuine website
by supplying details, the user may be inadvertently giving away personal details to a third
party
it is very likely to be a phishing scam.
Activity 6B
1 error at intersection of bit 6 and byte 4:
(bit 6 has even parity and byte 4 has even parity)
2 a Name: character check, presence check
Date of birth: range check, character check, presence check, format check
Tel No: character check, presence check, length check, format check (0……)
Title/Sex: consistency check
b Validation checks – if the input data matches a set of rules/meets a given criteria.
Verification checks – checks to make sure that the input data matches the original data by
double data entry and/or visual check.
Both methods needed since original data may not be correct.
For example 1, year of birth 1840 rather than 1940; a verification check would not pick this
up since the input data would match the original data and only a validation check would
show this data to be in error.
For example 2, data of birth input as 11/04/2004 when it should be 04/11/2004 would not
be picked up by validation checks (matches format, character check. length checks) but it
would be picked up by a verification check since it didn’t match the original data.
3 a
Verification could use double data entry when the data is entered twice by the same
person/different operators; the computer compares both sets of input.
Alternatively, as data is input the user checks the entries against the original to check for
mis-matches.
b Code NXXXXXNN – length check e.g. A516412KK would fail the check (it would also be
equally possible to do character checks on each field or carry out a format check to ensure it
matches NXXXXXNN or carry out a uniqueness check since each product should have a
unique code).
Number in stock – range field e.g. 125 would fail the check (it would also be equally possible
to do a character check to ensure only numeric values input or a length check to ensure
number of digits didn’t exceed 3 but this wouldn’t be enough on its own since it could still
exceed 100 and pass the check).
Cambridge International AS & A Level Computer Science 5
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
Unit cost – range check e.g. (assuming max price of an item is $1000.00) –$450 would fail the
test because it is negative or $1500.00 would also fail because it is > $1000.00 (it would also
be equally possible to do a character check to ensure only numerical values are input).
Telephone number – length check e.g. 012345678901112 would fail the check (it would also
be equally possible to do a character check since all characters entered must be numerical or it
would be possible to do a format check since the telephone number must fit the format
0XXXXXXXXXX; NOTE: a range check would not work here since the telephone number
begins with a zero).
Note: in all cases a presence check could be acceptable if the data is being input to an online
form where all fields require an entry
Extension Activity 6A
Levels of access controlled by use of different passwords
Extension Activity 6B
a weak – could be a birthday which would be relatively easy to guess
b fairly weak – this is a very common password to use
c strong – mix of numbers, upper and lower case letters, use of other characters
d strong – mix of numbers, upper and lower case letters, use of other characters
e weak – easy to guess the number sequence of 1 2 3 4 5
Extension Activity 6D
1 ISBN-13:
take first 12 digits
multiply each in turn (left to right) by 1, 3, 1, 3, …… 1, 3
add all 12 totals and carry out modulo-10 division
subtract remainder from 10 to give check digit
example: 9 7 8 0 3 4 0 9 8 3 8 2
×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3
= 9 + 21 + 8 + 0 + 3 + 12 + 0 + 27 + 8 + 9 + 8 + 6
= 111 ൊ 10 = 11 remainder 1
check digit = 10 − 1 = 9
2 a modulo-11
2 1 3 1 1 1 0 0 0 4 2 8
×13 ×12 ×11 ×10 ×9 ×8 ×7 ×6 ×5 ×4 ×3 ×2
= 26 + 12 + 33 + 10 + 9 + 8 + 0 + 0 + 0 + 16 + 6 + 16
= 136 ൊ 11 = 12 remainder 4
check digit = 11 − 4 = 7
ISBN-13
2 1 3 1 1 1 0 0 0 4 2 8
×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3
= 2 + 3 + 3 + 3 + 1 + 3 + 0 + 0 + 0 + 12 + 2 + 24
= 53 ൊ 10 = 5 remainder 3
check digit = 10 − 3 = 7
b modulo-11
9 0 9 8 1 2 1 2 3 5 4 4
×13 ×12 ×11 ×10 ×9 ×8 ×7 ×6 ×5 ×4 ×3 ×2
= 117 + 0 + 99 + 80 + 9 + 16 + 7 + 12 + 15 + 20 + 12 + 8
= 395 ൊ 11 = 35 remainder 10
check digit = 11 − 10 = 1
ISBN-13
9 0 9 8 1 2 1 2 3 5 4 4
×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3 ×1 ×3
= 9 + 0 + 9 + 24 + 1 + 6 + 1 + 6 + 3 + 15 + 4 + 12
= 90 ൊ 10 = 9 remainder 0
check digit = 10 − 0 = X
Extension Activity 6E
1 1
2 0
3 1
4 1
5 0
Extension Activity 6F
1 a
b
c
d
e
2 No it isn’t possible
They need an active host program on the target computer or an operating system that has
already been infected before they can run.
Running antivirus software in the background on a computer will constantly check for
virus attacks.
All antivirus software have the following common features:
They check software or files before they are run or loaded on a computer.
Antivirus software compares a possible virus against a database of known viruses.
They carry out heuristic checking.
Any possible files or programs which are infected are put into quarantine which …
… allows the virus to be automatically deleted or …
… allows the user to make the decision about deletion.
Antivirus software needs to be kept up to date since new viruses are constantly being
discovered.
Full system checks need to be carried out once a week, for example, since some viruses
lie dormant and would only be picked up by this full system scan .
b
A firewall can be either software or hardware.
It sits between the user’s computer and an external network …
… and filters information in and out of the computer.
This allows the user to decide to allow communication with an external source …
… and it also warns a user that an external source is trying to access their computer.
Firewalls are the primary defence to any computer system to help protect it from hacking,
malware, phishing and pharming.
The main tasks carried out by a firewall include:
Examine the ‘traffic’ between user’s computer (or internal network) and a public
network.
Check whether incoming or outgoing data meets a given set of criteria …
… if the data fails the criteria, the firewall will block the ‘traffic’ and give the user a
warning that there may be a security issue.
The firewall can be used to log all incoming and outgoing ‘traffic’ to allow later
interrogation by the user.
Criteria can be set so that the firewall prevents access to certain undesirable sites …
… the firewall can keep a list of all undesirable IP addresses.
It is possible for firewalls to help prevent viruses or hackers entering the user’s
computer.
The firewall can be a hardware interface which is located somewhere between the
computer and the internet connection.
It is often referred to in this case as a gateway …
… alternatively the firewall can be software installed on a computer and …
… in some cases this is part of the operating system.
3 At the intersection of bit 6 and byte 5 – the bit in this position is incorrect.
(bit 6 is even parity; byte 5 is even parity)
corrected byte: 1 1 1 0 1 0 1 0
Cambridge International AS & A Level Computer Science 8
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science
iii)
Online banking and commerce is leading to the closure of high street banks and shops in
towns and cities.
This leads to job losses and creation of ‘ghost towns’.
iv)
Human interactions become reduced as people spend more and more time using
computer devices such as games, texting on mobile phones …
… leading to reduction in verbal and written communication.
Recent research has shown that on average we check our phones every 12 minutes and
it is the first thing we check on waking up in the morning!
b Positive impacts
job increases
greater communication with people around the world
greater ability to search for information quickly (5 seconds on a search engine can reveal
thousands of webpage resources).
4 a
Fake news can be posted on any social media platform.
It has become an epidemic leaving users uncertain of the truth.
Articles are designed to misinform or deceive readers.
It is argued that fake news helped in the USA election of 2017 and in the 2016 UK
referendum (although at the time of writing these two statements had yet to be proved right
or wrong).
Because the internet is not policed, people can publish anything they want playing on the
public’s fears and prejudices; the information can come from what appear to be trusted
sources.
Because a large number of people have internet access, it is very powerful tool and
arguments rage as to how much censorship should exist within social media companies.
There are 5 types of fake news:
b
World safety is at risk since terrorist groups can use electronic media to spread their
extreme views and therefore corrupt vulnerable people.
Using phone encryption can make it difficult to understand covert messages being
transmitted around the world.
Cambridge International AS & A Level Computer Science 2
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
c
People publishing information on social media aimed at causing embarrassment and harm.
Hate mail has been on the rise recently since people think that comments published online
are not liable to the same prosecution or they hide behind relative anonymity (although
this, of course, incorrect).
d This is covered in (i) above since fake news can affect election results.
Activity 7A
1
Computer ethics is a set of principles set out to regulate the use of computers.
Three factors should be considered
intellectual property rights – this covers, for example, copying of software without the
permission of the owner
privacy issues – this covers, for example, hacking or any illegal access to another person’s
personal data
effect of computers on society – this covers factors such as job losses, social impacts and
so on.
Use of the internet has led to an increase in plagiarism – this is when a person takes another
person’s idea/work and claims it was their own idea/work.
While it is perfectly fine to quote another person’s idea, it is essential that some
acknowledgement is made so that the originator of the idea/work is known to other
… this can be done by
a series of references at the end of a document …
… or footnotes on each page where a reference needs to be made
software exists that can scan text and then look for examples of plagiarism by searching
web pages on the internet.
2
Recent events in hacking (for example, the hacking of Sony Films in USA) and in terrorism
(for example, the 2015 terrorist attacks in France) bring increasing pressure from many people
to start policing the internet.
Those that support freedom of speech argue that the internet only works because it isn’t
policed.
Many security departments and governments believe that the hacking and terrorism attacks
could have been stopped by having tighter laws …
… allowing them to ‘eavesdrop’ on any data transmission on the internet.
There are many points that support both sides of the argument.
Some form of control would prevent children and other vulnerable groups being subjected to
undesirable websites.
Some form of control would stop incorrect information being published on websites.
again this may not be seen as unethical and certainly not illegal, but nonetheless can cause
distress.
Activity 7B
1 a Software is making and distributing illegal copies of software. Software protected by
copyright laws in much the same way as music CDs, videos and articles from magazines and
books are protected.
b When software is purchased there are certain rules that must be obeyed:
It is not legal to make a software copy and then sell it or give it away to a friend or
colleague.
Software can’t be used on a network or used in multiple computers unless a licence has
been acquired to allow this to happen.
It is not legal to use coding from the copyright software in your own software and then pass
this software on or sell it as your own without the permission of the copyright holders.
Renting out of a software package without permission to do so is illegal.
It is illegal to use the name of copyrighted software on other software without agreement to
do so.
Software piracy (illegal copies of software) is a big issue amongst software companies …
… they take many steps to stop the illegal copying of software and to stop illegal copies
being used once they have been sold.
The following list shows a number of ways software is protected both by making the
installer agree to certain conditions and also by methods which require the original
software to be present for it to work:
When software is being installed, the user will be asked to key in a unique reference
number or product key (a string of letters and numbers) which was supplied with
the original copy of the software (for example: 4a3c 0efa 65ab a81e).
The user will be asked to click ‘OK’ or ‘I AGREE’ or put a cross in a box to agree to
the licence agreement before the software continues to install.
The original software packaging often comes with a sticker informing the purchaser that
it is illegal to make copies of the software; the label is often in the form of a hologram
indicating that this is a genuine copy
some software will only run if the CD-ROM, DVD-ROM or memory stick is
actually in the drive; this stops illegal multiple use and network use of the software;
some software will only run if a dongle is plugged into one of the USB ports.
The Federation Against Software Theft (FAST) was set up in the UK many years ago to
protect the software industry against piracy …
… FAST prosecutes organisations and individuals who are involved in any copyright
infringements …
… this is done by legal penalties for anyone found guilty of such infringement.
2 Benefits to both company and customer
you can check it meets company/personal needs before buying it
a level of product support that exceeds traditional software methods
larger customer base which can be used to get help
leads to bug fixes more quickly and benefits fed back to shareware purchasers
less money spent on advertising, packaging and marketing therefore tend to pass on these
benefits to customers.
Cambridge International AS & A Level Computer Science 5
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
Activity 7D
1 The answer could cover some of the following (or other) points
where and when farmers should plant and harvest their crops; leading to maximising yield
water resource management
more accurate climate information
cross-referencing genetics, habits and medical records can lead to early spotting of cancers
ability to analyse masses of data quickly would lead to massive increase in the accuracy of
data
AI systems developed by what is known as training data: the AI system is trained to recognise
certain aspects therefore they could learn to check the over-policing of minority groups or
discrimination of certain people when asking for a loan (many other examples exist)
carry out fair assessment of data since AI used to help decide on loan applications, insurance
claims and job applications.
2 The following is just part of a long list of possible uses
spam filters
smart email categorisation
smart personal assistants (such as Siri, Amazon Alexa or Google Now)
online customer support systems (for example, Cogito which is a behavioural adaptive system
designed to improve customer support)
security surveillance systems
product recommendations and purchase predictions (for example, Pandora smart music
recommendation system or Amazon product prediction systems)
predictive customer service
Netflix (this company uses accurate predictive technology based on customer reactions to
films and tv series being screened).
The following is a generic list of benefits and drawbacks which should be matched up to AI
applications chosen (bearing in mind there are many others you can choose from)
Benefits Drawbacks
reduces errors allowing higher degrees of can be expensive to repair and maintain
data accuracy some of the AI technology
automated reasoning and learning and cannot replicate human intuitive abilities
perception (when using Siri, for example) and lack a degree of creativity
will help with daily chores and life
ability to do rational thinking with complete don’t have emotions and therefore cannot
absence of any emotion make decisions about whether something is
morally right or wrong
repetitive multi-tasking means jobs are cannot change their responses to a changing
done faster without error environment
Commercial software
Commercial software is available to customers for a fee …
… the fees paid either allow one genuine copy to be used on a single device or involves a
licence being bought to allow multiple users.
Occasionally, software is offered free of charge if an earlier version was bought by the user
…
… this type of software is fully copyright-protected and none of the code can be used
without the prior consent of the copyright owner …
… to ignore this is to break the law.
Freeware:
Freeware is software a user can download from the internet free of charge …
… once it has been downloaded, there are no fees associated with using the software …
… unlike, free software, freeware is subject to copyright laws and users are often requested
to tick a box to say they understand and agree to the terms and conditions governing the
software …
which basically means that a user is not allowed to study or modify the source code in any
way.
Shareware:
Shareware allows users to try out some software free of charge for a trial period …
… at the end of the trial period, the author of the software will request that you pay a fee if
you like it …
once the fee is paid, a user is registered with the originator of the software and free updates
and help are then provided …
… very often, the trial version of the software is missing some of the features found in the
full version, and these don’t become available until the fee is paid.
Obviously, this type of software is fully protected by copyright laws and a user must make
sure they don’t use the source code in any of their own software.
Permission needs to be obtained before this software is copied and given to friends, family
or colleagues.
3 a fifth (E)
b heuristics (C)
c making a machine behave in an intelligent way (D)
d iteration (E)
4 a, b
2 a) Suggestions include:
Access
Oracle
dBase
MySQL
Filemaker
b) storage space not wasted, reduction in redundant data stored, consistent data, independent
data.
3 a) See glossary
c) A normalised relational database is a data base in 3NF, where entities do not contain repeated
groups of attributes, any non-key attributes depend upon the primary key and are independent,
there are no partial dependencies, and the table contains no non-key dependencies.
Activity 8A
Staff Name and staff number are stored twice so the is redundant data.
Data could be inconsistent if the staff number was altered in the payroll file and not the sales file
or vice versa.
The data is not independent, for example, the fields are stored in a different order and in the
payroll file the first name and second name are stored in different fields, but in the sales program
they are stored together in the same field.
Activity 8B
Attributes for the table Teacher: teaching licence number, date of birth, address
Activity 8C
Activity 8D
(P SOR\HH (P SOR\HH
3RVLWLRQ
1XP EHU 1DP H
Employee Table
Contact Table
&RQWDFW (P SOR\HH
1XP EHU 1XP EHU
E-R Diagam
Activity 8E
1 a) i) See Section 8.1.1
ii) See Section 8.1.2
b)
i) Normalisation is the process of organising data to be stored in a database into two or more
tables and relationships between the tables, so that data redundancy is minimised.
ii) Normalisation is carried out by the following:
First Normal Form (1NF) – ensuring that entities do not contain repeated groups of
attributes.
Second Normal Form (2NF) – ensuring that entities are in 1NF and any non-key
attributes depend upon the primary key. There are no partial dependencies.
Third Normal Form (3NF) – ensuring that entities are in 2NF and all non-key
attributes are independent. The table contains no non-key dependencies.
2 a)
Part (Part Number, Part Description, Date Last Ordered, Number in Stock, Minimum Order
Level, Position in Warehouse)
Manufacturer (Manufacturer Name, Manufacturer Address, Manufacturer Contact Details)
Part Manufacturer (Part Number, Manufacturer Name)
b)
Activity 8F
1 a) See Section 8.2.1
b) See Section 8.2.1 last paragraph
2 a) See Section 8.2.1 and 8.2.2
b) The use of access rights to limit what can be seen or changed:
Administrators would have full access rights to everything.
Teachers may be able to see most items but only change details about themselves and their
pupils.
Pupils may only have the right to see data about themselves but not change it.
Activity 8G
CREATE TABLE Teacher(
TeacherName CHARACTER,
Address CHARACTER,
TeacherDateOfBirth DATE);
ALTER TABLE Teacher ADD PRIMARY KEY (LicenceNumber);
ALTER TABLE Class ADD FOREIGN KEY LicenceNumber REFERENCES Teacher (LicenceNumber);
Activity 8H
Activity 8I
SELECT COUNT(STUDENTSUBJECT.ExamMark)
FROM STUDENTSUBJECT;
SELECT AVG(STUDENTSUBJECT.ExamMark)
FROM STUDENTSUBJECT;
Alice WC
Charles PC
Ahmed QR
i) The primary key of the Programmer table is FirstName. This links to FirstName
(foreign key) in Program.
ii) There is a non-key dependency Customer is dependent on ProgramName, (which is not
the primary key of the Program table).
iii) Programmer (FirstName, Team)
ProgramWorkDone (FirstName, ProgramName, NoOfDays)
Program (ProgramName, Customer)
2 a)
i) Database Management System
ii) Issue usernames and passwords to stop unauthorised access to the data. Set access rights so
only relevant staff can edit certain parts of the data.
iii) Setup search criteria to find the data that matches the criteria set
iv) By storing data in (separate) linked tables data redundancy is reduced/data
duplication is controlled. Compatibility/data integrity issues are reduced as data only needs
to be updated once/is only stored once. Unwanted or accidental deletion of linked data is
prevented as the DBMS will flag an error.
b) i) The Primary Key in CLASS is ClassID. The Foreign Key of CLASS-GROUP is ClassID.
ii) Many-to-one
iii)
SELECT StudentID, FirstName
FROM STUDENT
WHERE TutorGroup = "10B" // WHERE (TutorGroup = "10B")
ORDER BY LastName ASC;
iv)
SELECT STUDENT.LastName
FROM STUDENT, CLASS-GROUP
WHERE ClassID = "CS1" // WHERE (ClassID = "CS1") AND CLASS-
GROUP.StudentID = STUDENT.StudentID;
Activity 9A
Possible solution
1 Ask for the number of sides
2 Ask for the length of each side
3 Calculate the internal angle of the polygon
4 Using a pencil and ruler draw a line of the required length
5 From the leftmost end of the line draw another line of the required length at the calculated angle
6 Repeat step 5 for number of sides − 1
Activity 9B
Counter is 2
MyChar is "A"
LetterValue is 65
StudentMark is 40
Percentage is 50
OldString is "Your mark is"
NewString is "Your mark is ninety-seven"
Activity 9C
1 else used in all three programming languages.
Python
# IF - single choice with alternative Python
MyValue = int(input("Please enter my value "))
YourValue = int(input("Please enter your value "))
if MyValue > YourValue:
print ("I win")
else:
print ("You win")
VB
Sub Main()
End Sub
End Module
Java
if Direction == "N":
X=X+1
elif Direction == "S":
X=X-1
elif Direction == "E":
Y=Y+1
elif Direction == "W":
Y=Y-1
else:
print("Error")
print(X,Y)
Sub Main()
Dim X, Y As Integer
Dim Direction As String
X = 0
Y = 0
Console.Write("Please Enter N, S, E or W ")
Direction = Console.ReadLine()
Select Case Direction
Case "N"
Y = Y + 1
Case "S"
Y = Y - 1
Case "E"
X = X + 1
Case "W"
X = X - 1
Case Else
Console.WriteLine("Error")
End Select
Console.Write(X & " " & Y)
Console.ReadKey() 'wait for keypress
End Sub
End Module
import java.util.Scanner;
public class CaseStatement
{
public static void main(String args[])
{
int X = 0,Y = 0;
Scanner myObj = new Scanner(System.in);
Activity 9D
VB - does reach 10
'FOR - simple loop VB without step
Module Module1
Sub Main()
End Module
Sub Main()
Dim Number As Integer
Do
Console.Write("Please enter a positive number ")
Number = Console.ReadLine()
End Sub
End Module
While loop
Sub Main()
Dim Number As Integer
Number = 0
While Number >= 0
Console.Write("Please enter a positive number ")
Number = Console.ReadLine()
End While
Console.ReadKey() 'wait for keypress
End Sub
End Module
Activity 9E
Number 0
REPEAT
PRINT "Enter a number, your number must be between 10 and 20 or over
100"
INPUT Number
UNTIL (Number > 10 AND Number < 20) OR (Number > 100)
Activity 9F
DECLARE Password1, Password2 : STRING
DECLARE Counter : INTEGER
Counter 0
REPEAT
PRINT "Enter your password "
INPUT Password1
PRINT "Enter your password again "
INPUT Password1
Counter Counter + 1
UNTIL (Counter = 3) OR (Password1 = Password2)
IF Password1 = Password2
THEN
OUTPUT "Password correct"
ELSE
OUTPUT "Password incorrect"
ENDIF
Python
# three attempts at checking password
Counter = 0
Password1 = "Pass1"
Password2 = "Pass2"
while ((Counter != 3) and (Password1 != Password2)):
Password1 = input("Enter your password ")
Password2 = input("Enter your password again ")
Counter = Counter + 1
if Password1 == Password2:
print ("Password correct")
else:
print ("Password incorrect")
VB
'three attempts at checking password
Module Module1
Sub Main()
Dim Password1, Password2 As String
Dim Counter As Integer
Counter = 0
Do
Console.Write("Please enter password ")
Password1 = Console.ReadLine()
Console.Write("Please enter password again ")
Password2 = Console.ReadLine()
Counter = Counter + 1
Loop Until ((Counter = 3) Or (Password1 = Password2))
If Password1 = Password2 Then
Console.WriteLine("Password correct")
Else
Console.WriteLine("Password incorrect")
End If
Console.ReadKey() 'wait for keypress
End Sub
End Module
Activity 9G
OUTPUT "Enter your personal best time in seconds "
INPUT PBTimeSeconds
IF TotalMarathonTimeSeconds < PBTimeSeconds
THEN
PBTimeSeconds TotalMarathonTimeSeconds
ENDIF
OUTPUT "Your personal best time in seconds is ", PBTimeSeconds
Python
# checking personal best time
TotalMarathonTimeSeconds = 14400 #value to use for test
PBTimeSeconds = int(input("Enter your personal best time in seconds "))
if TotalMarathonTimeSeconds < PBTimeSeconds:
PBTimeSeconds = TotalMarathonTimeSeconds
print( "Your personal best time in seconds is ", PBTimeSeconds)
VB
'checking personal best time
Module Module1
Sub Main()
Dim TotalMarathonTimeSeconds, PBTimeSeconds As Integer
TotalMarathonTimeSeconds = 14400 'value to use for test
Console.Write("Enter your personal best time in seconds ")
PBTimeSeconds = Console.ReadLine()
If TotalMarathonTimeSeconds < PBTimeSeconds Then
PBTimeSeconds = TotalMarathonTimeSeconds
End If
Console.WriteLine("Your personal best time in seconds is " +
PBTimeSeconds.ToString())
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//checking personal best time
import java.util.Scanner;
class ACTIVITY9G
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int TotalMarathonTimeSeconds = 14400;
System.out.println("Enter your personal best time in seconds");
int PBTimeSeconds = myObj.nextInt();
if ( TotalMarathonTimeSeconds < PBTimeSeconds){
PBTimeSeconds= TotalMarathonTimeSeconds;
}
System.out.println("Your personal best time in seconds is " +
PBTimeSeconds);
}
}
Activity 9H
DECLARE Mark : INTEGER
DECLARE Grade, Reply : STRING
REPEAT
OUTPUT "Enter your exam mark"
INPUT Mark
IF Mark < 40
THEN
Grade "Fail"
ELSE
IF Mark < 60
THEN
Grade "Pass"
ELSE
IF Mark < 80
THEN
Grade "Merit"
ELSE
Grade "Distinction"
ENDIF
ENDIF
ENDIF
OUTPUT "Your grade is ", Grade
OUTPUT "Enter another exam mark Y/N "
INPUT Reply
UNTIL Reply <> "Y"
Python
# more than one mark
Reply = "Y"
while Reply == "Y":
Mark = int(input("Enter your exam mark "))
if Mark < 40:
Grade = "Fail"
elif Mark < 60:
Grade = "Pass"
elif Mark < 80:
Grade = "Merit"
else:
Grade = "Distinction"
print( "Your grade is ", Grade)
Reply = input("Enter another exam mark Y/N ")
VB
'more than one mark
Module Module1
Sub Main()
Dim Mark As Integer
Dim Grade, Reply As String
Reply = "Y"
Do
Console.Write("Enter your exam mark ")
Mark = Console.ReadLine()
Select Case Mark
Case 0 To 39
Grade = "Fail"
Case 40 To 59
Grade = "Pass"
Case 60 To 79
Grade = "Merit"
Case 80 To 100
Grade = "Distinction"
End Select
Console.WriteLine("Your Grade is " + Grade)
Console.Write("Enter another exam mark Y/N ")
Reply = Console.ReadLine()
Loop While (Reply = "Y")
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//more than one mark
import java.util.Scanner;
class ACTIVITY9H
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
String Grade, Reply;
Grade = "";
int Mark;
do {
System.out.println("Enter your exam mark");
Mark = myObj.nextInt();
if ( Mark < 40){
Grade = "Fail";
}
if ((Mark >= 40) && (Mark < 60) ){
Grade = "Pass";
}
if ((Mark >= 60) && (Mark < 80)) {
Grade = "Merit";
}
if (Mark > 80) {
Grade = "Distinction";
}
System.out.println("Your grade is " + Grade);
System.out.println("Enter another exam mark Y/N ");
Reply = myObj.next();
}
while (Reply.equals("Y"));
}
}
Activity 9I
DECLARE Shape : STRING
DECLARE Side, Base, Height, Radius : INTEGER
DECLARE Area : REAL
Area = 0
CONSTANT Pi = 3.142
OUTPUT "Please enter the shape (Square, Triangle, Circle) "
INPUT Shape
IF Shape = "Square"
THEN
OUTPUT "Please enter length of side "
INPUT Side
Area Side * Side
ENDIF
IF Shape = "Triangle"
THEN
OUTPUT "Please enter length of base and height "
INPUT Base, Height
Area (Base * Height) / 2
ENDIF
IF Shape = "Circle"
THEN
Cambridge International AS & A Level Computer Science 12
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
IF Area <> 0
THEN
OUTPUT "Area of ", Shape, " is ", Area
ENDIF
Python
# finding the area of a shape
Pi = 3.142
Area = 0.0
Shape = input("Please enter the shape ")
if Shape == "Square":
Side = int(input("Plese enter the length of the side "))
Area = Side * Side
elif Shape == "Triangle":
Base = int(input("Plese enter the length of the base "))
Height = int(input("Plese enter the length of the height "))
Area = (Base * Height) / 2
elif Shape == "Circle":
Radius = int(input("Plese enter the length of the radius "))
Area = Pi * Radius * Radius
if Area != 0:
print("Area of ", Shape, " is ", Area)
VB
' finding the area
Module Module1
Sub Main()
Dim Shape As String
Dim Area As Decimal
Dim Side, Base, Height, Radius As Integer
Const Pi As Decimal = 3.142
Area = 0.0
Console.Write("Please enter the shape ")
Shape = Console.ReadLine()
End Sub
End Module
Java
// finding the area
import java.util.Scanner;
public class ACTIVITY9I
{
public static void main(String args[])
{
int Side, Base, Height, Radius;
float Area = 0.0f;
float Pi = 3.142f;
}
if (Area != 0.0) {
System.out.println("Area of " + Shape + " is " + Area);
}
}
}
01 Try 0
02 REPEAT
03 OUTPUT" Menu Temperature Conversion"
04 OUTPUT" Celsius to Fahrenheit 1"
05 OUTPUT" Fahrenheit to Celsius 2"
06 OUTPUT" Exit 3"
07 OUTPUT" Enter choice"
08 IF Choice = 1 OR Choice = 2
09 THEN
10 OUTPUT"Enter temperature"
11 INPUT Temperature
12 IF Choice = 1
13 THEN
14 ConvertedTemperature 1.8*Temperature + 32
15 ELSE
16 ConvertedTemperature (Temperature – 32) * 5 / 9
17 ENDIF
18 OUTPUT "Converted temperature is ", ConvertedTemperature
19 ELSE
20 IF Choice <> 3
21 THEN
22 OUTPUT "Error in choice"
23 Try Try + 1
24 ENDIF
25 ENDIF
26 UNTIL Choice = 3 OR Try = 3
Activity 10A
a) String
b) Integer
c) Real
d) Boolean
e) Date
Activity 10B
DECLARE MyName : STRING
DECLARE NumberOfChildren : INTEGER
DECLARE RaceTime : REAL
DECLARE DoorState : BOOLEAN
Python
MyName = "Helen"
NumberOfChildren = 27
RaceTime = 45.13
DoorState = True
VB
Dim MyName As String
Dim NumberOfChildren As Integer
Dim RaceTime As Decimal
Dim DoorState As Boolean
Java
String MyName;
int NumberOfChildren;
float RaceTime;
boolean DoorState;
Activity 10C
TYPE
TStudentRecord
DECLARE name : STRING
DECLARE dateOfBirth : DATE
DECLARE class : STRING
DECLARE gender : STRING
ENDTYPE
DECLARE MyStudent : TStudentRecord
MyStudent.name "Ahmad Sayed"
MyStudent.dateOfBirth 10/March/2010
MyStudent.class "5A"
MyStudent.gender "Male"
OUTPUT "Name ", MyStudent.name
OUTPUT "Date of birth ", MyStudent. dateOfBirth
OUTPUT "Class ", MyStudent.class
OUTPUT "Gender ", MyStudent.gender
Python
#student record
import datetime
class TStudentRecord:
def _init_(self):
self.name =""
self.dateOfBirth = datetime.datetime()
self.group = ""
self.gender =""
myStudent = TStudentRecord()
myStudent.name = "Ahmad Sayed"
myStudent.dateOfBirth = datetime.datetime(2010, 3, 10)
myStudent.group = "5A"
myStudent.gender ="Male"
print ("Name ", myStudent.name)
print ("Date of Birth ", myStudent.dateOfBirth)
print ("Class ", myStudent.group)
print ("Gender ", myStudent.gender)
VB
'student record
Module Module1
Sub Main()
Java
//student record
import java.util.*;
class ACTIVITY10C {
static class TStudentRecord {
String name;
String dateOfBirth;
String group;
String gender;
Activity 10D
OUTPUT "Enter these 9 values in order 27, 19, 36, 42, 16, 89, 21, 16,
55"
FOR counter 0 TO 8
OUTPUT "Enter next value "
INPUT myList[counter]
NEXT counter
Python
# 1-D list
myList = [27, 19, 36, 42, 16, 89, 21, 16, 55]
print (*myList)
VB
'1-D Array
Module Module1
Sub Main()
Dim myList = New Integer() {27, 19, 36, 42, 16, 89, 21, 16, 55}
Dim index As Integer
For index = 0 To myList.GetUpperBound(0)
Console.Write(myList(index))
Console.Write(" ")
Next
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//1-D Array
class ACTIVITY10D {
public static void main(String args[]){
int[] myList = {27, 19, 36, 42, 16, 89, 21, 16, 55};
for(int index = 0; index < myList.length; index ++){
}
}
}
Activity 10E
OUTPUT "Enter these values in order 27, 19, 36, 42, 16, 89, 21, 16, 55"
OUTPUT "Enter these values in order 31, 67, 98, 22, 35, 46, 71, 23, 11"
OUTPUT "Enter these values in order 17, 48, 29, 95, 61, 47, 28, 13, 77"
FOR columnCounter 0 TO 2
FOR rowCounter 0 TO 8
OUTPUT "Enter next value "
INPUT myArray[rowCounter, columnCounter]
NEXT rowCounter
NEXT columnCounter
Python
# 2-D list
myArray = [[27, 31, 17], [19, 67, 48],[36, 98, 29],[42, 22, 95],
[16, 35, 61], [89, 46, 47], [21, 71, 28], [16, 23, 13], [55, 11, 77]]
print(*myArray)
VB
' 2-D Array
Module Module1
Sub Main()
Dim myArray = New Integer(8, 2) {{27, 31, 17}, {19, 67, 48},
{36, 98, 29}, {42, 22, 95}, {16, 35, 61}, {89, 46, 47},
{21, 71, 28}, {16, 23, 13}, {55, 11, 77}}
Dim rowIndex, columnIndex As Integer
For rowIndex = 0 To myArray.GetUpperBound(0)
For columnIndex = 0 To myArray.GetUpperBound(1)
Console.Write(myArray(rowIndex, columnIndex))
Console.Write(" ")
Next
Console.WriteLine()
Next
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//2-D Array
class ACTIVITY10E {
public static void main(String args[]){
int[][] myArray = {{27, 31, 17}, {19, 67, 48},
{36, 98, 29}, {42, 22, 95}, {16, 35, 61}, {89, 46, 47},
{21, 71, 28}, {16, 23, 13}, {55, 11, 77}};
for(int rowIndex = 0; rowIndex < myArray.length; rowIndex ++){
for(int columnIndex = 0; columnIndex < myArray[rowIndex].length;
columnIndex ++){
System.out.print(myArray[rowIndex][columnIndex] + " ");
}
System.out.println();
}
}
}
Activity 10F
1-D Array uses:
List of names, list of exam results, leader board scores for a game
2-D Array uses:
Seats booked for a show, homework marks for a class, list of book titles and their authors
Records are used when several pieces of information need to be stored about each indexed item and
the information has different data types. For example, student name, exam mark, exam grade and date
of birth.
Activity 10G
DECLARE myList : ARRAY[0:8] OF INTEGER
DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE item : INTEGER
DECLARE found : BOOLEAN
DECLARE foundIndex : INTEGER
upperBound 8
lowerBound 0
OUTPUT "Please enter item to be found"
INPUT item
found FALSE
index lowerBound
REPEAT
IF item = myList[index]
THEN
found TRUE
ENDIF
index index + 1
UNTIL (found = TRUE) OR (index > upperBound)
IF found
THEN
OUTPUT "Item found at index ", foundIndex
ELSE
OUTPUT "Item not found"
ENDIF
Python
#linear search
myList = [27, 19, 36, 42, 16, 89, 21, 16, 55]
print (*myList)
item = int(input("Please enter item to be found "))
lowerBound = 0
upperBound = len(myList) - 1
found = False
index = lowerBound
while (not found) and (index <= upperBound):
if item == myList[index]:
found = True
foundIndex = index
index = index + 1
if found:
print ("Item found at index ", foundIndex)
else:
print ("Item not found")
VB
'linear search
Module Module1
Sub Main()
Dim myList = New Integer() {27, 19, 36, 42, 16, 89, 21, 16, 55}
Dim item, index, foundIndex As Integer
Dim found = False
Console.Write("Please enter your item to be found ")
item = Console.ReadLine()
index = myList.GetLowerBound(0)
Do
If item = myList(index) Then
found = True
foundIndex = index
End If
index = index + 1
Loop Until found Or index > myList.GetUpperBound(0)
If found Then
Console.WriteLine("Item found at index " +
foundIndex.ToString())
Else
Console.WriteLine("Item not found")
End If
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//linear search
import java.util.Scanner;
class ACTIVITY10G {
public static void main(String args[]){
Scanner myObj = new Scanner(System.in);
int[] myList = {27, 19, 36, 42, 16, 89, 21, 16, 55};
int index = 0;
int foundIndex = -1;
boolean found = false;
System.out.println("Please enter your item to be found ");
int item = myObj.nextInt();
do {
if (item == myList[index]) {
found = true;
foundIndex = index;
}
index = index + 1;
}
while (!found && index< myList.length);
if (found){
System.out.println ("Item found at index + foundIndex);
} else {
System.out.println ("Item not found");
}
}
}
Activity 10H
Python
#bubble sort
myList = [27, 19, 36, 42, 16, 89, 21, 16, 55]
print (*myList)
lowerBound = 0
top = len(myList) - 1
swap = True
VB
'Bubble Sort
Module Module1
Sub Main()
Dim myList = New Integer() {27, 19, 36, 42, 16, 89, 21, 16, 55}
Dim index, top, temp As Integer
Dim swap As Boolean
top = myList.GetUpperBound(0) - 1
For index = myList.GetLowerBound(0) To myList.GetUpperBound(0)
Console.Write(myList(index).ToString() + " ")
Next
Console.WriteLine()
Do
swap = False
For index = myList.GetLowerBound(0) To top
If myList(index) > myList(index + 1) Then
temp = myList(index)
myList(index) = myList(index + 1)
myList(index + 1) = temp
swap = True
End If
Next
top = top - 1
Loop Until Not swap Or top = myList.GetLowerBound(0)
For index = myList.GetLowerBound(0) To myList.GetUpperBound(0)
Console.Write(myList(index).ToString() + " ")
Next
Console.WriteLine()
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//bubble sort
class ACTIVITY10H {
public static void main(String args[]){
int[] myList = {27, 19, 36, 42, 16, 89, 21, 16, 55};
int top = myList.length - 1;
int temp, index;
int lowerBound = 0;
boolean swap;
for (index = lowerBound; index <= top; index++){
System.out.print(myList[index] + " ");
}
System.out.println();
do {
swap = false;
for (index = lowerBound; index < top; index++){
if (myList[index] > myList[index + 1]) {
temp = myList[index];
myList[index] = myList[index + 1];
myList[index + 1] = temp;
swap = true;
}
}
top = top - 1;
}
while (swap && (top > lowerBound));
for (index = lowerBound; index <= myList.length - 1; index++){
System.out.print(myList[index] + " ");
}
System.out.println();
}
}
Activity 10I
Extended pseudocode
DECLARE textLn : STRING
DECLARE myFile : STRING
myFile "myText.txt"
OPEN myFile FOR WRITE // write lines of text to file
REPEAT
OUTPUT "Please enter a line of text"
INPUT textLn
IF textLn <> ""
THEN
WRITEFILE, textLn
ELSE
CLOSEFILE(myFile)
ENDIF
UNTIL textLn = ""
OUTPUT "The file contains these lines of text:"
OPEN myFile FOR READ // read lines of text to file
REPEAT
READFILE, textLn
OUTPUT textLn
UNTIL EOF(myFile)
CLOSEFILE(myFile)
OPEN myFile FOR APPEND // write more lines of text to file
REPEAT
OUTPUT "Please enter a line of text"
INPUT textLn
IF textLn <> ""
THEN
WRITEFILE, textLn
ELSE
CLOSEFILE(myFile)
ENDIF
UNTIL textLn = ""
OUTPUT "The file now contains these lines of text:"
OPEN myFile FOR READ // rad all the lines of text to file
REPEAT
READFILE, textLn
OUTPUT textLn
UNTIL EOF(myFile)
CLOSEFILE(myFile)
Python
# writing to and reading a line of text from a file
myFile = open ("myText.txt","w")
textLn = "start"
while textLn != "":
textLn = input("Please enter a line of text ")
if textLn != "":
myFile.write(textLn + "\n")
else: myFile.close()
print("The file contains these lines of text")
myFile = open ("myText.txt","r")
textLn = myFile.read()
print(textLn)
VB
'writing to and reading from a text file
Imports System.IO
Module Module1
Sub Main()
Dim textLn As String
Dim objMyFileWrite As StreamWriter
Dim objMyFileRead As StreamReader
objMyFileWrite = New StreamWriter("textFile.txt")
Do
Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()
objMyFileWrite.WriteLine(textLn)
Loop Until textLn = ""
objMyFileWrite.Close()
Console.ReadLine()
End Sub
End Module
Java
//writing to and reading from a text file
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class ACTIVITY10I {
do {
System.out.println("Please enter a line of text ");
textLn = myObj.next();
myPrintWriter.printf("%s" + "%n", textLn);
}
while (!textLn.equals("end"));
myPrintWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader myFileReader = new FileReader("textFile.txt");
BufferedReader myBufferReader = new
BufferedReader(myFileReader);
do {
textLn = myBufferReader.readLine();
System.out.println(textLn);
}
while(!textLn.equals("end"));
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Activity 10J
9
8
7
6
5 92 topPointer
4 67
3 87
2 16
1 32 basePointer
Activity 10K
1
2 55 frontPointer
3 19
4 25
5 75 rearPointer
6
7
9
9
Length of queue is 4
Activity 10L
1 1 −1
2 45 2 4
3 12 3 −1
4 18 4 3
5 75 startPointer 5 2
6 heapPointer 6 7
7 7 0
8 8 9
9 9 10
10 10 11
11 11 0
2 a) myFile "Student.txt"
CREATE myFile
OPEN myFile FOR WRITE
b) OPEN myFile FOR APPEND
WRITEFILE myFile, StudentRecord
c) OPEN myFile FOR READ
OPEN myNewFile FOR WRITE
REPEAT
READFILE myFile, StudentRecord
IF StudentRecord.name <> "Not Wanted"
THEN
WRITEFILE myFile, StudentRecord
ENDIF
UNTIL EOF (myFile)
CLOSEFILE(myFile)
CLOSEFILE(myNewFile)
d) OPEN myFile FOR READ
REPEAT
READFILE myFile, StudentRecord
OUTPUT StudentRecord
UNTIL EOF (myFile)
CLOSEFILE(myFile)
Cambridge International AS & A Level Computer Science 16
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
ii)
NumberOfItems 10
REPEAT
NoMoreSwaps TRUE
6 a)
Head Ben
Ahmed
Jatinder
Tail
b) i)
Queue
HeadPointer Name Pointer
0 2
[1]
[2] 3
TailPointer [3] 4
0 5
[4]
[5] 6
FreePointer [6] 7
1
[7] 8
[8]
9
[9]
10
[10]
0
// sort myList
REPEAT
FOR index lowerBound TO top - 1
Swap FALSE
IF myList[index] > myList[index + 1]
THEN
temp myList[index]
myList[index] myList[index + 1]
myList[index + 1] temp
swap TRUE
ENDIF
NEXT
top top -1
UNTIL (NOT swap) OR (top = 0)
// search for 27
found FALSE
index lowerBound
REPEAT
IF 27 = myList[index]
THEN
found TRUE
Cambridge International AS & A Level Computer Science 1
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
ENDIF
index index + 1
UNTIL (found = TRUE) OR (index > upperBound)
// Output if 27 found
IF found
THEN
OUTPUT "27 found"
ELSE
OUTPUT "27 not found"
ENDIF
Python
#input values into myList
myList =[]
upperBound = 10
lowerBound = 0
for index in range (lowerBound, upperBound):
myList.append(int(input("Please Enter Value ")))
#sort myList
top = len(myList) - 1
swap = True
while (swap and top > lowerBound):
swap = False
for index in range (lowerBound, top):
if myList[index] > myList[index + 1]:
temp = myList[index]
myList[index] = myList[index + 1]
myList[index + 1] = temp
swap = True
top = top - 1
lowerBound = 0
upperBound = len(myList) - 1
found = False
index = lowerBound
while (not found) and (index <= upperBound):
if 27 == myList[index]:
found = True
foundIndex = index
index = index + 1
# output if 27 found
if found:
print ("27 found")
else:
print ("27 not found")
VB
Module Module1
Sub Main()
Dim myList(9) As Integer
Dim index, lowerBound, upperBound, top, temp As Integer
Dim swap As Boolean
Dim found = False
lowerBound = 0
upperBound = 9
'sort myList
Do
swap = False
For index = myList.GetLowerBound(0) To top
If myList(index) > myList(index + 1) Then
temp = myList(index)
myList(index) = myList(index + 1)
myList(index + 1) = temp
swap = True
End If
Next
top = top - 1
Loop Until Not swap Or top = myList.GetLowerBound(0)
'search for 27
index = myList.GetLowerBound(0)
Do
If 27 = myList(index) Then
found = True
End If
index = index + 1
Loop Until found Or index > myList.GetUpperBound(0)
'Output if 27 found
If found Then
Console.WriteLine("27 found")
Else
Console.WriteLine("27 not found")
End If
Console.ReadKey() 'wait for keypress
End Sub
End Module
Java
//linear search
import java.util.Scanner;
class Chapter11
{
public static void main(String args[]){
Scanner myObj = new Scanner(System.in);
int[] myList = new int [10];
int top = myList.length - 1;
int index = 0;
boolean found = false;
int temp;
int lowerBound = 0;
boolean swap;
//sort myList
do {
swap = false;
for (index = lowerBound; index < top; index++){
if (myList[index] > myList[index + 1]) {
temp = myList[index];
myList[index] = myList[index + 1];
myList[index + 1] = temp;
swap = true;
}
}
top = top - 1;
}
while (swap && (top > lowerBound));
//search for 27
found = false;
index = lowerBound;
do {
if (27 == myList[index]) {
found = true;
}
index = index + 1;
}
while (!found && index< myList.length);
//output if 27 found
if (found){
System.out.println ("27 found");
} else {
System.out.println ("27 not found");
}
}
}
Activity 11A
Python
#calculate the volume and surface area of a sphere
pi = 3.142
finish = False
radius = float(input("Please enter the radius of the sphere "))
while finish == False:
while radius <= 0 and radius != -1:
radius = float(input("Please enter the radius
of the sphere "))
if radius != -1:
volume = (4 / 3) * pi * radius * radius *
radius
surfaceArea = 3 * pi * radius * radius
print("Volume is ", volume)
print("Surface area is ", surfaceArea)
radius = float(input("Please enter the radius
of the sphere "))
else:
finish = True
VB
Module Module1
Public Sub Main()
Dim radius As Decimal
Dim volume As Decimal
Dim surfaceArea As Decimal
Const pi As Decimal = 3.142
Dim found As Boolean = False
Do
Do
Console.Write("Please enter the radius of the sphere
")
radius = Decimal.Parse(Console.ReadLine())
Loop Until (radius > 0) Or (radius = -1.0)
If radius <> -1 Then
volume = (4 / 3) * pi * radius * radius * radius
surfaceArea = 3 * pi * radius * radius
Console.WriteLine("Volume is " & volume)
Console.WriteLine("Surface area is " & surfaceArea)
Else
found = True
End If
Loop Until found
Console.ReadKey()
End Sub
End Module
Java
import java.util.Scanner;
class Activity11A
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
final double PI = 3.142;
double radius;
boolean found = false;
do {
do {
System.out.println("Please enter the radius of the sphere ");
radius = myObj.nextDouble();
}
while (radius < 0 && radius != -1);
if (radius != -1){
double volume = (4 / 3) * PI * radius * radius * radius;
double surfaceArea = 4 * PI * radius * radius;
}
else {
found = true;
}
}
while(!found);
}
}
Activity 11B
Python
#password checker
storedPassword = "Secret"
inputPassword = input("Please enter your password ")
size = len(inputPassword)
if size == len(storedPassword) :
if (inputPassword[0] == storedPassword[0]) and (inputPassword[-1]
== storedPassword[-1:]):
print ("Password entered has correct first and last letters")
else:
print("Password entered is incorrect")
else:
print("Password entered is incorrect")
VB
'Password checker
Module Module1
Sub Main()
Dim storedPassword = "Secret"
Dim inputPassword As String
Dim size As Integer
Console.Write("Please enter your password ")
inputPassword = Console.ReadLine() I’
size = Len(inputPassword)
If size = Len(storedPassword) Then
If Left(inputPassword, 1) = Left(storedPassword, 1) And
Right(inputPassword, 1) = Right(storedPassword, 1) Then
Console.WriteLine("Password has correct first and last
letters")
Else
Console.WriteLine("Password entered is incorrect")
End If
Else
Console.WriteLine("Password entered is incorrect")
End If
Console.ReadLine()
End Sub
End Module
Java
//password checker
import java.util.Scanner;
class ACTIVITY11B {
public static void main(String args[]){
Scanner myObj = new Scanner(System.in);
String storedPassword = "Secret";
System.out.println("Please enter your password ");
String inputPassword = myObj.next();
int size = inputPassword.length();
if (size == storedPassword.length()){
if ((inputPassword.charAt(0) == storedPassword.charAt(0)) &&
(inputPassword.charAt(size - 1) ==
storedPassword.charAt(storedPassword.length() - 1))) {
System.out.println("Password entered has correct first and last
letters");
}
else{
System.out.println("Password entered is incorrect");
}
} else {
System.out.println ("Password entered is incorrect");
}
}
}
Extension
The strings would need converting to upper or lower case using these functions.
Upper Language
inputPassword.upper() Python
UCase(inputPassword) Visual Basic
inputPassword.toUpperCase(); Java
Lower Language
inputPassword.lower() Python
LCase(inputPassword) Visual Basic
inputPassword.tolowerCase(); Java
Activity 11C
Python
Standard Library Routines – examples
1 NumPy – mathematical functions and large arrays
2 datetime – allows the use of dates
3 Scrapy – web crawler
4 Pandas – data manipulation and management
5 Matplotlib – 2D plotting
6 PyGTK – creation of programs with a GUI
VB
Standard Library functions – examples
Java
Standard Library Packages – examples
1 util – miscellaneous useful classes
2 time – date, time etc
3 math – maths calculations
4 net – networking
5 sql – accessing a relational database
6 awt – user interfaces and graphics
Activity 11D
DECLARE number1, number2, answer : REAL
DECLARE sign : STRING
OUTPUT "Please enter Number one "
INPUT number1
OUTPUT "Please enter Number two "
INPUT number2
OUTPUT "Please enter + - * or / "
INPUT sign
CASE OF sign
"+" : answer number1 + number2
"-" : answer number1 - number2
"*" : answer number1 * number2
"/" : answer number1 / number2
OTHERWISE OUTPUT "Invalid sign entered"
ENDCASE
IF sign = "+" or sign = "-" or sign = "*" or sign = "/"
THEN
OUTPUT "Answer is ", answer
ENDIF
Python
# calculations
number1 = float(input("Please enter number one "))
number2 = float(input("Please enter number two "))
sign = input("Please enter + - * or / ")
if sign =="+":
answer = number1 + number2
print("Answer is ", answer)
elif sign =="-":
answer = number1 - number2
print("Answer is ", answer)
elif sign =="*":
answer = number1 * number2
print("Answer is ", answer)
elif sign =="/":
answer = number1 / number2
print("Answer is ", answer)
else:
print("Invalid sign")
VB
'Calculations
Module Module1
Sub Main()
Dim number1, number2, answer As Decimal
Dim sign As String
Console.Write("Please enter number one ")
number1 = (Console.ReadLine())
Console.Write("Please enter number two ")
number2 = (Console.ReadLine())
Console.Write("Please enter sign ")
sign = (Console.ReadLine())
Select Case sign
Case "+"
answer = number1 + number2
Console.WriteLine("Answer is " + answer.ToString)
Case "-"
answer = number1 - number2
Console.WriteLine("Answer is " + answer.ToString)
Case "*"
answer = number1 * number2
Console.WriteLine("Answer is " + answer.ToString)
Case "/"
answer = number1 / number2
Console.WriteLine("Answer is " + answer.ToString)
Case Else
Console.WriteLine("Invalid sign")
End Select
Console.ReadKey()
End Sub
End Module
Java
//calculations
import java.util.Scanner;
class ACTIVITY11D {
public static void main(String args[]){
Scanner myObj = new Scanner(System.in);
System.out.println("Please enter Number one ");
float number1 = myObj.nextFloat();
System.out.println("Please enter Number two ");
float number2 = myObj.nextFloat();
System.out.println("Please enter + - * or / ");
String sign = myObj.next();
float answer = 0.0f;
switch (sign) {
case "+":
answer = number1 + number2;
System.out.println("Answer is " + answer);
break;
case "-":
answer = number1 - number2;
System.out.println("Answer is " + answer);
break;
case "*":
answer = number1 * number2;
System.out.println("Answer is " + answer);
break;
case "/":
answer = number1 / number2;
System.out.println("Answer is " + answer);
break;
default:
System.out.println("Invalid sign entered");
}
}
}
Activity 11E
Python
# validation
value = int (input("Please enter a number between 1 and 10 inclusive "))
while 1 > value or value > 10:
value = int (input("Please enter a number between 1 and 10 inclusive "))
VB
' validation
Module Module1
Sub Main()
Dim value As Integer
Console.Write("Please enter a number between 1 and 10 inclusive ")
value = Console.ReadLine()
While (value < 1 Or value > 10)
Console.Write("Please enter a number between 1 and 10 inclusive
")
value = Console.ReadLine()
End While
Console.ReadKey()
End Sub
End Module
Java
//validation
import java.util.Scanner;
class ACTIVITY11E {
public static void main(String args[]){
Scanner myObj = new Scanner(System.in);
int value = 0;
while (value < 1 || value > 10){
System.out.println ("Item Please enter a number between 1 and 10
inclusive ");
value = myObj.nextInt();
}
}
}
Activity 11F
Python
# line of stars
def stars():
print("**********")
stars()
VB
' line of stars
Module Module1
Sub Main()
stars()
Console.ReadKey()
End Sub
Sub stars()
Console.WriteLine("**********")
End Sub
End Module
Java
//line of stars
class ACTIVITY11F {
static void stars(){
System.out.println("**********");
}
public static void main(String args[]){
stars();
}
}
Activity 1G
Python
# line of stars with parameter
def stars(number):
for counter in range (number):
print("*", end ='')
stars(7)
VB
' line of stars with parameter
Module Module1
Sub Main()
stars(7)
Console.ReadKey()
End Sub
Sub stars(number As Integer)
Dim counter As Integer
For counter = 1 To number
Console.Write("*")
Next
End Sub
End Module
Java
//line of stars
class ACTIVITY11G {
static void stars(int number){
for (int counter = 1 ;counter <= number; counter++)
System.out.print("*");
}
public static void main(String args[]){
stars(7);
}
}
Activity 11H
// procedure to convert Celsius to Fahrenheit
DECLARE myTemp : REAL
PROCEDURE Fahrenheit (BYREF temperature : REAL)
temperature temperature * 9 / 5 +32
ENDPROCEDURE
Activity 11I
Pseudocode
// function to convert Celsius to Fahrenheit
DECLARE myTemp : REAL
FUNCTION fahrenheit (temperature : REAL)RETURNS REAL
temperature temperature * 9 / 5 +32
ENDFUNCTION
Python
# function to convert Celsius to Fahrenheit
def fahrenheit (temperature):
return temperature * 9 /5 +32
myTemp = float(input("Please enter a temperature in Celsius "))
myTemp = fahrenheit(myTemp)
print("Temperature in Fahrenheit is ", myTemp)
VB
'function to convert Celsius to Fahrenheit
Module Module1
Sub Main()
Dim myTemp As Decimal
Console.Write("Please enter a temperature in Celsius ")
myTemp = Console.ReadLine()
myTemp = fahrenheit(myTemp)
Console.WriteLine("Temperature in Fahrenheit is " +
myTemp.ToString())
Console.ReadKey()
End Sub
Function fahrenheit(ByVal temperature As Decimal) As Decimal
Return temperature * 9 / 5 + 32
End Function
End Module
Java
// function to convert Celsius to Fahrenheit
import java.util.Scanner;
class ACTIVITY11I {
static double fahrenheit(double temperature){
return temperature * 9 / 5 + 32;
}
A function is the better structure because a new value is required and this will be used in an
assignment statement making the code more efficient and easier to understand
Python
#Chapter 11 question 3 c)
import math
maxHeight = 25
maxWidth = 30
height = float(input("Please enter the height of the triangle "))
while height < 0 or height > maxHeight:
height = float(input("Please enter the height of the triangle "))
if choice == 1:
area = width * height / 2
print("The area of the triangle is ", area)
elif choice == 2:
hypotenuse = math.sqrt(height * height + width * width)
print("The hypotenuse is ", hypotenuse)
elif choice == 3:
perimeter = math.sqrt(height * height + width * width) + height + width
print("The perimeter is ", perimeter)
else:
print("Incorrect choice")
Visual Basic
Module Module1
Public Sub Main()
Dim choice As Integer
Dim height, width, maxHeight, maxWidth, area, hypotenuse, perimeter
As Decimal
maxHeight = 25
maxWidth = 30
Do
Console.Write("Please enter the height of the triangle ")
height = Decimal.Parse(Console.ReadLine())
Loop Until height > 0 And height <= maxHeight
Do
Console.Write("Please enter the width of the triangle ")
width = Decimal.Parse(Console.ReadLine())
Loop Until width > 0 And width <= maxWidth
Console.WriteLine(" Menu")
Console.WriteLine("1............ Area")
Console.WriteLine("2.......Hypotenuse")
Console.WriteLine("3........Perimeter")
End Sub
End Module
Java
import java.util.Scanner;
import java.lang.*;
class Chaper11Q3C
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
final double maxHeight = 25;
final double maxWidth = 30;
double width;
double height;
do {
System.out.println("Please enter the height of the triangle ");
height = myObj.nextDouble();
}
while (height < 0 || height > maxHeight);
do {
System.out.println("Please enter the width of the triangle ");
width = myObj.nextDouble();
}
while (width < 0 || width > maxWidth);
System.out.println(" Menu");
System.out.println("1........... Area");
System.out.println("2......Hypotenuse");
System.out.println("3.......Perimeter");
switch (choice) {
case 1:
double area = width * height / 2;
System.out.println("The area of the triangle is " + area);
break;
case 2:
double hypotenuse = Math.sqrt(height * height + width * width);
System.out.println("The hypotenuse is " + hypotenuse);
break;
case 3:
double perimeter = Math.sqrt(height * height + width * width) +
height + width;
System.out.println("The perimeter is " + perimeter);
break;
default:
System.out.println("Incorrect choice");
}
}
}
4 Library routine – a prewritten fully tested subroutine that is available to incorporate into a
program. For example, printer drivers, string handling routines.
b)
OUTPUT "Enter purchase price"
INPUT PurchasePrice
CurrentValue ← PurchasePrice
YearCount 1
WHILE YearCount < 9 AND CurrentValue >= 1000
IF YearCount = 1
THEN
CurrentValue CurrentValue * (1 – 40 / 100)
ELSE
CurrentValue CurrentValue * 0.8
ENDIF
OUTPUT YearCount, CurrentValue
YearCount YearCount + 1
ENDWHILE
Activity 12A
Activity 12B
Activity 12C
Activity 12D
// function to convert Celsius to
Fahrenheit
DECLARE myTemp : REAL
DECLARE myScale : CHAR
DECLARE finish : BOOLEAN
Finish FALSE
REPEAT
OUTPUT "Please enter value for temperature for conversion "
INPUT myTemp
OUTPUT "Please enter value C to convert to Celsius or F to convert to
Fahrenheit "
INPUT myScale
IF myTemp <> 999
THEN
CASE OF myScale
'C' : myTemp fahrenheit (myTemp)
'F' : myTemp Celsius (myTemp)
ENDCASE
OUTPUT " Temperature is ",myTemp
ELSE
finish TRUE
ENDIF
UNTIL finish
Activity 12E
Current state Event Next state
Activity 12F
PROCEDURE calculation(number1, number2, sign)
IF number2 <> 0
THEN
CASE sign OF
ˈ+ˈ : answer number1 + number2
ˈ-ˈ : answer number1 - number2
ˈ*ˈ : answer number1 * number2
ˈ/ˈ : answer number1 / number2
OTHERWISE answer 0
ENDCASE
ELSE
answer 0
ENDIF
IF answer <> 0
THEN
OUTPUT answer
ENDIF
ENDPROCEDURE
Activity 12G
Example test data
10, V 10, S 10, v 10, p ten, V −1, V
Problems:
S is not checked for
No checking that the input is numeric
Activity 12H
Example test data
Boundary for length
Lower bound Rejected Abcdef1 Accepted Abcdefg1
Upper bound Rejected Abcdefghijklmno1 Accepted Abcdefghijklmn1
Format
Rejected Abcdefgh, Abcdefg! Accepted Abcdefg1
Problems:
Multiple ways of rejection – need to devise test data that fails both the format and the length for
example abcdefghijklmno1
Activity 12I
Sample improvements:
1 Allow for repeated values to be entered.
2 Allow either upper or lower case ‘S’ or ‘V’ to be entered.
3 Reject all other values.
4 Output answers correct to 2 decimal places etc.
Activity 12J
1 Syntax error in the grammar of the source code, e.g. prnt instead of print.
Logic error in the solution provided by the program, e.g. an incorrect test for values of 60 and
over IF value > 60 THEN … does not include 60.
2 Normal data 50 should be accepted
Erroneous data 120 should be rejected
Boundary data (for integer values) 10 should be rejected, 11 should be accepted.
3 See12.3.4
2
Line
Error Correction
number
Wrong procedure name –
01 PROCEDURE ArraySort
"SortArray"
02 Wrong data type - CHAR DECLARE Temp: STRING
DECLARE FirstID, SecondID, I, J :
03 Variables undefined
INTEGER
04 Wrong 'Value2' of 100 FOR I 1 TO 99
05 Wrong range FOR J 1 TO (100 – I)
Replace MODULUS with TONUM:
06/07 Wrong function - MODULUS
FirstID TONUM(LEFT(Product[J],
06/07 Wrong value of 6 Should be 4:
Assigning wrong value to
10 Temp Product[J]
Temp
Assigning wrong value to
11 Product[J] Product[J + 1]
Product[I]
13 ENDIF
13/14 Lines reversed
14 ENDFOR
3 a) 1D-array of INTEGER.
b) i)
x DayNumber OUTPUT
0 1
1 3 5/6/2015
2 5 7/6/2015
3 7 9/6/2015
ii) The algorithm loops through days 1 to 7, adds the sales and, if they are greater than 10,
adds 1 to x and outputs the day of those sales. At the end it outputs x, the total number of
days where sales are greater than 10
Activity 13A
TYPE Tday = (Monday, Tuesday, Wednesday, Thursday, Friday,
Saturday, Sunday)
DECLARE today : Tday
DECLARE yesterday : Tday
today Wednesday
yesterday today - 1
Activity 13B
TYPE TdayPointer = ^Tday
DECLARE dayPointer : TdayPointer
dayPointer ^today
Activity 13C
1 A composite data type refers to other data types in its definition. A non-composite data type
does not refer to other data types.
2 Use defined data types allow programs to be more readable for other programmers. For
example, using the days of the week as an enumerated data type.
3 a) An enumerated data type, as a list of colours can be provided with meaningful names used
for each colour in the list.
b) A record structure that contains different types of data would be used, so the data for each
house can be used together in one structure.
c) pointer data type as this will reference the address/location of the integer stored in main
memory.
Python
# writing to a file, reading a line of text from a file,
appending a line of text
myFile = open ("myText.txt","w")
textLn = "start"
while textLn != "":
textLn = input("Please enter a line of text ")
if textLn != "":
myFile.write(textLn + "\n")
else: myFile.close()
VB
'writing to, reading from and appending to a text file
Imports System.IO
Module Module1
Sub Main()
Dim textLn As String
Dim objMyFileWrite As StreamWriter
Dim objMyFileAppend As StreamWriter
Dim objMyFileRead As StreamReader
Dim objMyFileReadAgain As StreamReader
Do
objMyFileWrite.WriteLine(textLn)
Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()
Loop Until textLn = ""
objMyFileWrite.Close()
objMyFileReadAgain.Close()
Console.ReadLine()
End Sub
End Module
Java
//writing to and reading from a text file
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
class WhatYouNeedToKnow13_2 {
try {
FileReader myFileReader = new FileReader("textFile.txt");
BufferedReader myBufferReader = new BufferedReader(myFileReader);
textLn = myBufferReader.readLine();
do {
System.out.println(textLn);
textLn = myBufferReader.readLine();
}
while(textLn != null);
myFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter myFileWriter = new FileWriter("textFile.txt", true);
PrintWriter myPrintWriter = new PrintWriter(myFileWriter);
System.out.println("Please enter a line of text ");
textLn = myObj.next();
do {
myPrintWriter.printf("%s" + "%n", textLn);
System.out.println("Please enter a line of text ");
textLn = myObj.next();
}
while (!textLn.equals("end"));
myPrintWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader myFileReader = new FileReader("textFile.txt");
} catch (IOException e) {
e.printStackTrace();
}
}
Activity 13D
As 9354 1000 is 9 remainder is 354, with 5 locations for each record, this record would be stored at
address 2175 = 500 + 353 5 and the next four locations, assuming that the first record is stored at
address 500.
Activity 13E
1 Serial file each new record is added to the end of a file, for example a log of temperature
readings taken at a weather station.
Sequential file records are stored in a given order, usually based on the key field, for example
ascending number of employee number for a personnel file.
2 See section 13.2.1
3 a) Random access as only one record is required at a time, low hit rate.
b) Sequential access as all the records need to be accessed, high hit rate.
c) Serial access, as each record is added to the end of the file in chronological order.
Activity 13F
a) 39/64 × 25 = 19.5
b) 41/128 × 27 = 41
c) 7/8 × 2−5 = 7/256 (0.02734375)
d) 15/64 × 2−4 = 15/1024 (0.0146484375)
e) 7/8 × 23 = 7
f) −13/16 × 22 = −3.25
g) −3/32 × 24 = −1.5
h) −5/8 × 25 = −20
i) −5/8 × 2−3 = −5/64 (−0.078125)
j) −1/4 × 2−6 = −1/256 (−0.00390625)
Activity 13G
1a) 0 0 1 0 1 1 0 0 0 0 0 0 0 1 1 1
b)
0 0 1 0 0 1 1 0 0 0 0 0 0 0 1 1
c)
0 0 0 1 0 1 1 0 1 1 1 1 1 0 1 1
d)
0 1 1 1 1 0 0 0 1 1 1 1 1 1 0 1
e)
0 1 0 1 0 1 0 0 0 0 0 0 0 1 0 1
f)
1 1 1 0 1 0 1 0 0 0 0 0 0 1 0 0
g)
1 0 1 1 1 0 0 0 1 1 1 1 1 1 1 1
h)
1 1 0 1 1 0 0 0 0 0 0 0 0 1 0 1
i)
1 1 1 0 0 0 0 0 1 1 1 1 1 0 1 0
..j)
1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 0
Activity 13H
a) 0.1101000 × 00000011 f) 1.0000000 × 00000100
b) 0.1100000 × 00000111 g) 1.0010000 × 00001010
c) 0.1110000 × 00000010 h) 1.0110000 × 00000000
d) 0.1000100 × 00000001 i) 0.1111000 × 11110101
e) 0.1110000 × 00000110 j) 1.0000000 × 11110000
Activity 13I
1 Largest:
0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1
Smallest magnitude:
0 1 0 0 0 0 0 0 0 0 1 0 0 0 0 0
2 Accuracy (precision) is increased by increasing size of mantissa.
Range is increased by increasing size of component.
3 a) This will cause an overflow error since the number > maximum number which can be stored.
b) underflow error will occur since division by zero generates a very small number < smallest value
which can be stored.
5 a)
File organisation
File access method
method
random sequential
serial direct
sequential
b) A – serial, as meter readings are added to the end of file and stored chronologically.
B – sequential as each customer has a unique account number and the file is sorted on the
account number and there is a high hit rate.
C – random organisation allows fastest direct access to the required record, so this is
suitable for access to individual records.
Activity 14A
1 a) Application Layer
Transport Layer
Internet/Network Layer
Network/Datalink Layer
b) Application Layer – HTTP, SMTP, POP, IMAP, DNS, FTP, SNMP
Transport Layer – TCP, SSL, TLS, UDP
Internet Layer – IPv4/6, Ethernet, ARP
Network – IEEE 802.11 etc.
c) i) SMTP
text-based protocol when sending emails
this is a push protocol.
MIME
improved version of SMTP which can handle binary files.
POP3/4
protocol used when receiving emails
this is a pull protocol.
IMAP
protocol used when receiving emails
improved version of POP3/4.
ii) MIME can handle binary file attachments when sending emails
c) They require IP to go outside local networks. The IP protocol sits on top of the Ethernet protocol.
3 a) i) Peer – this is a client in a peer-to-peer network.
ii) Swarm – connected peers that share a (data) torrent.
iii) Tracker – central server that stores details of all other computers in the swarm.
iv) Leech – peer with negative feedback from the swarm.
v) Seed – when a peer starts to upload downloaded material to other peers in the swarm.
b) The peer randomly selects other peers in the swarm, but only continue to upload to peers that
provide regular downloads. If a peer isn’t downloading then they will be isolated by other peers.
4 a) Packet header
IP address source
IP address of receiver
hop number
length of packet (in bytes)
number of packets in the message
sequence number of each packet to allow reassembly
IP protocol version.
b) Routing tables
contain information necessary to forward a package along shortest/best route to allow it to
reach its destination
as soon as a packet reaches a router, the packet heading is read and is examined and compared
to the routing table
table supplies router with instructions for sending packet (to hop) to next router.
5 Description:
This uses either an internet phone or microphone and speakers (video calls also require a
webcam).
The internet connection is only ‘live’ while data (sound/video image) is being transmitted.
Uses of voice over internet protocol (VoIP) which converts sound to digital packages (encoding)
which can be sent over the internet.
VoIP uses packet switching; the networks simply send and retrieve data as it is needed – there is
no dedicated line unlike PSTN. Data is routed through 1000s of possible pathways thus allowing
the fastest route to be determined.
The conversation (i.e. data) is split into data packages with each packet containing at least the
senders address, receivers address and order number of packet. The sending computer sends the
Cambridge International AS & A Level Computer Science 3
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
data to its router which sends the packets to another router and so on. At the receiving end the
packets are reassembled into the original state.
VoIP also carries out file compression to reduce the amount of data being transmitted.
Because the link only exists while data is being transmitted, a typical 10 minute phone call may
only contain about 3 minutes where people are talking, thus only 3MB of data is transmitted
making it much more efficient that PSTN.
Problems:
Picture and sound may not be synchronised (packets arrive at different times).
Video is not continuous (due to time delay reassembling packets in correct order).
Sound/video quality may be degraded (caused by competing network traffic).
b)
Application layer
Transport layer
Internet (network) layer
Network/Datalink layer
c) SMTP
text-based protocol when sending emails
this is a push protocol.
MIME
improved version of SMTP which can handle binary files.
POP3/4
protocol used when receiving emails
this is a pull protocol.
IMAP
protocol used when receiving emails
improved version of POP3/4.
2 a)
frame check
destination source MAC payload/data/
Ethernet type sequence/
MAC address address message
check sum
b) Metadata summarises basic information about other data
c) In the BitTorrent Protocol
file to be shared is split into pieces
peer creates small files called a torrent …
… which contains metadata about the files to be shared
tracker keeps record of all of the peers in the swarm and the parts of the file they have
tracker coordinates file distribution
peers connected to a tracker which tells them which other peers are downloading the file
peers downloading file can get pieces from different peers simultaneously
once a peer has a piece of file it can become a seed for the parts downloaded.
3 a) Circuit switching
dedicated circuit/channel/path …
… which lasts for the duration of the connection
b) Circuit switching
gives a dedicated circuit
whole bandwidth is available
faster data transfer rate
packets arrive in same order they were sent
packets cannot get lost
better for real time applications.
Packet switching
data is split into packets
data shares bandwidth
packets may arrive out of order, so there is a delay until packet order is restored
packets may get lost, so retransmission causes delays.
c) When a web page is transferred from a web server to a computer
web page divided into packets
each packet has a destination address
router looks up IP address …
… and decides where to send packet next for most efficient/shortest path
packets can take different routes
home computer software reassembles packets to rebuild web page.
4 a)
circuit packet
statements
switching switching
a dedicated circuit/path is needed at all times
the same route/circuit is used for every packet
in the message
bandwidth is shared with other packets of data
none of the bandwidth available is wasted
during transmission
packets arrive at the destination in the correct
order
b) i) Hop number is a number in a header used to stop packets which never reach their destination
from clogging up routes.
ii) Checksum is a number generated from a set of data which is transmitted with the data. The
receiver also calculates the checksum to ensure no transmission errors have occurred.
c) Routing tables
contain information necessary to forward a package along shortest/best route to allow it to
reach its destination
as soon as a packet reaches a router, the packet header is read and is examined and compared
to the routing table
table supplies router with instructions for sending packet (to hop) to next router.
Activity 15A
1 a)
RISC processor architecture has fewer built-in instructions which can actually lead to higher
computer performance.
RISC design strategy is built on simple instructions which is achieved by breaking up
complex instructions into simpler sub-operations where each instruction requires one clock
cycle.
b) CISC features:
many instruction formats are possible
there are more addressing modes
makes use of multi-cycle instructions
instructions can be of a variable length
longer execution time for instructions
decoding of instructions is more complex
it is more difficult to make pipelining work
the design emphasis is on the hardware
uses the memory unit to allow complex instructions to be carried out.
RISC features:
uses fewer instruction formats/sets
uses fewer addressing modes
makes use of single-cycle instructions
instructions are of a fixed length
faster execution time for instructions
makes use of general multi-purpose registers
easier to make pipelining function correctly
the design emphasis is on the software
processor chips require fewer transistors.
2 a) Von Neumann bottleneck:
shared bus between program memory and data memory leads to the bottleneck …
… so, throughput limitation due to inadequate data transfer rates between memory and CPU
…
… this causes CPU to wait and remain idle for a period of time while low speed memory is
being accessed.
b) This slows down the performance of a computer system.
3 a) In a cluster, each machine is independent of the other computers in terms of memory and back-
up store; the computers are interconnected in some variation of a network.
In massively parallel processing there is really only one machine with many thousands of
CPUs/processors interconnected.
b) There are many applications in scientific and medical research (reader should pick one example
form a huge list).
4 A = LOAD A
B = LOAD B
C = LOAD C
D = ADD A,B,C
E = STORE D
F = OUT D
0 0 0 1
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 0
2
P Q R X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
b)
c)
S1 S2 S3 W
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
Activity 15B
1 a) A. B A. C A. D B. C. D
b) Let X = original expression; thus X (from a Karnaugh map) gives: A. B. C. D
Using de Morgan’s Law then gives: A B C D
c)
A. B. C A. B. C A. B. C A. B. C
⇒ B. C. A A B. C. A A
⇒ B. C. 1 B. C. 1
⇒ B. C C ⇒ B. 1
⇒B
d)
A. A B B A. A . A B
⇒ A. A A. B B A .A B A .B
⇒ A. B B A .A B A .B
⇒ A. B B. A A. A B. B A. B
⇒ A. B B. A A A. B
⇒ A. B A. B A. 1 A. B
⇒ A. B A. B 1 B
⇒ A. B A ⇒ A A. B ⇒ A A . A B
⇒A B
e)
A C . A. D A. D A. C C
⇒ A C . A. D D A. C C
⇒ A C . A. A. C C
⇒ A. A C C C
⇒ A. A C C ⇒ A. A A. C C ⇒ A A 1 .C
⇒A C
Activity 15C
1
Input Output
A B S Cout
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1
2
Input Output
A B Cin S Cout
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1
Activity 15D
1
A B X
0 0 1
0 1 1
1 0 1
1 1 0
Simplified circuit is a NAND gate:
.
A B
2
A B X Y
0 0 0 0
0 1 1 0
1 0 1 0
1 1 0 1
Simplified circuit:
Activity 15E
1 a)
A B C D X
0 0 0 0 0
0 0 0 1 0
0 0 1 0 0
0 0 1 1 1
0 1 0 0 0
0 1 0 1 1
0 1 1 0 0
0 1 1 1 1
1 0 0 0 0
1 0 0 1 0
1 0 1 0 0
1 0 1 1 1
1 1 0 0 0
1 1 0 1 1
1 1 1 0 0
1 1 1 1 1
2 a)
A B C X
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 0
1 1 0 1
1 1 1 1
b) B AB
00 01 11 10
C
0 0 1 1 0
1 0 1 1 0
3 a)
A B C D X
0 0 0 0 1
0 0 0 1 1
0 0 1 0 1
0 0 1 1 1
0 1 0 0 1
0 1 0 1 1
0 1 1 0 1
Cambridge International AS & A Level Computer Science 8
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
0 1 1 1 1
1 0 0 0 1
1 0 0 1 1
1 0 1 0 0
1 0 1 1 0
1 1 0 0 0
1 1 0 1 0
1 1 1 0 0
1 1 1 1 0
b) A. B. C A
AB
CD
00 01 11 10
00 1 1 0 1
01 1 1 0 1
11 1 1 0 0
10 1 1 0 0
c)
2 a) i) ii) 𝐀 𝐁. 𝐃 𝐁. 𝐂
AB
00 01 11 10
CD
00 0 0 1 1
01 0 1 1 1
11 1 1 1 1
10 1 0 1 1
b) i)
A C . A. D A. D A. C C
⇒ A. C . A. D D A. C C
⇒ A C . A A. C C
⇒ A. A C C C
⇒ A. A C C
⇒ A. A A. C C
⇒A A 1 .C
⇒A C
ii)
A. A B B A. A . A B
⇒ A. A A. B B A .A B A .B
⇒ A. B B A .A B A .B
⇒ A. B B. A A. A B. B A. B
⇒ A. B B. A A A. B
⇒ A. B A B 1 B
⇒ A. B A
⇒ A A . A B
⇒A B
3 a) i)
INPUTS OUTPUTS
S R Q Q comment
1 0 1 0
0 0 1 0 following S = 1 change
0 1 0 1
0 0 0 1 following R = 1 change
1 1 0 0
ii) S = 1, R = 1, Q = 0, Q = 0 this is an invalid case since Q should be the compliment
(opposite) of Q
b) i) two input values, J and K, and synchronisation (clock pulse) input
ii) uses a toggle which removes the invalid S, R states when using SR flip-flop
iii) Uses
Several JK flip-flops can be used to produce SHIFT REGISTERS in a computer.
Cambridge International AS & A Level Computer Science 10
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
A simple binary counter can be made from linking up several JK flip-flop circuits (this
requires the toggle function).
4 a) SISD (single instruction single data)
uses a single processor that can handle a single instruction which uses one data source at a
time
each task is processed in sequential order.
SIMD (single instruction multiple data)
uses several processors which execute the same instruction set but use different data inputs
all processes do same calculations but on different data sets simultaneously.
MISD (multiple instruction single data)
uses several processors
each processor uses different instructions but uses same shared data.
MIMD (multiple instruction multiple data)
uses several processors
each processor can accept its own instructions independently
each processor uses data from a separate data stream (e.g. single memory which has been
partitioned).
b) Features of parallel processing:
It is a much faster way to handle large volumes of independent data.
The data used sometimes relies on the result of a previous operation, therefore such data
cannot be handled in parallel.
Data sets require the same processing for it to work.
It overcomes the von Neumann bottleneck and therefore greatly improves CPU performance.
Parallel processing requires more expensive hardware.
c)
Eight instructions need 12 clock cycles when using pipelining.
Without pipelining, it would require 8 × 5 = 40 clock cycles to complete (each of the 8
instructions requires 5 processing stages: IF, ID, OF, IF and WB).
5 a)
c i) ii)
PQ
R
00 01 11 10
0 0 0 0 0
1 1 1 0 0
iii) S P. R
d)
S P Q R .R
⇒S P. Q . R . R
⇒S P. R Q . R. R
⇒S P. R Q . 0
⇒S P. R 0
⇒S P. R
b)
Static libraries – where software being developed is linked to executable code in the library at
the time of compilation. The library routines would be embedded directly into the new program
code.
Dynamic – where software being developed is not linked to the library routines until actual run
time (these are known as dynamic link library files or DLL). These library routines would be
stand-alone files only being accessed as required by the new program. The routines will be
available to several applications at the same time).
Activity 16A
1 A 6 D 11 E
2 B 7 E 12 C
3 B 8 C 13 E
4 C 9 B 14 A
5 E 10 A 15 E
Activity 16B
34 85 04 83
Activity 16C
1 Valid variables are:
A1 letter (must be A, B or C) followed by digit (must be 1, 2 or 3)
C3 letter (must be A, B or C) followed by digit (must be 1, 2 or 3).
2 Invalid statements are:
A1 = A1 + B1 + C1 can only have 2 variables on the right-hand side of the assignment
statement
A1 := C1 – C2 := is not included in the syntax diagram for an assignment statement.
Activity 16D
Letter Digit
Variable
Letter
Letter Digit
A 0
B 1
C
2
D
3
Activity 16E
<integer> ::= <digit> | <integer> <digit>
Activity 16F
1 Lexical analysis, Syntax analysis, Code generation and Optimisation
– see section 16.3.2
2 a)
Letter Digit
I
0
J 1
K 2
Assignment
Variable = Variable Operator Variable
3 a) i) A B C D * + +
ii) A B C + + D *
iii) A B + D * A B – C * +
b) i)
2
5 10
3 3 13
7 7 7 20
ii)
5
3 8 2
7 7 15 30
iii)
3 5
3 2 7 4 4 20
7 10 20 20 20 20 20 40
ii)
page presence flag page frame address additional data
6 1 221 12:07:34:49
iii)
When the procedure call is made, Page 1 is swapped out and Page 3 is swapped in.
At the end of the procedure call, Page 3 is swapped out and Page 1 is swapped in.
Page 1/3 is always in memory the shortest amount of time.
The entire sequence is repeated for every iteration.
iv) Thrashing/continuously swapping pages
3 a) quantum g) non-preemptive
b) pre-emptive
h) burst
c) virtual memory
i) segmentation
d) low level scheduler
j) starvation
e) context switching
f) paging
b) i) FIFO:
When using first in first out (FIFO), the OS keeps track of all pages in memory using a
queue structure
The oldest page is at the front of the queue and is the first to be removed when a new page
needs to be added.
FIFO algorithms don’t consider page usage when replacing pages; a page may be replaced
simply because it arrived earlier than another page.
It suffers from, what is known as, Belady’s Anomaly where it is possible to have more
page faults when increasing the number of page frames.
ii) OPR:
Optimal page replacement looks forward in time to see which frame it can replace in the
event of a page fault.
The algorithm is actually impossible to implement; at the time of a page fault, the OS has
no way of knowing when each of the pages will be replaced next.
It tends to get used for comparison studies but has the advantage that it is free of Belady’s
Anomaly and also has the fewest page faults.
iii) LRU:
With least recently used page replacement (LRU), the page which has not been used for
the longest time is replaced.
To implement this method, it is necessary to maintain a linked list of all pages in memory
with the most recently used page at the front and the least recently used page at the rear.
6 a)
b) paging is fixed size; segmentation is variable size; pages are smaller than segments
c) Types of interrupts
device interrupt (e.g. printer out of paper)
exception (e.g. division by zero)
trap/software interrupt (e.g. software needs to access/use a resource).
7 a)
Token
Symbol
Value Type
Start 60 Variable
0.1 61 Constant
Counter 62 Variable
10 63 Constant
b)
60 01 61 4E 62 01 60 50 63 52 62 02 60 53
c) i) Syntax analysis
ii) Checking the grammar of the program and producing an error report.
d) i) Minimise the time taken to execute the program.
ii) Replace 2 * 6 with the value 12
iv)
LDD 436
ADD 437
STO 612
ADD 438
STO 613
8 a) i) There should be a colon before the equals sign.
ii) The second operand should be an unsigned integer and not a variable.
iii) A32 is not a variable, as a variable should be a letter followed by a single digit.
b)
<assignment_statement> ::= <variable> := <variable> <operator>
<unsigned_integer>
<variable> ::= <letter> <digit>
<unsigned_integer> ::= <digit> | <digit> <unsigned_integer>
<letter> ::= A | B | C
<operator> ::= + | - | * | ^
c)
Variable
d)
<assignment_statement> ::= <variable> := <variable> <operator> <real>
9 a)
Statement Compilation stage
This stage can improve
the time taken to execute Lexical analysis
the statement: x = y + 0
b) P Q + R S / -
c) i)
2
3 3 5
2 1 1 1 1 6
2 2 4 4 4 4 4 4 -2
ii) b * a - (c + d + a)
iii) In RPN evaluation of operators is left to right so there is no need for brackets to
establish precedence.
Chapter 17 answers
What you should already know
1 i) Data integrity – data stored on a computer should always be accurate/consistent and kept up to
date.
ii) Data privacy – this refers to the need to ensure a user’s data remains private and unauthorised
access to their data is prevented.
iii) Data security – this refers to the recovery of data if it is lost/deleted, but also refers to ways of
preventing unauthorised access to data on a system.
2 Data recovery refers to:
Accidental loss of data:
use of back-ups in case the data is lost or corrupted through an accidental operation.
save data on a regular basis
use of passwords and user ids to restrict access to authorised users only.
Hardware malfunction:
use of back-ups in case the data is lost or corrupted through an accidental operation
save data on a regular basis
use of passwords and user ids to restrict access to authorised users only.
Software malfunction:
use of back-ups in case the data is lost or corrupted through the software fault
save data on a regular basis in case the software suddenly “freezes” or “crashes” whilst the
user is working on it.
Incorrect computer operation:
use of back-ups in case the data is lost or corrupted through wrong operation
correct training procedures so that users are aware of the correct operation of hardware.
In all cases the regular backing up of data is a key component to data recovery. If data becomes corrupted
or lost by one of the methods describe above, it is possible to reinstall the affected data from the back-
ups. Back-ups should be made on a regular basis (either automatically or manually at the end of the day)
onto another medium (such as cloud storage, CD/DVD, memory stick or removable HDD/SSD) and the
back-up should be stored in a separate location in case of fire, etc. A person should be appointed to do
the back-ups to make sure it is done. It is important to realise that backing up data may not be a suitable
method of recovery in the case of data loss or corruption through a virus infection. Unfortunately, the
backed-up data may contain strands of the virus which would simply re-infect the ‘cleaned’ computer if
an attempt was made to reinstate this data. Increasingly the preferred method of storing data in another
location is the use of managed cloud storage.
3 Protect against data loss by:
user accounts which authenticate the user (account number/name and password)
use of access rights (level of access to data)
digital signatures
firewalls (to monitor traffic and help reduce hacking and other eavesdropping risks)
use of anti-spyware, anti-virus software, for example
encryption can help in prevention of data loss
biometrics (fingerprint, facial, recognition, for example) can restrict access to sensitive data
Cambridge International AS & A Level Computer Science 1
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
backups to guard against loss due to software crash; hardware failure or power loss
multiple backups in case of back up failure
use of uninterruptable power supply (UPS) or power filters to protect against data loss through
power failure
ensuring system warns user it is still writing to a removable device.
4 a) i) Hacking
Hacking can lead to loss of data or illegal use of data (e.g. access to bank details) with
serious consequences for data security, data privacy and data integrity.
Hacking is illegal access to a computer without user’s permission.
ii) Malware
There are many forms of malware (e.g. virus, Trojan horses and spyware, for example).
The effects of malware can vary from
corrupting data/exec files stored on a computer
replacement of legitimate software with malicious software
to monitoring a user’s key presses.
All of these can lead to loss/corruption of data, allowing access to personal data and so
on.
iii) Phishing
This occurs when a user opens an email (or attachment) from what seems to be a
legitimate source/company only to be redirected to a fake website where personal details
can be accessed.
iv) Pharming
This is slightly more alarming than phishing since it doesn’t require any action by a user.
Code is placed on a user’s hard drive or on the web server and when user types in a
targeted website, they are sent to a fake website without their knowledge – this again can
lead to personal data being accessed by a hacker, for example.
b) methods of guarding against the above include:
use of passwords
authentication techniques
running up-to-date virus checkers/spyware checkers
encryption
only open emails from secure sources, and so on.
Activity 17A
1 A 5 A 9 C
2 B 6 A 10 B
3 B 7 C
4 E 8 D
103 (MOD 11) = 1000 (MOD 11) 25 (MOD 11) = 32 (MOD 11)
= 90 remainder 10 = 2 remainder 10
47 (MOD 11) = 16384 (MOD 11) 66 (MOD 11) = 46656 (MOD 11)
= 1489 remainder 5 = 4241 remainder 5
Chapter 18 answers
What you should already know
1 Artificial Intelligence
is a machine which carries out a task that requires some degree of ‘human’ intelligence
duplicates human tasks requiring decision-making and problem-solving skills.
2 AI pros and cons
technologies such as autonomous vehicles
artificial limb technology helping the disabled
improvements in medical areas
job losses in many areas
dependence by humans on the technology
loss of skills since taken over by AI.
3 Examples of the use of AI
robotics
predictions such as climate change
performing delicate operations
bespoke cancer treatments
drones in bomb disposal, welding, nuclear incidents, and so on.
Activity 18A
Shortest route: A B C F I
Activity 18B
1 ‘A’ has two nodes ‘B’ and ‘F’
F(B) = 6 + 8 = 14, F(F) = 3 + 6 = 9
since F(F) < F(B) then ‘F’ is the next start node
Path: A → F
‘F’ has two nodes ‘G’ and ‘H’
F(G) = ((3 + 1) + 5) = 9, F(H) = ((3 + 7) + 3) = 13
since F(G) < F(H) then ‘G’ is the next start node
Path: A → F → G
‘G’ has one node, ‘I’
so F(I) = 7 + 1 = 8
Path: A → F → G → I
‘I’ has three nodes ‘E’, ‘H’ and ‘J’
F(E) = ((3 + 1 + 3 + 5) + 3) = 15
F(H) = ((3 + 1 + 3 + 2) + 3) = 12
F(J) = ((3 + 1 + 3 + 3) + 0) = 10
F(J) has the smallest value …
3 a)
b) shortest route: E B C D G
4 a) i)
Activity 18C
1 a) Narrow AI – machine which is superior to a human when doing a specific task.
General AI – machine which is similar in performance to a human in any intellectual task.
Strong AI – machine which is superior to a human in many tasks.
b) Reward and punishment
The machine learns from good results and bad results to help improve the
performance/produce optimal outcomes.
For example, search engines:
The number of hits shown on the first page (matching search criteria) is very high
indicates a good result.
If user needs to look at page 2, page 3, … then this is seen as a bad result and the search
engine would need to learn from these two outcomes to improve future performance.
c) Artificial neural networks:
Are artificial networks based on the biology of the human brain in its inter-connections
between neurons.
Makes use of input, output and hidden layers.
Has hidden layers are where the inputs are processed to produce output(s).
For example, the following diagram shows an artificial neural network (with two hidden
layers):
2 a) i) Supervised learning
are systems able to predict future outcomes based on past data.
uses labelled data
uses both inputs and outputs to train the model.
ii) Unsupervised learning
are systems able to identify hidden patterns based on input data provided
systems are not trained on ‘right’ answers.
iii) Reinforcement learning
are systems given no training …
… but learns on the basis of ‘reward and punishment’ when performing an action to
determine which action yields optimal outcomes.
Cambridge International AS & A Level Computer Science 4
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
b)
2 a) i) Reinforcement learning
given no training
learns using ‘reward and punishment’
uses optimisation techniques.
ii) Supervised learning
requires both input and output so model can be trained
once trained, uses labelled data and results compared to what they should be
uses regression and classification analysis.
b) i) Chat bots
interact through instant messaging, artificially replicating patterns of human interaction
uses machine learning.
ii) Search engines
measures success of search based on whether website/web page comes up as first page of
search
if not on first page, this is seen as a failure and system adapts to improve the search
process.
b) i)
ii) Route: C A S H N Q
5
a) ii) route: A B F G K L
b) A → D = 30 min}
D → H = 12 min} total = 62 mins
H → L = 20 min}
A → I = 20 min }
I → J = 14 min } total = 69 mins
J → K = 20 min }
K → L = 15 min}
4
DECLARE myList : ARRAY[0:19] OF INTEGER
DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE swap : BOOLEAN
DECLARE temp : INTEGER
DECLARE top : INTEGER
upperBound 19
lowerBound 0
top upperBound
REPEAT
Swap FALSE
FOR index = lowerBound TO top - 1
IF myList[index] > myList[index + 1]
THEN
temp myList[index]
myList[index] myList[index + 1]
myList[index + 1] temp
swap TRUE
ENDIF
NEXT
top top -1
UNTIL (NOT swap) OR (top = 0)
5 Answers given
Activity 19A
Python
#Python program for Linear Search
#create array to store all the numbers
myList = [4, 2, 8, 17, 9, 3, 7, 12, 34, 21]
found = False
if(found):
print("Item found")
else:
print("Item not found")
VB
'VB program for Linear Search
Module Module1
Public Sub Main()
Dim index As Integer
Dim item As Integer
Dim found As Boolean
'Create array to store all the numbers
Dim myList() As Integer = New Integer() {4, 2, 8, 17, 9, 3, 7, 12, 34,
21}
If (found) Then
Console.WriteLine("Item found")
Else : Console.WriteLine("Item not found")
End If
Console.ReadKey()
End Sub
End Module
Java
//Java program Linear Search
import java.util.Scanner;
class ACTIVITY19A
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
//Create array to store the all the numbers
int myList[] = new int[] {4, 2, 8, 17, 9, 3, 7, 12, 34, 21};
int item, index;
boolean found = false;
}
}
Activity 19B
4 comparisons to find the letter D
A and B take fewer comparisons
Activity 19C
Python
#Python program for Binary Search
#create sorted list to store all the numbers
myList = [16, 19, 21, 27, 36, 42, 55, 67, 76, 89]
found = False
lowerBound = 0
upperBound = len(myList) - 1
if(found):
print("Item found")
else:
print("Item not found")
VB
'VB program for Binary Search
Module Module1
Public Sub Main()
Dim index, lowerBound, upperBound As Integer
Dim item As Integer
Dim found As Boolean
'Create array to store all the numbers
Dim myList() As Integer = New Integer() {16, 19, 21, 27, 36, 42,
55, 67, 76, 89}
found = False
lowerBound = 0
upperBound = myList.Length - 1
Do
index = (upperBound + lowerBound) \ 2
If (found) Then
Console.WriteLine("Item found")
End If
Console.ReadKey()
End Sub
End Module
Java
//Java program Binary Search
import java.util.Scanner;
class ACTIVITY19C
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
//Create array to store the all the numbers
int myList[] = new int[] {16, 19, 21, 27, 36, 42, 55, 67, 76, 89};
do
{
index = (upperBound + lowerBound) / 2;
if (myList[index] == item)
{
found = true;
}
if (item > myList[index])
{
lowerBound = index + 1;
}
if (item < myList[index])
{
upperBound = index - 1;
}
if (found)
{
System.out.println("Item found");
}
else
{
System.out.println("Item not found");
}
}
}
Activity 19D
Python
#Python program for Insertion Sort
myList = [4,46,43,27,57,41,45,21,14]
lowerBound = 0
upperBound = len(myList)
VB
'VB program for insertion sort
Module Module1
Sub Main()
Dim myList() As Integer = New Integer() {4, 46, 43, 27, 57, 41, 45, 21, 14}
Dim index, lowerBound, upperBound, place, myKey, temp As Integer
upperBound = myList.Length - 1
lowerBound = 0
End Sub
End Module
Java
public class ACTIVITY19D {
int insertPlace = 0;
for (int place = index-1; place >= lowerBound; place--) {
if (myList[place] > myKey) {
myList[place+1] = myList[place];
} else {
insertPlace = place+1;
break;
}
}
myList[insertPlace] = myKey;
}
Activity 19E
Python
stack = [None for index in range(0,10)]
basePointer = 0
topPointer = -1
stackFull = 10
item = None
def push(item):
global topPointer
if topPointer < stackFull - 1:
topPointer = topPointer + 1
stack[topPointer] = item
else:
print("Stack is full, cannot push")
def pop():
global topPointer, basePointer, item
if topPointer == basePointer -1:
print("Stack is empty,cannot pop")
else:
item = stack[topPointer]
topPointer = topPointer - 1
push(7)
push(32)
print (*stack)
pop()
print(item)
pop()
print(item)
pop()
print(*stack)
push(1)
print(*stack)
push(2)
print(*stack)
push(3)
print(*stack)
push(4)
print(*stack)
push(5)
print(*stack)
push(6)
print(*stack)
push(7)
print(*stack)
push(8)
print(*stack)
push(9)
print(*stack)
push(10)
print(*stack)
push(11)
Note:
There is an automated method for printing the stack in Python that has been included in the program.
For VB and Java you could write the function that would print the stack, using a loop and use it to
show the contents of the stack at each stage.
VB
'VB program for stack
Module Module1
Public stack() As Integer = {Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing, Nothing, Nothing,
Nothing}
Public basePointer As Integer = 0
Public topPointer As Integer = -1
Public Const stackFull As Integer = 10
Public item As Integer
Sub Main()
push(7)
push(32)
pop()
Console.WriteLine(item)
pop()
Console.WriteLine(item)
pop()
push(1)
push(2)
push(3)
push(4)
push(5)
push(6)
push(7)
push(8)
push(9)
push(10)
push(11)
Console.ReadKey() 'wait for keypress
End Sub
Sub pop()
If topPointer = basePointer - 1 Then
Console.WriteLine("Stack is empty, cannot pop")
Else
item = Stack(topPointer)
topPointer = topPointer - 1
End If
End Sub
Java
//Java program for a stack
import java.util.Scanner;
class ACTIVITY19E
{
public static int stack[] = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
public static int basePointer = 0;
public static int topPointer = -1;
public static final int stackFull = 10;
public static int item;
pop();
System.out.println(item);
pop();
push(1);
push(2);
push(3);
push(4);
push(5);
push(6);
push(7);
push(8);
push(9);
push(10);
push(11);
}
}
Activity 19F
Python
queue = [None for index in range(0,10)]
frontPointer = 0
rearPointer = -1
queueFull = 10
queueLength = 0
def enQueue(item):
global queueLength, rearPointer
if queueLength < queueFull:
if rearPointer < len(queue) - 1:
rearPointer = rearPointer + 1
else:
rearPointer = 0
queueLength = queueLength + 1
queue[rearPointer] = item
else:
print("Queue is full, cannot enqueue")
def deQueue():
global queueLength, frontPointer, item
if queueLength == 0:
print("Queue is empty,cannot dequeue")
else:
item = queue[frontPointer]
queue[frontPointer] = None
if frontPointer == len(queue) - 1:
frontPointer = 0
else:
frontPointer = frontPointer + 1
queueLength = queueLength -1
enQueue(7)
enQueue(32)
print (*queue)
deQueue()
print(item)
deQueue()
print(item)
deQueue()
print(*queue)
enQueue(1)
print(*queue)
enQueue(2)
print(*queue)
enQueue(3)
print(*queue)
enQueue(4)
print(*queue)
enQueue(5)
print(*queue)
enQueue(6)
print(*queue)
enQueue(7)
print(*queue)
enQueue(8)
print(*queue)
enQueue(9)
print(*queue)
enQueue(10)
print(*queue)
enQueue(11)
Note:
There is an automated method for printing the stack in Python that has been included in the program.
For VB and Java you could write the function that would print the stack, using a loop and use it to
show the contents of the stack at each stage.
VB
'VB program for a queue
Module Module1
Console.ReadKey()
enQueue(7)
enQueue(32)
deQueue()
Console.WriteLine(item)
deQueue()
Console.WriteLine(item)
deQueue()
Console.ReadKey()
enQueue(1)
enQueue(2)
enQueue(3)
enQueue(4)
enQueue(5)
enQueue(6)
enQueue(7)
enQueue(8)
enQueue(9)
enQueue(10)
enQueue(11)
Console.ReadKey()
End Sub
Sub enQueue(ByVal item)
If queueLength < queueFull Then
If rearPointer < queue.length - 1 Then
rearPointer = rearPointer + 1
Else
rearPointer = 0
End If
queueLength = queueLength + 1
queue(rearPointer) = item
Cambridge International AS & A Level Computer Science 13
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers
Else
Console.WriteLine("Queue is full, cannot enqueue")
End if
End Sub
Sub deQueue()
If queueLength = 0 Then
Console.WriteLine("Queue is empty, cannot dequeue")
Else
item = queue(frontPointer)
If frontPointer = queue.length - 1 Then
frontPointer = 0
Else
frontPointer = frontPointer + 1
End if
queueLength = queueLength - 1
End If
End Sub
End Module
Java
//Java program for a queue
import java.util.Scanner;
class Queue
{
public static int queue[] = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
public static int frontPointer = 0;
public static int rearPointer = -1;
public static final int queueFull = 10;
public static int queueLength = 0;
public static int item;
deQueue();
System.out.println(item);
deQueue();
enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);
enQueue(6);
enQueue(7);
enQueue(8);
enQueue(9);
enQueue(10);
enQueue(11);
}
}
myLinkedList = [27, 19, 36, 42, 16, None, None, None, None, None, None,
None]
myLinkedListPointers = [-1, 0, 1, 2, 3, 6, 7, 8, 9, 10, 11, -1]
heapStartPointer = 5
startPointer = 4
nullPointer = -1
def delete(itemDelete):
global startPointer, heapStartPointer
if startPointer == nullPointer:
print("Linked List empty")
else:
index = startPointer
while myLinkedList[index] != itemDelete and index !=
nullPointer:
oldindex = index
index = myLinkedListPointers[index]
if index == nullPointer:
print("Item ", itemDelete, " not found")
else:
myLinkedList[index] = None
tempPointer = myLinkedListPointers[index]
myLinkedListPointers[index] = heapStartPointer
heapStartPointer = index
myLinkedListPointers[oldindex] = tempPointer
def insert(itemAdd):
global startPointer, heapStartPointer
if heapStartPointer == nullPointer:
print("Linked List full")
else:
tempPointer = startPointer
startPointer = heapStartPointer
heapStartPointer = myLinkedListPointers[heapStartPointer]
myLinkedList[startPointer] = itemAdd
myLinkedListPointers[startPointer] = tempPointer
def find(itemSearch):
found = False
itemPointer = startPointer
while itemPointer != nullPointer and not found:
if myLinkedList[itemPointer] == itemSearch:
found = True
else:
itemPointer = myLinkedListPointers[itemPointer]
return itemPointer
VB
'VB program for a linked list
Module Module1
Public Dim myLinkedList() As Integer = {27, 19, 36, 42, 16, Nothing,
Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}
Public Dim myLinkedListPointers() As Integer = {-1, 0, 1, 2, 3, 6, 7, 8,
9, 10, 11, -1}
End if
End Sub
myLinkedList(index) = nothing
tempPointer = myLinkedListPointers(index)
myLinkedListPointers(index) = heapStartPointer
heapStartPointer = index
myLinkedListPointers(oldIndex) = tempPointer
End if
End If
End Sub
End Module
Java
//Java program for a linked list
import java.util.Scanner;
class ACTIVITY19GHI
{
public static int myLinkedList[] = new int[] {27, 19, 36, 42, 16, 0, 0,0, 0,
0, 0};
public static int myLinkedListPointers[] = new int[] {-1, 0, 1, 2, 3, 6, 7, 8,
9, 10, 11, -1};
public static int startPointer = 4;
public static int heapStartPointer = 5;
public static final int nullPointer = -1;
if (startPointer == nullPointer)
System.out.println("Linked List is empty");
else
{
{
myLinkedList[index] = 0;
int tempPointer = myLinkedListPointers[index];
myLinkedListPointers[index] = heapStartPointer;
heapStartPointer = index;
myLinkedListPointers[oldIndex] = tempPointer;
}
}
}
System.out.println();
if (result != -1 )
{
System.out.println("Item found");
}
else
{
System.out.println("Item not found");
}
}
}
For 19H
startPointer heapStartPointer itemAdd tempPointer
Already set to 4 Already set to 5 18
5 6 4
6 7 25 5
The linked list, myLinkedList will now be as shown below.
mylinkedList myLinkedListPointers
[0] 27 −1
[1] 19 0
[2] 36 1
[3] 42 2
[4] 16 3
[5] 18 4
startPointer → [6] 25 5
heapStartPointer → [7] 8
[8] 9
[9] 10
[10] 11
[11] −1
For 19I
startPointer heapStartPointer itemDelete index oldIndex tempPointer
Already set to 6 Already set to 7 5 5
6 4 18 4 4 2
3
mylinkedList myLinkedListPointers
[0] 27 −1
[1] 19 0
[2] 36 1
[3] 42 2
heapStartPointer → [4] 16 7
[5] 18 3
startPointer → [6] 25 5
[7] 8
[8] 9
[9] 10
[10] 11
[11] −1
Activity 19J
/
‐ +
x y * z
x y
Activity 19K
TYPE node
DECLARE item : STRING
DECLARE leftPointer : INTEGER
DECLARE rightPointer : INTEGER
ENDTYPE
DECLARE myTree[0 : 49] OF node
DECLARE rootPointer : INTEGER
DECLARE nextFreePointer : INTEGER
Activity 19L
rootPointer itemPointer itemSearch
0 0 55
2
3
5
8
Activity 19M
leftBranch nextFreePointer itemAddPointer rootPointer itemAdd itemPointer oldPointer
10 10 0 25 0 0
11
TRUE 1 1
FALSE 6 6
FALSE −1
[0] 27 1 2
[1] 19 4 6
[2] 36 −1 3
[3] 42 −1 5
[4] 16 −1 7
[5] 89 8 −1
[6] 21 −1 10
[7] 17 −1 −1
[8] 55 −1 −1
[9] 18 −1 −1
[10] 25 −1 −1
[11] −1
Activity 19N
Path = {School, Town centre, Shopping centre, Gardens}
Path = {Town centre, School, Train station}
Path = {Town centre, Shopping centre, Gardens, Town centre}
Activity 19O
// a linked list to store names
TYPE linkedList
DECLARE name : STRING
DECLARE pointer : INTEGER
ENDTYPE
REPEAT
index startPointer
OUTPUT myLinkedList[index].name
Index myLinkedList[index].pointer
UNTIL index = -1
Activity 19P
Python
#using a dictionary in Python
studentdict ={
"Leon":27,
"Ahmad":78,
"Susie":64
}
print (studentdict)
score = studentdict["Leon"]
print(score)
studentdict["Mo"] = 99
print (studentdict)
del studentdict["Ahmad"]
print (studentdict)
VB
'using a dictionary in VB
Module Module1
Sub Main()
Dim studentdict As New Dictionary(Of String, Integer)
Dim studentScore As Integer
Dim studentName As String
studentdict.Add("Leon", 27)
studentdict.Add("Ahmad", 78)
studentdict.Add("Susie", 64)
For Each item As KeyValuePair(Of String, Integer) In studentdict
studentName = item.Key
studentScore = item.Value
Console.WriteLine(studentName + " " + studentScore.ToString)
Next
If studentdict.ContainsKey("Ahmad") Then
studentScore = studentdict.Item("Ahmad")
Console.WriteLine(studentScore)
End If
Console.WriteLine()
studentdict.Remove("Ahmad")
For Each item As KeyValuePair(Of String, Integer) In studentdict
studentName = item.Key
studentScore = item.Value
Console.WriteLine(studentName + " " + studentScore.ToString)
Next
Console.ReadKey()
End Sub
End Module
Java
//Java program for a dictionary
import java.util.*;
class ACTIVITY19P
{
public static void main(String[] args)
{
// creating a My HashTable Dictionary
Hashtable<String, Integer> studentdict = new
Hashtable<String, Integer>();
System.out.println(studentdict);
Activity 19Q
1 a) see Figure 19.10
b) see Figure 10.12
2 a) an ADT that consists of pairs a key and a value, they key is used to find the value
b)
TYPE linkedList
DECLARE item : STRING
DECLARE Pointer : INTEGER
ENDTYPE
TYPE dictionary
DECLARE key : myLinkedList : ARRAY [0:19] OF linkedList
DECLARE value : ARRAY [0:19] OF STRING
ENDTYPE
3 For a linear search the time to perform a search will increase linearly as the number of items in the
list increases, the time taken is directly proportional to the number of items in the list. In big O
notation, this is O(N) where N is the number of items in the list.
For a binary search the time to perform a search will increase linearly as the number of items in
the list increases exponentially, the time taken is logarithmically proportional to the number of
items in the list. In big O notation, this is O(log N) where N is the number of items in the list.
Therefore a binary search becomes more time efficient than a linear search as the number of items
in the list increases.
Activity 19R
Python
#Python program recursive factorial function
def factorial(number):
if number == 0:
answer = 1
else:
answer = number * factorial(number - 1)
return answer
print(factorial(0))
print(factorial(5))
VB
'VB program recursive factorial function
Module Module1
Sub Main()
Console.WriteLine(factorial(0))
Console.Writeline(factorial(5))
Console.ReadKey()
End Sub
Function factorial(ByVal number As Integer) As Integer
Dim answer As Integer
If number = 0 Then
answer = 1
Else
answer = number * factorial(number - 1)
End If
return answer
End Function
End Module
Java
// Java program recursive factorial function
public class Factorial {
1 factorial(5) 5 5 * factorial(4)
2 factorial(4) 4 4 * factorial(3)
3 factorial(3) 3 3 * factorial(2)
4 factorial(2) 2 2 * factorial(1)
5 factorial(1) 1 1 * factorial(0)
6 factorial(0) 0 1 1
5 continued factorial(1) 1 1 * 1 1
4 continued factorial(2) 2 2 * 1 2
3 continued factorial(3) 3 3 * 2 6
2 continued factorial(4) 4 4 * 3 * 2 24
Activity 19T
1 Recursion – see 19.2.1
2 Use of stack for recursive procedures – see 19.2.2
Activity 19S
FUNCTION fibonacci (number : INTEGER) RETURNS INTEGER
IF number = 0 OR number = 1
THEN
answer 1 // base case
ELSE
answer Fibonacci(number - 1) + fibonacci (number - 2)
// recursive call with general case
ENDIF
RETURN answer
ENDFUNCTION
1 fibonacci(4) 4 fibonacci(3) +
fibonacci(2)
2 fibonacci(3) 3 fibonacci(2) +
fibonacci(1)
3 fibonacci(2) 2 fibonacci(1) +
fibonacci(0)
4 fibonacci(1) 1 1 1
5 fibonacci(0) 0 1 1
3 continued fibonacci(2) 2 1 + 1 2
2 continued fibonacci(3) 3 1 + 2 3
1 continued fibonacci(4) 4 3 + 2 5
b) ii) The outer loop is always executed 9 times and the inner loop is never executed as
Temp is always larger.
c) i) Both loops are always executed 9 times.
ii)
REPEAT
NoMoreSwaps TRUE
FOR Pointer 1 TO NumberOfItems – 1
IF NameList[Pointer] > NameList[Pointer + 1]
THEN
NoMoreSwaps FALSE
Temp NameList[Pointer]
NameList[Pointer] NameList[Pointer + 1]
NameList[Pointer + 1] Temp
ENDIF
ENDFOR
NumberOfItems NumberOfItems - 1
UNTIL NoMoreSwaps
2 a)
Head Ben
Ahmed
Tail Jatinder 0
b) i)
Name Pointer
HeadPointer [1] 2
0 [2] 3
[3] 4
TailPointer [4] 5
0 [5] 6
[6] 7
FreePointer [7] 8
1 [8] 9
[9] 10
[10] 0
ii)
PROCEDURE RemoveName()
//Report error if Queue is empty
IF HeadPointer = 0
THEN
Error
ELSE
OUTPUT Queue[HeadPointer].Name
//current node is head of queue
CurrentPointer HeadPointer
// update head pointer
HeadPointer Queue[CurrentPointer].Pointer
//if only one element in queue, then update tail pointer
IF HeadPointer = 0
THEN
TailPointer 0
ENDIF
// link released node to free list
Queue[CurrentPointer].Pointer FreePointer
FreePointer CurrentPointer
ENDIF
ENDPROCEDURE
Activity 20A
Address Opcode Operand ACC IX
500 LDM #230 #230
501 LDD 230 #231
502 LDI 230 #5
503 LDR #1 #1
504 LDX 230 #5,#7,#9,#11,#0
505 CMP #0
506 JPE 509
507 INC IX #2,#3,#4,#5
508 JMP 504
509 JMP 509
Activity 20B
Pseudocode – without procedures and functions
DECLARE base, height, radius : INTEGER
DECLARE area : REAL
DECLARE CONSTANT Pi = 3.142
OUTPUT "Please enter base, height and radius"
INPUT base, height, radius
area = base * base
OUTPUT "Area of square is ", area
area = base * height
OUTPUT "Area of rectangle is ", area
area = base * base / 2
OUTPUT "Area of triangle is ", area
area = base * height
OUTPUT "Area of parallelogram is ", area
area = Pi * radius * radius
OUTPUT "Area of circle is ", area
area = circle(radius)
printArea ("circle", area)
def square(side):
return side * side
def circle(circRad):
Pi = 3.142
return circRad * circRad * Pi
area = square(base)
printArea ("square", area)
area = circle(radius)
printArea ("circle", area)
Console.ReadKey()
End Sub
End Module
Console.ReadKey()
End Sub
}
}
area = square(base);
printArea("square", area);
area = rectangle(base, height);
printArea("rectangle", area);
area = triangle(base, height);
printArea("triangle", area);
area = base * height;
printArea("parallelogram", area);
area = circle(radius);
printArea("circle", area);
}
}
Activity 20C
Python
#ACTIVITY 20C classes and objects
class student:
def __init__(self, name, dateOfBirth, examMark):
self.name = name
self.dateOfBirth = dateOfBirth
self.examMark = examMark;
def displayExamMark(self):
print("Student Name " + self.name)
print("Exam Mark " , self.examMark)
myStudent.displayExamMark()
VB
'ACTIVITY 20C classes and objects
Module Module1
Public Sub Main()
Dim myStudent As New student("Mary Wu", #10/12/2012#, 67)
myStudent.displayExamMark()
End Sub
Class student
Dim name As String
Dim dateOfBirth As Date
Dim examMark As Integer
Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As
Integer)
name = n
dateOfBirth = d
examMark = e
End Sub
End Module
Java
//ACTIVITY 20C classes and objects
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class student{
private String name;
private LocalDate dateOfBirth;
private int examMark;
}
}
Activity 20D
Python
#ACTIVITY 20D classes, objects and inheritance
class student:
def __init__(self, name, dateOfBirth, examMark):
self.name = name
self.dateOfBirth = dateOfBirth
self.examMark = examMark;
def displayExamMark(self):
print("Student Name " + self.name)
print("Exam Mark " , self.examMark)
class partTimeStudent(student):
def __init__(self, name, dateOfBirth, examMark):
student.__init__(self, name, dateOfBirth, examMark)
self.__fullTimeStudent = False
class fullTimeStudent(student):
def __init__(self, name, dateOfBirth, examMark):
student.__init__(self, name, dateOfBirth, examMark)
self.__fullTimeStudent = True
VB
'ACTIVITY 20D classes, objects and inheritance
Module Module1
Public Sub Main()
Dim myFullTimeStudent As New fullTimeStudent("Mary Wu", #10/12/2012#, 67)
myFullTimeStudent.displayExamMark()
Dim myPartTimeStudent As New fullTimeStudent("Janet Yo", #05/23/2012#, 95)
myPartTimeStudent.displayExamMark()
Console.ReadKey()
End Sub
Class student
Dim name As String
Dim dateOfBirth As Date
Dim examMark As Integer
Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As Integer)
name = n
dateOfBirth = d
examMark = e
End Sub
End Class
End Class
End Module
Java
//ACTIVITY 20D classes, objects and inheritance
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class student{
private String name;
private LocalDate dateOfBirth;
private int examMark;
}
}
Activity 20E
Python
# ACTIVITY 20E polymorphism
class shape:
def __init__(self):
self.__areaValue = 0
self.__perimeterValue = 0
def area(self):
print("Area ", self.__areaValue)
class square(shape):
def __init__(self, side):
shape.__init__(self)
self.__side = side
class rectangle(shape):
def __init__(self, length, breadth):
shape.__init__(self)
self.__length = length
self.__breadth = breadth
class circle(shape):
def __init__(self, radius):
shape.__init__(self)
self.__radius = radius
mySquare = square(10)
mySquare.area()
myCircle = circle(20)
myCircle.area()
VB
'VB ACTIVITY 20E polymorphism
Module Module1
Public Sub Main()
Dim myCircle As New circle(20)
myCircle.Area()
Dim myRectangle As New rectangle(10, 17)
myRectangle.Area()
Dim mySquare As New square(10)
mySquare.Area()
Console.ReadKey()
End Sub
Class shape
Protected areaValue As Decimal
Protected perimeterValue As Decimal
End Class
End Module
Java
// ACTIVITY20E polymorphism
class shape {
protected double areaValue;
}
}
Activity 20F
Python
#ACTIVITY 20F overloading
class greeting:
myGreeting = greeting()
myGreeting.hello()
myGreeting.hello("Christopher")
myGreeting.hello("Christopher", "Robin")
VB
'ACTIVITY 20F overloading
Module Module1
Public Sub Main()
Dim myGreeting As New greeting
myGreeting.hello()
myGreeting.hello("Christopher")
myGreeting.hello("Christopher", "Robin")
Console.ReadKey()
End Sub
Class greeting
End Module
Java
//ACTIVITY 20F overloading
class greeting{
public void hello(){
System.out.println("Hello");
}
class ACTIVITY20F{
public static void main(String[] args){
greeting myGreeting = new greeting();
myGreeting.hello();
myGreeting.hello("Christopher");
myGreeting.hello("Christopher","Robin");
}
}
Activity 20G
flight
courseID : STRING
numberOfLectures : INTEGER
courseLecture [1 : 50] OF lecture
numberOfExams : INTEGER
courseExam [1 : 3] OF exam
:
:
Constructor ()
addLecture ()
addExam ()
removeLecture ()
removeExam
:
:
lecture exam
Name : STRING Name : STRING
lecturerName : STRING marks : INTEGER
: :
: :
: :
showLectureDetails () showExamDetails ()
: :
: :
Containment diagram for a university course
Activity 20H
Sample Answer in Python
#ACTIVITY20H
class Node:
self.leftPointer = None
self.rightPointer = None
self.item = item
# Preorder traversal
def PreorderTraversal(self, tree):
result = []
if tree:
result.append(tree.item)
result = result +
self.PreorderTraversal(tree.leftPointer)
result = result +
self.PreorderTraversal(tree.rightPointer)
return result
#print(tree.search(16))
tree.PrintInOrder()
print(tree.PreorderTraversal(tree)
Activity 20I
language(england,Language).
language(Country,japanese).
Activity 20J
savingsRate(laila, X).
bankAccount(X,savings,Y).
bankAccount(robert,savings,300.00).
interest(sevenPercent,savings,2000.00).
Activity 20K
1 Absolute/Immediate – uses the operand, e.g. LDM #20 stores the denary value 20 in the
accumulator.
Direct – uses the contents of the memory location specified by the operand,
e.g. LDD 20 stores the value stored in the location with address 20 in the accumulator.
Indirect - uses the contents of the contents of the memory location specified by the operand, e.g.
LDI 20 stores the value stored in the location with the address stored at location 20 in the
accumulator.
Indexed – uses the value found at the memory location specified by adding operand to the contents
of the index register, e.g. LDX 20 stores the value stored in the location with address 20 plus the
contents of the index register in the accumulator.
2 Use of procedures and functions for procedural programming. For example, each procedure or
function is developed separately.
def square(side):
return side * side
Use of polymorphism in object-oriented programming where classes can be derived from other
classes. For example, the use of the base class shape and the derived classed for specific shapes.
class shape:
def __init__(self):
self.__areaValue = 0
self.__perimeterValue = 0
def area(self):
print("Area ", self.__areaValue)
class square(shape):
def __init__(self, side):
shape.__init__(self)
self.__side = side
3 a) language(java,highLevel).
language(java,oop).
b) i) fortran
cobol
visualBasic
visualBasic
python
python
ii) false
c) translator(assembler,X).
Python
#set up file with one record
class TStudentRecord:
def _init_(self):
self.name =""
self.address = ""
self.className =""
studentFile = open('student.TXT','w')
myStudent = TStudentRecord()
myStudent.name = "Ahmad Sayed"
myStudent.address = "My House"
myStudent.className ="5X"
studentFile = open('student.TXT','r')
print (studentFile.read()) #print all the records in a file
studentFile.close()
myStudent = TStudentRecord()
myStudent.name = "Frank Yang"
myStudent.address = "My bungalow"
myStudent.className ="5X"
studentFile.close()
studentFile = open('student.TXT','r')
print (studentFile.read())
studentFile.close()
#delete record
studentFile = open('student.TXT','r')
newStudentFile = open('newStudent.TXT', 'w')
recordRead = studentFile.readline()
studentFile.close()
newStudentFile.close()
VB
'student record
Imports System.IO
Module Module1
Sub Main()
'set up file with one record
Dim recordWrite, recordRead As String
Dim studentFileWrite As StreamWriter
Dim studentFileRead As StreamReader
studentFileWrite = New StreamWriter("student.txt")
Dim myStudent As TStudentRecord
studentFileRead.Close()
myStudent.className = "5X"
Console.WriteLine("Name " + myStudent.name)
Console.WriteLine("Address " + myStudent.address)
Console.WriteLine("Class " + myStudent.className)
studentFileWrite = New StreamWriter("student.txt", True)
recordWrite = myStudent.name + " " + myStudent.address + " " +
myStudent.className
studentFileWrite.WriteLine(recordWrite)
studentFileWrite.Close()
studentFileRead.Close()
'delete record
studentFileRead = New StreamReader("student.txt")
studentFileWrite = New StreamWriter("newStudent.txt")
Do
recordRead = studentFileRead.ReadLine
If recordRead <> "Frank Yang" + " " + "My bungalow" + " " + "5X"
Then
recordWrite = recordRead
studentFileWrite.WriteLine(recordWrite)
End If
Loop Until recordRead Is Nothing
studentFileRead.Close()
studentFileWrite.Close()
My.Computer.FileSystem.DeleteFile("student.txt")
My.Computer.FileSystem.RenameFile("newStudent.txt", "student.txt")
Console.ReadKey()
End Sub
Structure TStudentRecord
Dim name As String
Dim address As String
Dim className As String
End Structure
End Module
Java
//student record
import java.util.*;
import java.io.*;
class ShouldKnow_20_2_Q1 {
static class TStudentRecord {
String name;
String address;
String className;
String gender;
String studentFileWrite;
studentFileWrite = myStudentRecord.name + " " + myStudentRecord.address + "
" + myStudentRecord.className;
try {
FileWriter studentFileWriter = new FileWriter("student.txt", false);
PrintWriter studentWriter = new PrintWriter(studentFileWriter);
studentWriter.printf(studentFileWrite + "\n");
studentWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
myStudentRecord.name = "Frank Yang
myStudentRecord.address = "My Bungalow";
myStudentRecord.className = "5X";
try {
FileReader studentFileReader = new FileReader("student.txt");
BufferedReader studentReader = new
BufferedReader(studentFileReader);
FileWriter studentFileWriter = new FileWriter("NewStudent.txt",
false);
PrintWriter studentWriter = new PrintWriter(studentFileWriter);
String studentFileRead;
} catch (IOException e) {
e.printStackTrace();
}
}
}
2 Serial – records are stored in a file one after another in the order they were added to the file.
Sequential – records are stored in a file in a given order based on the key field
Random – records are stored in a file in any available position based a hashing algorithm used on
the key field.
3 Direct – a record is found using a hashing algorithm without searching any other records.
Sequential – a record is found by searching each record in turn starting at the beginning of the
file.
Activity 20L
Python
#ACTIVITY 20L
import datetime
import pickle
class student:
def __init__(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()
studentFile = open('students.DAT','wb')
studentFile.close()
studentFile = open('students.DAT','rb')
studentRecord = pickle.load(studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)
studentFile.close()
VB
' ACTIVITY 20L
Option Explicit On
Imports System.IO
Module Module1
studentFileWriter.Write(studentRecord.name)
studentFileWriter.Write(studentRecord.registerNumber)
studentFileWriter.Write(studentRecord.dateOfBirth)
studentFileWriter.Write(studentRecord.fullTime)
studentFileWriter.Close()
studentFile.Close()
studentRecord.name = studentFileReader.ReadString()
studentRecord.registerNumber = studentFileReader.ReadInt32()
studentRecord.dateOfBirth = studentFileReader.ReadString()
studentRecord.fullTime = studentFileReader.ReadBoolean()
studentFileReader.Close()
studentFile.Close()
End Sub
class student:
Public name As String
Public registerNumber As Integer
Public dateOfBirth As Date
Public fullTime As Boolean
End Class
End Module
Java
//ACTIVITY20L no data of birth
import java.io.*;
import java.util.*;
class student {
private String name;
private int registerNumber;
private boolean fullTime;
String nameIn;
int registerNumberIn;
boolean fullTimeIn;
try {
FileWriter studentFile = new FileWriter("student.txt");
studentFile.write(nameIn + " " + registerNumberAsString +
" " + fullTimeAsString);
studentFile.close();
}
catch (IOException e) {
System.out.println("File write error");
e.printStackTrace();
}
try {
File myStudent = new File("student.txt");
Scanner myReader = new Scanner(myStudent);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("File read error");
e.printStackTrace();
}
}
Activity 20M
Sample Python
#ACTIVITY 20L updated
import datetime
import pickle
class student:
def __init__(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()
studentFile.close()
studentFile = open('students.DAT','rb')
studentRecord = pickle.load(studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)
studentFile.close()
Activity 20N
Python
#ACTIVITY 20N
try:
value = int(input('Please enter an integer value '))
except:
print('Not an integer')
VB
'ACTIVITY 20N
Module Module1
End Module
Java
//ACTIVITY20N
import java.io.*;
import java.util.*;
try {
System.out.println("Please input an integer value ");
int value = myObj.nextInt();
}
catch (InputMismatchException e) {
System.out.println("Not an integer");
}
}
}
Activity 20O
Python
#checking file exists before trying to read from it
try:
studentFile = open('students.DAT','rb')
except OSError:
print("Could not open students.DAT")
sys.exit()
Visual Basic
'checking file exists before trying to read from it
Try
studentFile = New FileStream("studentFile.DAT", FileMode.Open)
Catch e As System.IO.IOException
Console.WriteLine("File not found")
End Try
DateOfBirth : DATETIME
ShowDateOfBirth()
FullTimeStuden PartTimeStudent
NumberOfCourses : INTEGER
TelephoneNumber : STRING
Fee : Currency
FeePaid : BOOLEAN
Constructor()
Constructor()
ShowNumberOf Courses()
ShowTelephoneNumber()
ShowFee()
ShowFeePaid()
b) i)
Python
class Student : def __int__(self) :
self.__StudentName = ""
self.__DateOfBirth = "" # date(1,1,2015)
def ShowStudentName() :
pass
def ShowDateOfBirth() :
pass
VB
Class Student
Public Sub ShowStudentName()
End Sub
Public Sub ShowDateOfBirth()
End Sub
Private StudentName As String
Private DateOfBirth As Date
End Class
ii)
Python
class FullTimeStudent(Student) : def
__init__(self) :
self.Address = ""
self.__TelephoneNumber = ""
def ShowAddress() :
pass
def ShowTelephoneNumber() :
pass
VB.NET
Class FullTimeStudent : Inherits Student
Sub ShowAddress()
End Sub
Sub ShowTelephoneNumber()
End Sub
Private Address As String
Private TelephoneNumber As String
End Class
iii)
Python
NewStudent = FullTimeStudent()
NewStudent.StudentName = "A.Nyone"
NewStudent.DateOfBirth = "12/11/1990"
NewStudent.TelephoneNumber = "099111"
VB
Dim NewStudent As FullTimeStudent = New FullTimeStudent()
NewStudent.StudentName = "A.Nyone"
NewStudent.DateOfBirth = #11/12/1990#
NewStudent.TelephoneNumber = "099111"
3 a) Exception – situation causing a crash/run-time error/fatal error.
Exception handling – code which is called when a runtime error occurs to avoid the program
terminating/crashing.
b) Opening a non-existent file.
Using a directory path that does not exist.
Attempting to read past the end of the file.
c) i) 09
ii) Line 11 catches exceptions (only) between lines 05 and 10 and stops the program from
crashing.
Line 12 outputs the exception message if required.