0% found this document useful (0 votes)
21 views

Computer Science Answers

Uploaded by

senoc86278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Computer Science Answers

Uploaded by

senoc86278
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 253

Cambridge International AS & A Level Computer Science

Chapter 1 Student Book Answers


What you should already know
1 128 64 32 16 8 4 2 1
2 a) 01111101 (125)
b) 10111011 (187)
c) 01111101 (125)
d) 10110110 (182)
e) 11111000 (248)
f) 101010100 (340)
3 65536 4096 256 16 1
4 a) 35E (862)
b) C1F (3103)
c) 1221 (4641)
d) 9F6 (2550)
e) 1058 (4184)
f) 37B8 (14264)
g) F4B5 (62645)
h) 17780 (96128)
i) AFFA (45050)
j) D468 (54376)

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

End of chapter questions


1 a) i) 0100 1111 = 79
ii) 1001 1010 = –102
iii) –53 = 11001011
iv) range is: 10000000 (–128) to 01111111 (+127)
b) i) 798 = 0111 1001 1000 in BCD
ii) 9776
c) storage of digital displays on calculators (accept other valid uses)
2 a) i) Sampling Resolution – is a number of values available to encode each sample. It is
specified by number of bits per sample (bit depth).
ii) A larger sampling resolution leads to more values available improving accuracy of sound
digitised.

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b) i) number of pixels per unit


ii) 16-colour bit map image requires 4 bits (½ byte) per pixel
iii) number of pixels = 16384 × 512
1 pixel = 1 byte  (16384 × 512)/1024 = 8192/1024 ~ 8 GiB storage

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

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 2 Student Book Answers


What you should already know
1 a) i) MAC address
 A unique number that identifies a device connected to the internet.
 It can be a physical or virtual address.
 A MAC address is usually fixed.
IP address
 When a device connects to the internet it is given an IP address.
 An IP address is usually unique for a particular session.
 It’s format is xx.xx.xx.xx.
b)
 A MAC address identifies a device (usually NIC contains the address).
 An IP address is the location of the device on the internet.
 A MAC address and IP address operate on different layers of the internet protocol.
 A MAC address identifies machines on layer 2.
 An IP address are used on layer 3.
 Even if a computer has an IP address it still needs a MAC address to find other
devices which may be on same network.
c)
 An ISP is a company that provides services to access and use the internet.
 The company will charge a fee for the service provided.
 An ISP has equipment and telecommunication lines to allow internet connection.
 An ISP provides user with an IP address when connecting to the internet.
d)
 An internet (web) browser is software application for accessing information on the
World Wide Web
 An internet browser allows user to view pages on different websites.
 They allow location of websites by typing in the URL in the address bar.
2 Advantages
 NIC/WNIC cards
 network cabling to connect up computers and devices
 switches/hubs to connect devices to form a network
Disadvantages
 router required if internet/external networks need to be accessed
 firewall if any external links exist
 servers to manage security, store common software/files, manage printer queues
 setting up privileges to allow access to user areas
 web browser and ISP if internet connection needed
3 a)

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Real time (live)


 live event captured on camera/microphone and sent to a computer
 video/sound signal is encoded to a bit streaming media format
 encoded data is uploaded from computer to dedicated video streaming server
 because data is live, not possible to pause/fast forward/rewind.

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

c) i) 190.15.25.240 – class B network


ii) 190.15 – net ID
25.240 – host ID
iii) This means net ID can be set at maximum 18 bits leaving 14 bits for host ID.
d)
 IPv6 uses 128 bits rather than 32 bits
 IPv6 uses hexadecimal digits
 IPv6 uses built in authentication
 IPv6 ensures no more private address collisions
 IPv6 means there is no more need for NATs
3 a) A private IP address is reserved for internal use behind a router or other NAT device.
A public IP address is allocated by the ISP to identify where the device is on the network –
this IP address is accessible to anyone logged onto the internet.
b) protocol is https
domain is exampleofaurl.co.de
filename is computer_logic.html
c)
 browser opened and user types in url: www.exampleofaurl.co.de/computer_logic.html
 browser asks DNS for IP address
 if DNS server can’t find URL in its database or cache it sends out request to another DNS
server
 second DNS server finds URL and can map it to an IP address
 this IP address is sent back to first DNS server which now puts IP address and URL into its
database/cache; this IP address is now sent back to the user’s computer
 computer’s web browser now sets up communication with the website and starts to
download the pages
 web browser interprets HTML and displays pages on user’s monitor.
4 a) Internet
 a massive network of networks which are made up of computers and other devices
 stands for INTERconnected NETwork
 makes use of TCP/IP protocols.
www
 world wide web
 collection of multimedia web pages
 stored on websites
 http(s) protocols written using HTML
 URL specifies location of web pages
 documents accessed by web browsers
information is accessed over the network.
b) Yes, it is correct.
 WANs are made up of connected LANs using the public network.
 The LANs may be private networks only accessible through passwords and user ids …

Cambridge International AS & A Level Computer Science 7


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

End of chapter questions


1 a) i) Benefits
 signal only goes to destination node therefore more secure
 easier to expand network
 centralised management means it can be monitored
 failure of one node doesn’t affect whole network.
Drawbacks
 if central hub/switch fails, the whole network fails
 the overall performance is dependent on the central hub/switch.
ii) Benefits
 easier to detect faults
 uses routing logic so data reaches destination node only by the shortest route or
rerouted if one of the nodes fails
 has very good privacy and security
Drawbacks
 complex network topology
 requires considerable amount of cabling which means initial set up is relatively
expensive

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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) GEO – Geostationary Earth Orbit:


These provide long distance telephone and computer network communications; orbital period
is 24 hours and they orbit at 35 800 km.
MEO – Medium Earth Orbit
These are used for GPS systems (about 10 MEO satellites are currently orbiting the Earth);
orbital period is 2 to 8 hours; they orbit at 5000 to 12 000 km.
LEO – Low Earth Orbit
These are used by the mobile phone networks (there are currently more than 100 LEO
satellites orbiting the Earth); orbital period is 12 mins to 1 hour; they orbit at 500 to 1500 km.
c) i) Attenuation is the reduction in amplitude of a signal. For example, we see that infrared is
worst in this respect since it can be affected by rain and can also be stopped by internal
walls.
ii) When a device wants to communicate, it picks one of 79 channels at random. If the chosen
channel is already in use, it randomly chooses another channel
3 a) Bit streaming
 is a contiguous sequence of digital bits sent over a network/internet
 requires a high speed data transfer communications link
 requires buffering
bits arrive at destination in the same order as they were sent.
b) i) Benefits
 no need to store large files on a local computer
 no need to wait for whole files to be loaded before watching video
 allows on demand playback
 no specialist software needed.
ii) Potential problems
 video stops/hangs if internet connection is slow or is lost
 video stops/hangs if there is inadequate buffering
 may require special software to run certain files

usual risk of viruses and other malware being transmitted.
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.
Real time (live)
 live event captured on camera/microphone and sent to a computer
 video/sound signal is encoded to a bit streaming media format
 encoded data is uploaded from computer to dedicated video streaming server
 because data is live, not possible to pause/fast forward/rewind.
4 a)
 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’, for example, if the broadband speed is slow.

Cambridge International AS & A Level Computer Science 10


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

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b)

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 3 Student Book Answers


What you should already know
1 Memory – an immediate access store is RAM and ROM which are directly accessed by the CPU.
Storage – an external devices such as HDD, SSD which are not directly accessed by the CPU.
2
 Internal memory is RAM and ROM.
 RAM stores instructions, data and the part of the OS currently in use.
 Data in RAM is lost if the power is turned off.
 RAM is a very fast memory but relatively small and expensive per byte.
 ROM stores data which can’t be lost or deleted but cannot be changed.
 External storage is much larger than RAM/ROM but is not volatile and less expensive per
byte than RAM/ROM.
3 i) DVD/CD player
ii) RAM/ROM
iii) SSD
iv) HDD
4 Online – storage connected to and under the control of a computer.
Offline – storage not connected to and under the control of the computer.
5 Data access time – the time taken to locate and read data on a storage or memory device.
Data transfer rate – the time taken to transfer data from storage or memory to CPU or other
device.

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.

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

e) (A = 1 AND B = 1) AND (B = 1 OR C = NOT 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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

b) (G = 1 AND W = NOT 1) OR (G = NOT 1 AND R = 1) OR (W = 1 AND R = 1)

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Same as a NOR gate

Activity 3F
1 a)
b) the truth table will only generate a 0 when all inputs are 1

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

End of chapter questions


1 a) OLED technology
 OLED screens are thinner and lighter and therefore more flexible.
 They have a brighter output than equivalent LED/LCD screens.
 OLED requires no backlighting.
 They use less power than equivalent LED/LCD screens (very important on portable
devices).
 Screens can be moulded into any shape required.
 The colours are more vivid/better contrast.

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b)

 Sensor 1 measures temperature and sensor 2 measures humidity level.


 Sensor 1 data is continuously sent to the microprocessor via the ADC (if analogue in
nature); this converts data to digital format.
 If temperature < temperature setting, then a signal is sent out from the microprocessor to
the air con unit to increase heat output.
 If temperature > temperature setting, then a signal is sent out from the microprocessor to
the air con unit to increase output of cooling air.
 If the two values are the same, no signals are sent by the microprocessor.
 Sensor 2 data is continuously sent to the microprocessor via ADC (if analogue in nature);
this converts data to digital format.
 If humidity > set level, a signal is sent out from the microprocessor to the air con unit to
activate the dehumidifier.
 If humidity < set level, a signal is sent out from the microprocessor to the air con unit to
increase moisture level in the air being output.
 If the two values are the same, no signals are sent by the microprocessor.
4 order: A – 4, B – 6, C – 1, D – 9, E – 2, F – 7, G – 3, H – 8, I – 5
5 a)

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.

Cambridge International AS & A Level Computer Science 13


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 14


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 4 Student Book Answers


4.1 What you should already know
1 a) monitor, keyboard, mouse, hard disk drive or solid state drive, microprocessor
b) Tablet or phone
 has a smaller screen
 has a virtual or small keyboard
 uses cellular network instead of WiFi connectivity
 requires different type of operating system
 uses instant messaging rather than emailing
 is fully portable … usually have it with you.
2
 processor speed
 size of screen
 screen resolution
 ease of operation
 is OS easy to use/interface easy to use
 what Apps are available
 type of I/O ports
 battery life
3 USB, HDMI, VGA, lightning connector (mobile phones) are the most common
4
 much faster performance (has increased by about 50% each year)
 faster clock speeds
 greater reliability
 smaller components allowing more components on the motherboard (for example)
 transistor dimensions have reduced by 30% every two years which results in doubling
transistor density; electric fields must also be kept constant therefore a reduction of supply
voltage from 12 V (in 1970) to 0.05 V (in 2018)
 in reality, reduction has been nearer 10% than 30% which has contributed to a slowdown in
recent performance increases
(Refer to website https://arxiv.org/pdf/1801.05215.pdf for further information if this is to form a
project)

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

ii) two positive numbers added together give a negative result:


01110001
01011110 N 1
𝟏1001111

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

2 a) address bus, data bus, control bus


b)
Address bus
 carries addresses to memory controller, thus identifying memory location which is to be
read or written to
 bus is unidirectional between CPU and memory thus preventing an address being carried
back to the CPU.
Data bus
 bidirectional bus which carries data (address, instruction or numerical value) throughout
the processor
 data can be carried from CPU to memory (and vice versa) and to/from input/output
devices.
Control bus
 bidirectional bus which transmits signals from the control unit to other components of the
computer
 this includes clock signals used to synchronise all operations.
c)
 In general, a higher clock speed increases the performance of a computer.
 Using a wider address bus and data bus allows a larger range of memory locations to be
directly accessed or allows a larger word size to be handled by the computer.
 Both of the above speed up computer operations.
 However, it is not a simple matter of just increasing clock speed since …
 … If the processor doesn’t use wider buses (etc.), increasing the clock speed alone could
lead to problems such as overheating and non-synchronisation of operations.
 Risk of overclocking can occur.

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

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

4.2 What you should already know


1 a) Assembly language and machine code
b) Machine code
c) Writing instructions in binary is time consuming and can be error prone as codes need to be
exact and binary numbers are not easy to remember. Testing can only be done by executing
the code.

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

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

100 LDD number1 30 0

101 SUB number2 -10 0

102 ADD number3 10 0

103 CMP #10 10 0

104 JPE nomore 10 0

106 STO total 10 10

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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

3 a)

Label Opcode Operand Comment

LDM #0 Load 0 into ACC

STO counter Store 0 in counter

LDR #0 Set IX to 0

loop: LDX array Load the element of the array indexed by IX into ACC

OUT Output the ASCII character

INC IX Add 1 to the contents of IX

LDD counter Load counter into ACC

INC ACC Add 1 to ACC

STO counter Store result in counter

CMP #4 Compare with 4

JPN loop If ACC not equal to 4 then return to start of loop

END

array: #67 Array of 4 ASCII characters

#79

#68

#69

counter: counter for loop

b)
Label Address

loop 103

array 113

counter 117

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

c)
CIR Opcode Operand ACC IX counter Output

100 LDM #0 0

101 STO counter 0

102 LDR #0 0 0 0

103 LDX array 67 0 0

104 OUT 67 0 0 C

105 INC IX 67 1 0

106 LDD counter 0 1 0

107 INC ACC 1 1 0

108 STO counter 1 1 1

109 CMP #4 1 1 1

110 JPN loop 1 1 1

103 LDX array 79 1 1

104 OUT 79 1 1 O

105 INC IX 79 2 1

106 LDD counter 1 2 1

107 INC ACC 2 2 1

108 STO counter 2 2 2

109 CMP #4 2 2 2

110 JPN loop 2 2 2

103 LDX array 68 2 2

104 OUT 68 2 2 D

105 INC IX 68 3 2

106 LDD counter 2 3 2

107 INC ACC 3 3 2

108 STO counter 3 3 3

109 CMP #4 3 3 3

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

110 JPN loop 3 3 3

103 LDX array 69 3 3

104 OUT 69 3 3 E

105 INC IX 69 4 3

106 LDD counter 3 4 3

107 INC ACC 4 4 3

108 STO counter 4 4 4

109 CMP #4 4 4 4

110 JPN loop 4 4 4

111 END counter 2 2 2

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.

c) Shift left logical 3.

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

End of chapter questions


1 a)
Stage Order
Instruction is copied from the MDR and is placed in the CIR 3
Instruction is executed 6
Instruction is decoded 5
Address contained in PC is copied to the MAR 1
Value in PC is incremented by 1 4
Instruction is copied from memory location in MAR and placed in MDR 2
b) i) Width of the data bus and address bus
 determines number of bits that can be simultaneously transferred
 hence wider bus improves processing speed as fewer transfers are needed
 double bus width = 2 × data transferred per clock pulse.
ii) Clock speed
 determines number of cycles computer can execute per second
 increasing clock speed increases number of operations per unit time
 limited by heat generated by higher clock speeds.
iii) Dual or quad core
 each CPU contains 2 cores or 4 cores
 CPU with 2 or 4 processors in the same integrated circuit; each processor has its own
cache and controller
 single computing component with 2/4 independent processing units (cores) which can
read and execute program instructions
 this gives processor double or four times the processing power of a single core
processor
 however, this isn’t the case in reality since the CPU needs to communicate with each
core which reduces overall performance
 software frequently can’t take advantage of 2 or 4 core processors again reducing
potential overall performance.
c) Dangers are overheating and risk of going out of synchronisation causing errors and potential
computer ‘crash’ due to instructions no longer correctly synchronized.

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson/Hodder & Stoughton Ltd
Cambridge International AS & A Level Computer Science

Chapter 5 Student Book Answers


5.1 What you should already know
1 Devices such as washing machine and ovens have simple repetitive tasks which are controlled by
user pushing a button or turning a dial … therefore no need for an OS.
2 a) For example, Microsoft Windows 10, Apple MacOS, Google Android, IOS (mobile phones/
tablets only)
b) Different OS versions developed because
 different interfaces
 different connectivity methods
 different screen sizes
 need to manage cellular and wireless connectivity as well as phone access
 desktop OS allow Apps to continue consuming memory until the system gets very slow;
mobile phones/tablets, with their limited memories, can’t allow this and need better
management/control from the OS
 need to optimise for small memories and power use.
3 a) GUI – uses graphical interface which involves icons and selection by pointing devices or
touch screen.
CLI – a user interface is keyboard where user keys in commands to carry out actions; exact
instructions need to be used.
b)
interface advantages disadvantages
 the user needs to learn a
 the user is in direct
number of commands to carry
communication with the
out basic operations
computer
command line  all commands need to be typed
 the user is not restricted to a
interface (CLI) in which takes time and can be
number of pre-determined
error prone
options
 each command must be typed
 it is possible to alter computer
in using the correct format,
configuration settings
spelling, and so on
 the user doesn’t need to learn
 this type of interface uses up
any commands
considerably more computer
 it is more user-friendly; icons memory than a CLI interface
are used to represent
graphical user  the user is limited to the icons
applications
interface (GUI) provided on the screen
 a pointing device (such as a
 needs an operating system,
mouse) is used to click on an
such as windows, to operate,
icon to launch the application –
which uses up considerable
this is simpler than typing in
memory
commands

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson
Cambridge International AS & A Level Computer Science Answers

ii) Drawbacks of using DLL files


 DLL files aren’t integrated into programs that use them which leads to shared code.
 The programs using DLL files aren’t self-sufficient therefore a program requiring
these files won’t work if they are not available or are incompatible with the version of
the software.
 Shared files are an issue if they have been updated at a later point making them
potentially incompatible later.
 Because DLL libraries are outside programs that use them, they could be modified by
another programmer which may remove any software protection or even introduce
viruses or spyware into programs that use them.
 DLL-dependent programs usually run slower than those that use static library routines.
2 Disk formatter – prepares HDD to allow data to be stored.
Virus checker – checks for viruses and then quarantines/removes them.
File compression – reduces file size to save storage using lossy/lossless compression algorithms.
Back-up software – makes copies of files on separate medium in case of data corruption/loss.
Firewall – prevents unauthorised access to computer from external sources.
3 a) File compression – reduces file size so they can be sent.
b) Back-up – in case files/data are lost, a copy can be reinstalled.
c) Defragmentation – removes unused sections of HDD and makes it faster to access files.
d) Anti-virus – quarantines and removes any viruses found.
e) Formatters – can repair disks if bad sectors are found.

5.2 What you should already know


1 a) Compiler and Assembler
b) Interpretation

2 a) PyCharm (example there are many more)


b) Source code editor with colour coding, automatic layout and autocompletion, alternative
interpreters, a debugger with single stepping, breakpoints and a report window showing the
value of variables whilst single stepping through the program.
c) Most useful for me autocompletion to save time. (Example answer)

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.

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson
Cambridge International AS & A Level Computer Science Answers

End of chapter questions


1 a) Benefits of library routines
 code already written therefore saves programmer time
 code has been used by many users therefore thoroughly tested and error-free
 programmer has access to many complex routines which may be outside his knowledge if
he had to write them
 code should conform to industry standards which leads to more robust/compatible
programs.
b) i) Benefits of DLL files
 executable code is smaller because DLL files only loaded at run time
 changes/improvements to DLL file code is done independently of main program
therefore there is no need to recompile the main program
 single DLL file can be made available to several applications at the same time
 saves on memory space
ii) Drawbacks of DLL files
 executable code is not self-contained therefore DLL files need to be included at run
time
 linking software must be available at run time so that links to DLL files can be made
 DLL files must always be present otherwise inability to find the file at run time would
lead to .dll errors occurring
 unexpected changes to DLL files/corrupted DLL files could lead to the main program
crashing or giving unexpected results
 malicious changes to DLL files (For example, viruses) could lead to user’s computer
becoming infected or stored data being deleted/corrupted.
2 a)

b) i) file compression software


ii) back-up software
iii) disk repair software
iv) anti-virus software

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson
Cambridge International AS & A Level Computer Science Answers

3 a) in case files are deleted/corrupted (accidentally or on purpose)


b)
 allows user to return computer to status before the problem occurred
 it may involve reverting back to earlier versions of the software or files
 if a file is lost or the user forgot to save it, an earlier version (from auto save) could be
retrieved
 if OS updated and a newer version causes problems when running software, there may be a
need to revert back to the earlier version of the OS
c) Points to consider
 As an HDD becomes full, blocks used for files will become scattered all over the disk
surface (in potentially different sectors and tracks as well as different surfaces) …
 … this will happen because files will become deleted, partially deleted, extended and so on
over time …
 … the consequence of this is
 slower data access time
 the HDD read-write head will now require several movements just to find and
retrieve the data making up the required file
 It would obviously be advantageous if files could be stored in contiguous sectors
considerably reducing HDD head movements …
 … due to the different operation of SSDs when accessing data, this is less of a
problem when using solid state devices.
 A disk defragmenter will rearrange the blocks of data to store files in contiguous sectors
wherever possible …
 …. however, if the disk drive is almost full, defragmentation may not work.
 Defragmentation obviously allows for much faster data access and retrieval since the HDD
will now require fewer read-write head movements to access and read files.
 Some defragmenters also carry out clean up operations
 data blocks can become damaged after several read/write operations …
 …. in which case, they are flagged as “unusable” …
 …. and any subsequent write operation will avoid writing data to data blocks
which have become affected.
4 Assemblers – are used to translate programs written in low-level languages only.
Compilers – are used to translate programs written in high-level languages only.
Interpreters – are used with programs written in high-level languages only, no object program is
produced.
Both assemblers and compilers translate source code into object code. Both compilers and
interpreters are used with high-level languages. Both an interpreter and a compiler can be used
within an IDE.

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson
Cambridge International AS & A Level Computer Science Answers

5 Any four from


 Context-sensitive help
 Syntax checking (on entry)
 Automatic indentation
 Type checking (Parameter checking)
 PrettyPrinting
 Highlight structure blocks (e.g. selection, iteration)
 Highlight any undeclared variables
 Highlight any unassigned variables

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson
Cambridge International AS & A Level Computer Science

Chapter 6 Student Book Answers


What you should already know
1 a) Hacking – is unauthorised access to a computer system without the user’s knowledge or
consent.
b)
 Hacking is illegal if it aims to cause harm (For example, delete files, transfer money
illegally, etc.).
 ‘Ethical hacking’ is an expert who attempts to penetrate a computer system/network on
behalf of the owner(s) of the system to try and determine the security vulnerability that an
illegal hacker could exploit.
2
Pros Cons
 convenient since there is no need to tap in
 not yet universally available
a PIN
 user is protected against fraudulent  only available to users with contactless
transactions credit/debit cards
 uses Near Field Communications (NFC)  since there is no PIN to type in, lost cards
which uses encryption thus protecting could still be used until the owner realises
user against illegal acts the loss
 quicker transactions leads to shorter  limit set by the bank is fairly small and
queues at check-outs therefore only useful for small purchases
 studies have shown that customers are
 retailers no longer have access to user’s
more likely to spend money when using
credit/debit card details
contactless payment
3
 Hacking – the act of stealing personal or private data without the owner’s knowledge or
consent.
 Cracking – is where someone edits/changes the source code of a program or they create a
program (known as a patch) that can trick the software in to thinking a certain process has
occurred
 for example, a patch could trick software into thinking that a security key has been
successfully entered giving illegal access
 this is known as finding the ‘back door’ to the software and is used for malicious use or for
breaking of software copyright
whilst cracking is always essentially illegal, it is generally thought to be less harmful than
hacking and also requires more skill to carry out since there is a need to understand
program coding methods.
4 a Pop ups
 a window that opens without the user selecting it form a menu
 used by websites to display adverts
 can come from malware in which case it is evidence that a computer has become infected
 can generate ‘scareware’ such as the selling of fake antivrus programs by claiming that a
user’s computer has a virus and won’t remove it until a fee is paid.

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

There are numerous ways to help prevent phishing attacks:


 Users need to be aware of new phishing scams.
 It is important not to click on any emails links unless totally certain that it is safe
to do so …
 fake emails can often be identified by “Dear Customer ……” or “Dear email
[email protected] ………” and so on.
 It is important to run anti-phishing toolbars on web browsers.
 Always look out for https or the green padlock symbol in the address bar.
 Make regular checks of online accounts are also advisable as well as maintaining
passwords on a regular basis.
 Ensure an up-to-date browser is running on the computer device (which contains
all of the latest security upgrades) …
 … and run a good firewall in the background at all times; a combination of a
desktop firewall (usually software) and a network firewall (usually hardware)
considerably reduces the risk of hacking, pharming and phishing on network
computers.
 Be very wary of pop-ups and use the web browser to block them …
 … if pop-ups get through your defences, don’t click on ‘cancel’ since this can
ultimately lead to phishing or pharming sites down.
Pharming (risk to the security of stored data)
 Pharming is malicious code installed on a user’s computer or on a web server …
 … the code will re-direct the user to a fake website without their knowledge …
 … redirection from a legitimate website to the fake website can be done using
DNS cache poisoning.
 When a user enters a web address (URL) into a browser, the computer is sent the
IP address of the website …
 … if the IP address has been modified somehow (for example, through pharming)
the user’s computer will be redirected to the fake website.
 The creator of the malicious code can gain personal data such as credit/debit card
details from users when they visit the fake website.
 Usually the website appears to be that of a well-known and trusted company and
can lead to fraud or identity theft.
It is possible to mitigate the risk of pharming:
 Using antivrus software can detect unauthorised alterations to a website
address and warn the user of the potential risks …
 … however, if the DNS server itself has been infected) it is much more
difficult to mitigate the risk
 Many modern web browsers can alert users to pharming and phishing attacks
 It is very important to check the spelling of websites to ensure the web address
used is correct
Viruses
 A virus is a program/program code that can replicate/copy itself with the
intention of deleting or corrupting files …
 … or cause the computer to malfunction

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

 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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

6.2 What you should already know


1 to ensure data is reasonable and meets certain input criteria before it can be used
2 proofreading checks that a document reads correctly and is factually correct (it doesn’t necessarily
check against the original document)
3 can use drop down boxes:

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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

End of chapter questions


1 a any description of the following: use of passwords/user ids, use of a firewall, use of antivrus
or anti-spyware software, use of secure/private lines, and so on.
b 1 5 6 3 4 1 2
×7 ×6 ×5 ×4 ×3 ×2 ×1
= 7 + 30 + 30 + 12 + 12 + 2 + 2
= 95 ൊ 11
= 8 remainder 7
check digit = 11 − 7 = 4
c student ID: length check, character check or format check
2 a
 A virus is a program/program code that can replicate/copy itself with the intention of
deleting or corrupting files …
 … or cause the computer to malfunction.

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

 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

Chapter 7 Student Book Answers


What you should already know
1 a,b An expert system
 is an example of AI
 is a computer system that emulates a human expert in a number of areas
 is made up of an inference engine, rules base, interface, explanation system and knowledge
base
 uses the inference engine to apply rules to known facts (which make up the knowledge
base) to make decisions and conclusions
 can also give explanations for the reasoning used to draw conclusions.
c
 medical diagnosis
 fault finding in engines and electronic devices
 oil and mineral exploration
 playing strategy games such as chess
 ability to identify plants, animals, chemical compounds, etc.
 financial advice, for example, tax calculations
2 a Copyright is a protection that covers electronic and paper-based resources from illegal
copying and distribution.
b
 Without copyright there would be no way of preventing anybody copying something and
selling it without the originators receiving any fees.
 Since the originators spent time and money developing the resource, it would be legally
and morally unfair to allow anyone to make illegal copies.
c
 software
 articles (such as books)
 new scientific research
 designers (for example, cars, furniture, ceramics, etc.)
d
 Plagiarism is when a person uses ideas from existing work in their own work and claiming
they wrote/developed it …
 … without any reference to the originators.
3 a i) manual factory: admin and assembly jobs are lost …
… but jobs are created in writing software, running and installing IT systems, etc.
ii)
 Generally improves the environment since computer-based systems can save, for
example, on heating and lighting.
 Also leads to more efficient running of devices which are computer-controlled.

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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:

stories fabricated to gain website readers and increase


click bait advertising revenue; they are sensational headlines
designed to grab reader’s attention
stories created to deliberately mislead audiences and
propaganda
promote bias
satire and parody publishing fake news for entertainment purposes
journalists publishing stories without first checking the
sloppy journalism
validity/credentials of their information sources
headlines that distort the facts leading to sensationalist
stories , for example,‘man beats wife’ – could this mean
misleading headlines
a vicious attack or did a man simply win an argument?
You decide!

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.

Arguments in favour of some form of internet control


 It would prevent illegal material being posted on websites (for example, racist comments,
pornography, terrorist activities, and so on).
 People find it much easier to discover information which can have serious consequences (for
example, how to be a hacker, how to make a bomb, and so on) …
 … although this can be found in books, it is much easier for a novice to find the required
information using a search engine.

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Arguments against some form of internet control


 Material published on websites is already available from other sources.
 It would be very expensive to ‘police’ all websites and users would have to pay for this
somehow.
 It would be difficult to enforce rules and regulations on a global scale.
 It can be argued that policing would go against freedom of information/speech.
 Many topics and comments posted on websites are already illegal and laws already exist to
deal with the offenders.
 Who is to decide what is illegal or offensive – many things are only offensive to certain people
(for example, religious comments) but not to the majority.
3
 Legal covers the law – whether an action is punishable by law.
 Morality governs the private and personal interactions between people.
 Ethics governs professional interactions.
 Culture refers to the attitudes, values and practices shared by a society or group of people.
 Morality covers the human desire to distinguish between right and wrong …
 … the only problem here is that culture can get in the way …
 … what may be immoral in some cultures is regarded as acceptable practice in other cultures

 … because something is immoral, it isn’t necessarily illegal.
 Altering websites or creating fake websites is not in itself illegal …
 … provided the person who carries out the act doesn’t try to gain from their actions
 … it is simply an immoral act since it can cause distress to others who aren’t aware that it was
simply a harmless prank …
 … as soon as they try to obtain personal and financial data then it becomes an illegal act.
 Some people regard hacking as simply immoral – this again ceases to be true if the act of
hacking leads to breaking national security, or financial gain or leads to revealing personal
information which leads to distress …
 … it can be a very thin dividing line between an immoral act and an illegal act.
 Unethical behaviour is essentially breaking a code of conduct …
 … for example, if somebody works for a software company and passes on some of the ideas to
a rival company, this would be regarded as unethical behaviour …
 … unless the software passed on is part of national security, then it isn’t actually illegal to do
this
 the importance of culture is less tangible …
 … writing software games that make fun of religion could be seen by certain people as
unacceptable behaviour …
 … but some cultures would find it funny and wouldn’t understand why it was seen as offensive
 … when writing computer games, for example, programmers need to be careful that they don’t
include items which some cultures would find offensive or obscene …
Cambridge International AS & A Level Computer Science 4
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

 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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

End of chapter questions


1 a, b Ethics governs professional interactions.
Legal covers the law; whether an action is punishable by law.
Essentially, anything which breaks the law is termed illegal. Examples from computer
science would include copying software and then selling it without the permission of the
copyright holders.
Unethical behaviour is essentially breaking a code of conduct. For example, if somebody
works for a software company and passes on some of the ideas to a rival company, this
would be regarded as unethical behaviour. Unless the software passed on is part of national
security, then it isn’t actually illegal to do this.
c i)
 ‘assist colleagues in their professional development’ – Nicolae was given little or no
help in this area.
 ‘takes responsibility for detecting, correcting and reporting errors in software’ – since
the programming language was outside Nicolae’s knowledge he wasn’t comfortable
overseeing the project.
 ‘ensures an appropriate method is used for any project on which they work’ – Nicolae
had no previous experience on which to judge this.
(The above 3 are one of many you may choose as long as you can tie his three issues to the
task described.)
(ii) 7.02
6.08
3.05
(The above 3 are one of many you may choose as long as you can tie his three issues to
the task described.)
2 a, b, c

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.

Free software and open source initiative


 The open source initiative allows users to use source code from published software free of
charge …
 … it is very similar to free software …
 … with both types of software, users have the freedom to run, copy, change or adapt this
software.
 The originators of this type of software stress this is based on liberty and not price …
 … this means that a user is guaranteed the freedom to study and modify the software
source code in any way to suit their requirements.
 Essentially a user is allowed to do the following
Cambridge International AS & A Level Computer Science 7
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

 run the software for any legal purpose they wish


 study the software source code and modify it where necessary to meet their needs
 the software (in either original or modified form) can be passed on to friends, family or
colleagues.
 A user of the software doesn’t need to seek permission to do any of the above actions since
it isn’t protected by any copyright restrictions …
 … however, it is important that:
 the user cannot add source code from another piece of software unless this is also
described as free software
 the user cannot produce software which copies existing software subject to copyright
laws
 the user cannot adapt the software in such a way that it infringes copyright laws
protecting other software
 the user may not use the source code to produce software which is deemed offensive by
third parties.

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)

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

4 a, b

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 8 Student Book Answers


8.1 What you should already know
1 Suggestions to discuss include
 School database
 Database of births
 Examination board entries
 Doctors records
 Social media records, for example Facebook users

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

b) See Section 8.1 – key terms

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 8C

Activity 8D

(P SOR\HH (P SOR\HH
3RVLWLRQ
1XP EHU 1DP H

 -DPHV7H\ )LQDQFLDO'LUHFWRU

 3DXO/HLJK $FFRXQWDQW

 6X]\0H\ 3HUVRQQHO0DQDJHU

Employee Table

&RQWDFW &RQWDFW (P DLO


&RQWDFW1DP H
1XP EHU $GGUHVV

 -DPHV6PLWK MDPHV# STUFRP

 0LVKDO+XVVDQL PK# [\]FRP

 0DU\&KHXQJ PFK# DEFFRP

 'HDQ.QLJKW NQG# VZ]FRP

 0DU\-RQHV PDU\# [\]FRP

Contact Table

&RQWDFW (P SOR\HH
1XP EHU 1XP EHU

 

 

 

 

 

 

Employee Contact Table

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

8.2 What you should already know


1 a) Depends on student, probably MySQL or Access
b) Suggestions include parts database, school database, employee database
2 a) Back-up is a copy of a file in case the original is destroyed or corrupted.
b) Access rights are the permissions given to database users to access, modify or delete data.
c) Back-up ensures that if data is destroyed or corrupted it can be replaced; access rights help to
prevent unauthorised access to data.

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

8.3 What you should already know


1

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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 8I
SELECT COUNT(STUDENTSUBJECT.ExamMark)
FROM STUDENTSUBJECT;

SELECT AVG(STUDENTSUBJECT.ExamMark)
FROM STUDENTSUBJECT;

8.4 End of chapter questions


1 a) ProgDev table has repeated group of attributes.
b)
FirstName Team

Alice WC

Charles PC

Ahmed QR

FirstName ProgramName NoOfDays Customer

Alice TV control 3 SKM

Alice Ice alert 2 WZP

Alice Digital camera 6 HNC

Charles Oil flow 1 GEB

Charles Rescue pack 8 BGF

Ahmed TV control 2 SKM

Ahmed Accounts 8 ARC

Ahmed Digital camera 4 HNC

Ahmed Test Pack 3 GKN

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)

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 9 Student Book Answers


What you should already know
1 Procedure – a single set of statements that can be grouped together and called in a program when
required, rather than repeated each time the statements are used.
2 Function – a single set of statements grouped together that return a value and are called in a
program when required, rather than repeated each time the statements are used.
3 Algorithm – an ordered set of steps to complete a task.
4 Structured English – using English words and mathematical operations to show the steps in an
algorithm.
5 Flowchart – a diagrammatical representation of the steps in an algorithm.
6 Pseudocode – shows the detailed logical steps in an algorithm using a set of keywords, declared
and typed identifiers and mathematical and logical operators.
Flowchart – Figure 9.3, Pseudocode before – Figure 9.3, Programs – before ACTIVITY 9F

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB

'IF - single choice with alternative VB


Module Module1

Sub Main()

Dim MyValue, YourValue As Integer


Console.Write("Please enter my value ")
MyValue = Integer.Parse(Console.ReadLine())
Console.Write("Please enter your value ")
YourValue = Integer.Parse(Console.ReadLine())
If MyValue > YourValue Then
Console.WriteLine("I win")
Else
Console.Writeline("You win")
End If
Console.ReadKey() 'wait for keypress

End Sub

End Module

Java

//IF - single choice with alternative Java


import java.util.Scanner;
class IFProgramWithAlt
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);

System.out.println("Please enter my value ");


int MyValue = myObj.nextInt();
System.out.println("Please enter your value ");
int YourValue = myObj.nextInt();

if (MyValue > YourValue)


{
System.out.println("I win");
} else {
system.out.println("You win");
}
}
}

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Python - does not have a case statement

# - Multiple choice Python


X=0
Y=0
Direction = input("Please Enter N, S, E or W ")

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)

VB – uses Select Case and Case Else


'Select Case VB
Module Module1

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java – uses switch case and default


// Switch Case Java

import java.util.Scanner;
public class CaseStatement
{
public static void main(String args[])
{
int X = 0,Y = 0;
Scanner myObj = new Scanner(System.in);

System.out.println("Please Enter N, S, E or W ");


String Direction = myObj.next();
switch (Direction){
case "N":
Y = Y + 1;
break;
case "S":
Y = Y - 1;
break;
case "E":
X = X + 1;
break;
case "W":
X = X - 1;
break;
default:
System.out.println("Error");
}
System.out.println(X + " " + Y);
}
}

Activity 9D

FOR without step

Python - does not reach 10


# FOR - simple loop Python without step
for Counter in range (1,10):
print(Counter)

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB - does reach 10
'FOR - simple loop VB without step
Module Module1

Sub Main()

Dim Counter As Integer


For Counter = 1 To 10
Console.WriteLine(Counter)
Next
Console.ReadKey() 'wait for keypress
End Sub

End Module

Java - does reach 10 but always needs to include an increment


//FOR - simple loop Java always needs to include an increment
class FORProgramWithoutStep
{
public static void main(String args[])
{
for (int Counter = 1; Counter <= 10; Counter++)
{
System.out.println(Counter);
}
}
}

REPEAT UNTIL loop

Python - does not have a repeat loop

VB – uses Do and Loop Until

'REPEAT UNTIL loop


Module Module1

Sub Main()
Dim Number As Integer
Do
Console.Write("Please enter a positive number ")
Number = Console.ReadLine()

Loop Until Number > 0


Console.ReadKey() 'wait for keypress

End Sub

End Module

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java – uses a post condition while loop


//Post condition loop
import java.util.Scanner;
class PostConditionLoop
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int Number = 0;
do {
System.out.println("Please enter a positive number ");
Number = myObj.nextInt();
}
while (Number <= 0);
}
}

While loop

Python – uses while and indentation


# WHILE Python
Number = 0
while Number >= 0:
Number = int(input("Please enter a negative number "))

VB – uses While and End While


'WHILE loop
Module Module1

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

Java – uses a pre-condition while loop


//Pre-condition while loop
import java.util.Scanner;
class PreConditionWhileLoop
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int Number = 0;
while (Number >= 0){
System.out.println("Please enter a negative number ");
Number = myObj.nextInt();
}
}
}

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Identifier Name Description


Counter To count the number of attempts
Password1 To store the first password attempt
Password2 To store the second password attempt

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Java – note the use of .equals for string comparison


//three attempts at checking password
import java.util.Scanner;
class ACTIVITY9F
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
int Counter = 0;
String Password1 = "Pass1", Password2 = "Pass2";
do {
System.out.println("Enter your password ");
Password1 = myObj.next();
System.out.println("Enter your password again ");
Password2 = myObj.next();
Counter = Counter + 1;
}
while ((!Password1.equals(Password2)) && (Counter != 3));
if (Password1.equals(Password2)){
System.out.println("Password correct");
} else {
System.out.println("Password incorrect");
}
}
}

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Identifier Name Description


PBTimeSeconds Personal Best time in seconds

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

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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"

Identifier Name Description


Mark Exam mark
Grade Exam grade
Reply Check for another mark

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

OUTPUT "Please enter length of radius "


INPUT Radius
Area  Pi * Radius * Radius
ENDIF

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

Select Case Shape


Case = "Square"
Console.Write("Please enter the side ")
Side = Console.ReadLine()
Area = Side * Side
Case = "Triangle"
Console.Write("Please enter the base ")
Base = Console.ReadLine()
Console.Write("Please enter the height ")
Height = Console.ReadLine()
Area = (Base * Height) / 2
Case = "Circle"
Console.Write("Please enter the radius ")
Radius = Console.ReadLine()
Area = Pi * Radius * Radius
End Select
If Area <> 0.0 Then

Cambridge International AS & A Level Computer Science 13


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Console.WriteLine("Area of shape " + Shape + " is " + Area.ToString())


End If
Console.ReadKey() 'wait for keypress

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;

Scanner myObj = new Scanner(System.in);

System.out.println("Please enter the shape ");


String Shape = myObj.next();
switch (Shape){
case "Square":
System.out.println("Please enter the side ");
Side = myObj.nextInt();
Area = Side * Side;
break;
case "Triangle":
System.out.println("Please enter the base ");
Base = myObj.nextInt();
System.out.println("Please enter the height ");
Height = myObj.nextInt();
Area = (Base * Height) / 2;
break;
case "Circle":
System.out.println("Please enter the radius ");
Radius = myObj.nextInt();
Area = Pi * Radius * Radius;

}
if (Area != 0.0) {
System.out.println("Area of " + Shape + " is " + Area);
}
}
}

Cambridge International AS & A Level Computer Science 14


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

End of chapter questions


1 See Key terms 9.2.
2 See Section 9.1.
3 See Section 9.2.5.
4 a) 40 b) 314.2 c) Z not declared error d) True.
5 a) i) 13 or 14 ii) 07, 11 or 19 iii) 01 to 24
b)
Identifier Name Description
Choice Store Menu Choice
Temperature Store temperature input
ConvertedTemperature Store converted temperature

c) Use a variable Try

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

Cambridge International AS & A Level Computer Science 15


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 10 Student Book Answers


What you should already know
DECLARE Largest, Smallest, Counter : INTEGER
DECLARE NumberStore : ARRAY[1:5} OF INTEGER
FOR Counter  1 To 5
OUTPUT "Enter Number ", Counter
INPUT NumberStore[Counter]
NEXT Counter
Largest  NumberStore[1]
Smallest  NumberStore[1]
FOR Counter  2 To 5
IF NumberStore[Counter] > Largest
THEN
Largest  NumberStore[Counter]
ENDIF
IF NumberStore[Counter] < Smallest
THEN
Smallest  NumberStore[Counter]
ENDIF
NEXT Counter
OUTPUT "Largest number ", Largest
OUTPUT "Smallest number ", Smallest

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB
'student record
Module Module1

Sub Main()

Dim myStudent As TStudentRecord


myStudent.name = "Ahmad Sayed"
myStudent.dateOfBirth = #10/03/2010#
myStudent.group = "5A"
myStudent.gender = "Male"
Console.WriteLine("Name " + myStudent.name)
Console.Write("Date of Birth ")
Console.WriteLine(myStudent.dateOfBirth)
Console.WriteLine("Class " + myStudent.group)
Console.WriteLine("Gender " + myStudent.gender)
Console.ReadKey()
End Sub
Structure TStudentRecord
Dim name As String
Dim dateOfBirth As Date
Dim group As String
Dim gender As String
End Structure
End Module

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
//student record
import java.util.*;
class ACTIVITY10C {
static class TStudentRecord {
String name;
String dateOfBirth;
String group;
String gender;

public void TstudentRecord() {


name = "";
dateOfBirth = "";
group ="";
gender ="";
}
}

public static void main(String args[]){


TStudentRecord myStudentRecord = new TStudentRecord();
myStudentRecord.name = "Ahmad Sayed";
myStudentRecord.dateOfBirth = "10/03/2010";
myStudentRecord.group = "5A";
myStudentRecord.gender = "Male";

System.out.println("Name " + myStudentRecord.name);


System.out.println("Date of Birth " +
myStudentRecord.dateOfBirth);
System.out.println("Group " + myStudentRecord.group);
System.out.println("Gender " + myStudentRecord.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)

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 ++){

System.out.println (myList[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)

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

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
print (*myList)

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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();
}
}

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

objMyFileRead = New StreamReader("textFile.txt")


Do
textLn = objMyFileRead.ReadLine
Console.WriteLine(textLn)
Loop Until textLn = ""
objMyFileRead.Close()

Console.ReadLine()

End Sub

End Module

Cambridge International AS & A Level Computer Science 13


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 {

public static void main(String[] args) {


Scanner myObj = new Scanner(System.in);
String textLn;
try {
FileWriter myFileWriter = new FileWriter("textFile.txt",
false);
PrintWriter myPrintWriter = new PrintWriter(myFileWriter);

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();
}
}

Cambridge International AS & A Level Computer Science 14


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 15


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

End of chapter questions

1 a) Stack – see 10.4


b) Queue – see 10.4
c) Linked List – see 10.4
A composite data type is defined using an existing data type, for example a record of name and
address which are both of type string.
Read the all data items from a stack (FIFO) into a queue (LIFO) then read them back into the
stack.
Top of Queue Top of Stack Top of Queue
Item 1 Item 1 Item 4

Item 2 Item 2 Item 3

Item 3 Item 3 Item 2

Item 4 Item 4 Item 1

Items read into stack in the order 1, 2, 3, and 4


Items popped off the stack and placed back in the queue in the order 4, 3, 2 and 1

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

5 a) outer loop is executed 9 times


inner loop is executed 9 times (for each iteration of the outer loop)
not dependant on the dataset

ii)
NumberOfItems  10
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
NEXT
NumberOfItems  NumberOfItems - 1
UNTIL NoMoreSwaps = TRUE

6 a)

Head Ben

Ahmed

Jatinder
Tail

Cambridge International AS & A Level Computer Science 17


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

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 p
IF HeadPointer = 0
THEN
TailPointer  0
ENDIF
// link released node to free list
Queue[CurrentPointer].Pointer  FreePointer
FreePointer  CurrentPointer
ENDIF
ENDPROCEDURE

Cambridge International AS & A Level Computer Science 18


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 11 Student Book Answers


What you should already know
Pseudocode
DECLARE myList : ARRAY[0:9] OF INTEGER
DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE swap : BOOLEAN
DECLARE temp : INTEGER
DECLARE top : INTEGER
upperBound  9
lowerBound  0
DECLARE found : BOOLEAN

// input values to myList


FOR index  lowerBound TO upperBound
OUTPUT "Please Enter Value "
INPUT myList[index]
NEXT index
top  upperBound

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

// Output sorted list


OUTPUT "Sorted List"
FOR index  lowerBound TO upperBound
OUTPUT myList[index]
NEXT index

// 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

#output sorted list


print (*myList)
#search for 27

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

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

'input values into myList


For index = lowerBound To upperBound
Console.Write("Please Enter Value ")
myList(index) = Console.ReadLine()
Next

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

'output sorted list


Console.WriteLine("Sorted List")
For index = myList.GetLowerBound(0) To
myList.GetUpperBound(0)
Console.Write(myList(index).ToString() + " ")
Next
Console.WriteLine()

'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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

// input values to myList


for (index = lowerBound; index <= top; index++){
System.out.println("Please enter value ");
myList[index] = myObj.nextInt();
}
System.out.println();

//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));

// output sorted list


System.out.println("sorted list");
for (index = lowerBound; index <= myList.length - 1;
index++){
System.out.print(myList[index] + " ");
}
System.out.println();

//search for 27
found = false;
index = lowerBound;

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

System.out.println("Volume is " + volume);


System.out.println("Surface area is " + surfaceArea);

}
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")

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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");
}
}
}

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

1 MsgBox – pop up message box


2 Format – for displaying dates
3 Sign – determines the sign of a number
4 Int – returns the integer part of a number
5 Rnd – returns a random number
6 Clipboard – access to the clipboard

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

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 13


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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);
}
}

Cambridge International AS & A Level Computer Science 14


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 11H
// procedure to convert Celsius to Fahrenheit
DECLARE myTemp : REAL
PROCEDURE Fahrenheit (BYREF temperature : REAL)
temperature  temperature * 9 / 5 +32
ENDPROCEDURE

CALL Fahrenheit (myTemp)

Activity 11I
Pseudocode
// function to convert Celsius to Fahrenheit
DECLARE myTemp : REAL
FUNCTION fahrenheit (temperature : REAL)RETURNS REAL
temperature  temperature * 9 / 5 +32
ENDFUNCTION

myTemp  fahrenheit (myTemp)

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

Cambridge International AS & A Level Computer Science 15


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
// function to convert Celsius to Fahrenheit
import java.util.Scanner;
class ACTIVITY11I {
static double fahrenheit(double temperature){
return temperature * 9 / 5 + 32;
}

public static void main(String args[]){


Scanner myObj = new Scanner(System.in);
System.out.println ("Please enter a temperature in Celsius");
double myTemp = myObj.nextDouble();
myTemp = fahrenheit (myTemp);
System.out.println ("Temperature in Fahrenheit is" + myTemp);
}
}

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

End of chapter questions


1 DECLARE height : REAL
CONSTANT maxHeight  25
DECLARE width : REAL
CONSTANT maxWidth  30
DECLARE hypotenuse : REAL
DECLARE area : REAL
2 REPEAT
INPUT height
UNTIL height > 0 and height <= maxHeight
REPEAT
INPUT width
UNTIL width > 0 and height <= maxWidth
3 a) i) hypotenuse  SQUAREROOT(height * height + width * width)
ii) area  (width * height) / 2

iii) perimeter  hypotenuse + height + width

Cambridge International AS & A Level Computer Science 16


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b) OUTPUT " Menu"


OUTPUT "1 ........... Area"
OUTPUT "2 ..... Hypotenuse"
OUTPUT "3 ...... Perimeter"
INPUT choice
CASE choice OF a value
1 : area  (width * height) / 2
2 : hypotenuse  SQUAREROOT(height * height + width *
width)
3 : perimeter  SQUAREROOT(height * height + width *
width) + height + width
OTHERWISE OUTPUT "Incorrect choice "
ENDCASE
c)

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

width = float(input("Please enter the width of the triangle "))


while width < 0 or width > maxWidth:
width = float(input("Please enter the width of the triangle "))

print (" Menu")


print ("1.......... Area")
print ("2.....Hypotenuse")
print ("3......Perimeter")
choice = int(input("Please enter your choice of calculation "))

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

Cambridge International AS & A Level Computer Science 17


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Console.Write("Please enter your choice of calculation ")


choice = Integer.Parse(Console.ReadLine())
Select Case choice
Case 1
area = width * height / 2
Console.WriteLine("The area of the triangle is " +
Str(area))
Case 2
hypotenuse = Math.Sqrt(height * height + width * width)
Console.WriteLine("The hypotenuse is " + Str(hypotenuse))
Case 3
perimeter = Math.Sqrt(height * height + width * width) +
height + width
Console.WriteLine("The perimeter is " + Str(perimeter))
Case Else
Console.WriteLine("Incorrect choice")
End Select
Console.ReadLine()

End Sub

End Module

Cambridge International AS & A Level Computer Science 18


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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");

System.out.println("Please enter your choice of calculation ");


int choice = myObj.nextInt();

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.

Cambridge International AS & A Level Computer Science 19


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

5 a)Procedure – subroutine that may return a value


b)Function – subroutine that always returns a value
c)Parameter – a value that’s passed to a function or procedure
d)Header – the first statement of a procedure/function definition that contains the name and any
parameters used.
6 a) A function always returns a value and can be used a part of an expression, a procedure may or
may not change a variable and it is called as a single statement.
b) Parameters passed by value cannot be changed, parameters passed by reference can be
changed.
c) Procedures are defined once and called many times, the definition included all the statements
found in the procedure and the call is a single statement.
7 a)
Identifier Data type Description

YearCount Integer Loop counter

PurchasePrice Integer Purchase price of the car

CurrentValue Real The changing depreciated value

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

Cambridge International AS & A Level Computer Science 20


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 12 Student Book Answers


12.1 What you should already know
Stages of the systems development lifecycle
 Analysis
 Design
 Coding
 Testing
 Maintenance
Types of program development lifecycle
 Waterfall
 V-shaped model
 Iterative model
 Prototyping

12.2 What you should already know


Example answer
// procedure to convert Celsius to Fahrenheit
DECLARE myTemp : REAL
PROCEDURE Fahrenheit (BYREF temperature : REAL)
temperature  temperature * 9 / 5 +32
ENDPROCEDURE

CALL Fahrenheit (myTemp)

// function to convert Celsius to Fahrenheit


DECLARE myTemp : REAL
FUNCTION fahrenheit (temperature : REAL)RETURNS REAL
temperature  temperature * 9 / 5 +32
ENDFUNCTION

myTemp  fahrenheit (myTemp)

Activity 12A

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 12B

Activity 12C

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 12D
// function to convert Celsius to
Fahrenheit
DECLARE myTemp : REAL
DECLARE myScale : CHAR
DECLARE finish : BOOLEAN

Finish  FALSE

// function to convert Celsius to


Fahrenheit
FUNCTION fahrenheit (temperature :
REAL)RETURNS REAL
temperature  temperature * 9 / 5 +32
ENDFUNCTION

// function to convert Fahrenheit to Celsius


FUNCTION celsius (temperature : REAL)RETURNS REAL
temperature  (temperature – 32) * 5 / 9
ENDFUNCTION

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 12E
Current state Event Next state

Off Single press On

Off Double press Off

Standby Single press On

Standby Double press Standby

On Single press Standby

On Double press Off

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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

number1 number2 sign answer OUTPUT


20 10 + 30 30
20 10 - 10 10
20 10 * 200 200
20 10 / 2 2
20 10 ? 0
20 0 / 0

Activity 12G
Example test data
10, V 10, S 10, v 10, p ten, V −1, V

radius reply answer OUTPUT


10 V 30 Volume 4186.7
10 S 10 Surface Area 1236.8
10 v 200 Surface Area 1236.8
10 p 2 Surface Area 1236.8
ten V 0 Input error
-1 V 0 Please enter a positive
number

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.

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

End of chapter questions


1 a) b)

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.

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 13 Student Book Answers


13.1 What you should already know
1 a) String
b) Integer
c) Real
d) Date
e) Boolean
2 TYPE TAnimalRecord
DECLARE Name : STRING
DECLARE Species : STRING
DECLARE DateOfBirth : DATE
DECLARE Location : STRING
DECLARE BornInZoo : BOOLEAN
DECLARE Notes : STRING
ENDTYPE

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.

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

13.2 What you should already know


1 Read, to read the data stored in the file.
Write to write data to a file, this will overwrite any data stored in the file.
Append to add new data to the end of a file.
2 a) DECLARE myTextFile : STRING
myTextFile  "myText.txt"
b) DECLARE textLn : STRING
OPEN myTextFile FOR WRITE
REPEAT
OUTPUT "Please enter a line of text"
INPUT textLn
IF textLn <> ""
THEN
WRITEFILE, textLn
ELSE
CLOSEFILE(myTextFile)
ENDIF
UNTIL textLn = ""
c) OUTPUT "The file contains these lines of text:"
OPEN myTextFile FOR READ
REPEAT
READFILE, textLn
OUTPUT textLn
UNTIL EOF(myTextFile)
CLOSEFILE(myTextFile)
d) DECLARE textLn : STRING
OPEN myTextFile FOR APPEND
REPEAT
OUTPUT "Please enter a line of text"
INPUT textLn
IF textLn <> ""
THEN
WRITEFILE, textLn
ELSE
CLOSEFILE(myTextFile)
ENDIF
UNTIL textLn = ""

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

print("The file contains these lines of text")


myFile = open ("myText.txt","r")
textLn = myFile.read()
print(textLn)

myFile = open ("myText.txt","a")


textLn = "append"
while textLn != "":
textLn = input("Please enter a line of text ")
if textLn != "":
myFile.write(textLn + "\n")
else: myFile.close()

print("The file now contains these lines of text")


myFile = open ("myText.txt","r")
textLn = myFile.read()
print(textLn)

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

objMyFileWrite = New StreamWriter("textFile.txt")


Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()

Do
objMyFileWrite.WriteLine(textLn)
Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()
Loop Until textLn = ""

objMyFileWrite.Close()

objMyFileRead = New StreamReader("textFile.txt")


Do While Not textLn Is Nothing
textLn = objMyFileRead.ReadLine
Console.WriteLine(textLn)
Loop
objMyFileRead.Close()

objMyFileAppend = New StreamWriter("textFile.txt", True)


Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()
Do
objMyFileAppend.WriteLine(textLn)
Console.Write("Please enter a line of text ")
textLn = Console.ReadLine()
Loop Until textLn = ""
objMyFileAppend.Close()

objMyFileReadAgain = New StreamReader("textFile.txt")


Do While Not textLn Is Nothing
textLn = objMyFileReadAgain.ReadLine
Console.WriteLine(textLn)
Loop

objMyFileReadAgain.Close()

Console.ReadLine()

End Sub

End Module

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 {

public static void main(String[] args) {


Scanner myObj = new Scanner(System.in);
String textLn;
try {
FileWriter myFileWriter = new FileWriter("textFile.txt", false);
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");
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");

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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();
}
}

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.

13.3 What you should already know


1 a) 00110000 c) 10011100 e) 11111110
b) 01111010 d) 11001001
2 a) 51 c) −77 e) −1
b) 126 d) −14
3 a) 11001100 c) 10110100 e) 10000010
b) 11100011 d) 11000001
4 a) 01001111 e) 1)01001100 i) 1)11011111
b) 10000000 f) 1)00100010 j) 11101011
c) 10000001 g) 1)00000001
d) 11011001 h) 11111100
5 a) 1.23 × 108 c) −1.2 × 103 e) 1.24005 × 10−5
b) 2.505 × 1015 d) 2.341 × 10−9
6 a) i) 2.1/5 × 101 ii) 1.17/4 × 102 iii) 5.58/20 × 102
b) i) 11/16 × 8 (23) ii) 41/64 × 16 (24) iii) 52/64 × 16 (24)

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

..j)
1 0 1 1 0 0 0 0 1 1 1 1 1 1 1 0

2 a) 3.5 = 7/2 = 7/8 × 22 = 0.1110000 × 00000010


b) 0.3125 = 10/32 = 5/16 = 0.0101000 × 00000000 (or 0.1010000 × 11111111)
c) 15.375 = 123/8 = 123/128 × 24 = 0.1111011 × 00000100
d) 41/64 = 0.1010010 × 00000000
e) 9.125 = 73/8 = 73/128 × 24 = 0.1001001 × 00000100
f) −15/32 = −1 + 17/32 = 1.1000100 × 00000000
g) −3.5 = −7/2 = −7/8 × 22 = 1.0010000 × 00000010
h) −10.25 = −41/4 = −41/64 × 24 = 1.0101110 × 00000100
i) −67/64 = −67/128 × 21 = 1.0111111 × 00000001
j) −107/32 = −107/128 × 22 = 1.0010101 × 00000010

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.

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

4 a) .88 × 2 = 1.76 so we will use the 1 value to give 0.1


.76 × 2 = 1.52 so we will use the 1 value to give 0.11
.52 × 2 = 1.04 so we will use the 1 value to give 0.111
.04 × 2 = 0.08 so we will use the 0 value to give 0.1110
.08 × 2 = 0.16 so we will use the 0 value to give 0.11100
.16 × 2 = 0.32 so we will use the 0 value to give 0.111000
.32 × 2 = 0.64 so we will use the 0 value to give 0.1110000
.64 × 2 = 1.28 so we will use the 1 value to give 0.11100001
.28 × 2 = 0.56 so we will use the 0 value to give 0.111000010
.56 × 2 = 1.12 so we will use the 1 value to give 0.1110000101
We have to stop here since our system uses a maximum of 10 bits. Now the value of 2 (in binary)
is 0010; this therefore gives us:
2.88 = 0010.1110000101
Moving the binary point as far to the left as we can gives us:
0.101110000101 × 22 (22 since we moved the point 3 places)
Thus, we get 0.101110000 × 000010
(mantissa) (exponent)
2
This is equal to: 23/32 × 2 = 23/8 = 2.875
So, 2.88 is stored as 2.875 in our floating-point system.
b) .38 × 2 = 0.76 so we will use the 0 value to give 0.0
.76 × 2 = 1.52 so we will use the 1 value to give 0.01
.52 × 2 = 1.04 so we will use the 1 value to give 0.011
.04 × 2 = 0.08 so we will use the 0 value to give 0.0110
.08 × 2 = 0.16 so we will use the 0 value to give 0.01100
.16 × 2 = 0.32 so we will use the 0 value to give 0.011000
.32 × 2 = 0.64 so we will use the 0 value to give 0.0110000
.64 × 2 = 1.28 so we will use the 1 value to give 0.01100001
.28 × 2 = 0.56 so we will use the 0 value to give 0.011000010
We have to stop here since our system uses a maximum of 10 bits. Now the value of −5 (in
binary) is −0101; this therefore gives us:
− 5.88 = − 0101.011000010
Moving the binary point as far to the left as we can gives us:
− 0.101011000 × 23 (23 since we moved the point 3 places)
Thus we get − 0.101011000 000011
(mantissa) (exponent)
Applying two’s complement we get:
(1.010100111 + 1) × 000011
i.e. 1.010101000 × 000011
This is equal to: − 43/64 × 23 = − 43/8 = − 5.375
So − 5.38 is stored as − 5.375 in our floating-point system.

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

End of chapter questions


1 a) i) A = −1 + ¼ × 2−1 = −3/4 × 1/2 = −3/8 = −0.375
B = (1/2 + 1/8) × 23 = 5/8 × 8 = 5
C = (1/8 + 1/32) × 25 = 5/32 × 32 = 5
ii) C
iii) Because there could be more than one way to represent the same value and some options are
not possible (e.g. 0.1000000 × 00000010 could become 0.0000000 × 00001001 which is not
possible).
b) Accuracy and range
 16-bit mantissa and 8-bit exponent gives high accuracy but small range.
 Increasing mantissa size would increase accuracy further ….
 …. but correspondingly reducing the exponent size would reduce the range (and the converse
is true).
c) Because normalised values must have 1.0 or 0.1 therefore it is not possible to store the value
zero using this method.
2 a) i) (1/2 + ¼ + 1/8 + 1/64) × 27 = 57/64 × 27 = 114
ii) (−1 + ¼ + 1/32 + 1/64 + 1/128) × 2−4 = −89/128 × 1/16 = −89/211 = 0.000434571
b) i) 4.75 = 19/4 = 19/32 × 23 = 0.100110000000000 × 000011
ii) −8.375 = −67/8 = −67/128 × 24 = (−1 + 61/128) × 24
= 1.011110100000000 × 000100
3 a) +3.5
01110000 00000010
= 11.1
= 0.11 × 22
b) −3.5
10010000 00000010
One’s complement of 8-bit mantissa for +3.5 gives:
10010000
4 a) i) Tseason
ii) TJournalRecord
iii) STRING
vi) TJournalRecord or Tseason
b) DECLARE Journal : TJournal
Journal.title  "Spring Flowers"
Journal.author  "H Williams"
Journal.publisher  "XYZ Press"
Journal.noPages  40
Journal.season  Spring

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 14 Student Book Answers


14.1 What you should already know
1 a) IP = internet protocol
TCP = transport control protocol
b) Protocols are sets of rules agreed by sender and receiver when sending data or communicating
over a network.
2 a) Peer-to-peer – each node in a peer-to-peer network is connected to each other node; each node
provides services to all the users on the network.
b) Benefits:
 Each workstation can provide a service or request a service.
 Each peer has its own data.
 The network doesn’t suffer from ‘bottlenecks’.
Drawbacks:
 It offers little security since there is no central security system.
 It works well with only a few devices (for example, 12) otherwise suffers performance and
management issues.
 It suffers instability since each workstation needs to manage (for example, update) its own
data.
3 a) Stack – last in first out (LIFO) structure; used to store collection of objects.
b) Queue – first in first out (FIFO) structure; new items added at end of queue and removed from
front of queue.
c) Uses of stack
 used in binary searches
 used in the “UNDO” mechanism in text editors
 used in syntax checks when compiling source code.
Uses of queue
 used in buffers
 used in parsing during compilation (infix to postfix).
4 a) Ethernet is the main LAN protocol
 it transmits data in frames; it is the protocol used when connecting a number of computers
to form a LAN
 it controls the passing of information and avoids simultaneous transmission by two or more
computers.
b) IP conflicts
 occur when two receiving devices on a network have the same IP addresses
 can be resolved by restarting the computer so that a dynamic IP address would be reassigned
 the administrator can change IP addresses on devices which don’t have static IP addresses.
(5) (a) DNS – domain name system gives domain names for internet hosts and is a system for finding
IP addresses of domain names.
(b) Http – (hypertext transfer protocol) the protocol responsible for the correct transfer of files that
make up web pages from the world wide web.
(c) Status flags – the special registers in a computer that contain data/information about the state
of the processor. The individual values are read or written to by machine code instructions
during execution.
Cambridge International AS & A Level Computer Science 1
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

14.2 What you should already know

1 a) PSTN – public switched telephone network


 used as means to connect computer and LANs via telephone network
 lines are always ‘open’ and always remain active
 makes use of circuit switching.
b) VoIP – Voice over internet Protocol
 communication method (audio and visual) across internet
 uses packet switching
 uses encryption and data compression
 connection only made during actual transmission
2

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

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

2 a) Ethernet is the main LAN protocol.


 It transmits data in frames.
 It is the protocol used when connecting a number of computers to form a LAN.
 It controls the passing of information and avoids simultaneous transmission by two or more
computers.
b) frame:

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

End of chapter questions


1 a)

b)
Application layer
Transport layer
Internet (network) layer
Network/Datalink layer

c) SMTP
 text-based protocol when sending emails
 this is a push protocol.

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 15 Student Book Answers


15.1 What you should already know
1 i)
00111100 C 0
01000110 V 1
10000010 N 1
ii)
11000100 C
10111010 V 1
101111110 N 0
2

(3) (a) (i) Bus width


 word size used by the computer
 size of memory location which can be directly addressed/accessed
Cambridge International AS & A Level Computer Science 1
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

ii) smallest width = control bus


iii) Address bus upgrade
 larger word size can be used
 more addresses can be accessed directly.
b) i) Clock
 clock speed defines clock cycle that the computer system uses to synchronise all
operations
 increasing clock speed can increase processing speed of computer.
ii) Interrupts
 interrupt is a signal sent to CPU by a device/program,/user which requires CPUs attention
according to priority level
 interrupts can be caused by
 i/o processing (e.g. disk drive is ready)
 hardware fault (e.g. paper jam in printer)
 program error (e.g. division by zero would produce software error)
 user interaction (e.g. user presses the <BREAK> key on keyboard.

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 …

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

 … 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

15.2 What you should already know


1
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 1

1 1 1 0

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

((P.Q) + (Q + R)).R becomes “INPUT R” after circuit simplification

3 a) (S1.S2) + (S2.S3) + (S1.S3)

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

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

1 1 1 1 1

b) B.D + C.D = D.(C + B)


AB
00 01 11 10
CD
00 0 0 0 0
01 0 1 1 0
11 1 1 1 1
10 0 0 0 0
c)

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)

End of chapter questions


1 a) A. B. C A. B. C A. B. C
b) A.B + A.C
AB
C 00 01 11 10
0 0 0 1 0
1 0 0 1 1
c)

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b i) Massive – many processors linked together.


ii) Parallel – to perform a set of coordinated computations simultaneously.
c) Hardware – processors need to be able to communicate so that processed data can be transferred
from one processor to another.
Software – suitable software which allows data to be processed by multiple processors
simultaneously.
6 a) S P Q R .R
b)
P Q R S
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 1
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0

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

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 16 Student Book Answers


16.1 What you should already know
1 Key OS management tasks
 memory management
 file management
 security management
 hardware management
 processor management
2 a) OS provides an environment in which programs can be run and gives an interface to human
operators.
b) The interface is a simple set of dials/switches and the device carries out repeated (relatively
simple) tasks not requiring an OS.
3 OS utility software
 hard disk formatter
 virus checker
 defragmentation software
 disk contents analysis/disk repair software
 file compression
 back-up software
4 Command line interface (CLI):
 It requires a user to type in instructions to choose options from menus, open software etc.
 There are often a number of commands that need to be typed in, for example, to save or load a
file.
 The user has to therefore learn a number of commands (which must be typed exactly with no
errors) just to carry out basic operations.
 It is also slow having to key in these commands every time an operation has to be carried out.
 However, the advantage of CLI is that the user is in direct communication with the computer
and is not restricted to a number of pre-determined options.
Graphical user interface (GUI)
 It allows the user to interact with a computer (or MP3 player, gaming device, mobile phone,
etc.) using pictures or symbols (icons) rather than having to type in a number of commands.
5 Interface software
 Provides communication with all input and output devices using device drivers.
 A device driver takes data from a file (defined by the operating system) and translates it into a
format that the input/output device can understand.
 It ensures each hardware resource has a priority so that they can be used and released as required.
6 a) Program libraries are used for
 software under development using already-written code in program libraries
 benefits to a developer writing software constructed of library files such as dynamic link
library (DLL) files
 when software routines are written (e.g. a sort routine), they are frequently saved in a
program library for future use by other programmers …
 … therefore a program stored in a program library would be known as a library program
 we also have the term library routines to describe subroutines which could be used in another
piece of software under development.

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Extension Activity 16B


a)
FCFS
A B C D E
0 45 63 68 91 102
SJF
C E B D A
0 5 16 34 57 102
SRTF
A B C B E B D A
0 8 10 15 20 31 42 65 102
Round Robin
A B C D E A B D E A D A
0 10 20 25 35 45 55 63 73 74 84 87 102
b)
FCFS = 61.75 ms
SJF = 28.0 ms
SRTF = 12.75 ms
Round Robin = 62.25 ms

16.3 What you should already know


1 Assembler, compiler, interpreter.
2 Assembler – only type of language translator available for low level languages, makes writing
programs easier as mnemonics can be used instead of hexadecimal.
Compiler – once translated the object program can be executed without the compiler present,
this means that generally compiled programs are smaller in size so take up less storage space
in primary and secondary memory, and the execution time taken by a task is usually shorter.

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Interpreter – during program development, errors can be corrected as encountered during


translation and/or execution leading to a reduced development time.
3 An integrated development environment often contains these features:
 an integrated editor to use instead of a separate program
 error diagnostics including auto-completion and auto-correction to prevent errors in
spelling and syntax
 a runtime environment is used to test a program, this can include inspection of variables
and executing statements one at a time
 prettyprinting to print out and easily readable copy of a program with the use of indenting
and colour coding keywords etc.

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

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Digit Digit Digit


Variable
Letter

Assignment
Variable = Variable Operator Variable

b) <variable> ::= <letter> | <letter> <digit> | <letter> <digit>


<digit>| <letter> <digit> <digit> <digit>
c) operator

Variable = Variable Operator Variable

<assignment> ::= <variable> = <variable> <operator> <variable>

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

End of chapter questions


1 a) FCFS = 17.5 ms
b) SJF = 6.25 ms
c) SRTF = 6.0 ms
d) round robin = 12.75 ms
2 a)
 The page is present in memory.
 Loaded at/stored/present in page frame 542//its memory address is 542.
b) i)
 The next instruction is first instruction in Page 6.
 Page 6 is not present in memory.
 The instruction can only be executed if present in memory.
 The program cannot continue until Page 6 is loaded.
ii) When there is an attempt to load an instruction for a Page not in memory
 a page default occurs/Page 5 finishes …
 … this generates an interrupt
 ISR code is executed
 causes the OS to load Page 6 into memory.
c) i) time of entry

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

4 a) i) From blocked to ready


 Process is waiting for resource/IO operation to complete (blocked state).
 When IO operation completed, process goes into ready queue (ready state).
ii) From running to ready
 When process is executing, it is allocated a time slice (running state).
 The process is allocated time in processor.
 When time slice completed, interrupt occurs …
 … process can no longer use processor even though it is capable of further processing
(ready state).
b) A process cannot move directly from ready state to blocked state because
 to be in blocked state, process must initiate some IO operation
 to initiate operation, process must be executing
 if process is in ready state, it cannot be executing/must be in running state.
c) i) exit/termination/completion
ii) when process has finished execution
d) A low-level scheduler
 decides which of processes is in ready state
 should get use of processor/be put in running state
 is based on position/priority
 is invoked after interrupt/OS call.
5 a) Programs can access data from memory when using virtual memory because
 program executes load process with a virtual address
 computer translates virtual address to give a physical address in memory
 if physical address not in memory, the OS loads it from the HDD
 computer then reads RAM using physical address and returns the data to program.

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Letter Letter Digit Digit

d)
<assignment_statement> ::= <variable> := <variable> <operator> <real>

<real> ::= <unsigned_integer> . <unsigned_integer>

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

9 a)
Statement Compilation stage
This stage can improve
the time taken to execute Lexical analysis
the statement: x = y + 0

This stage produces


Syntax analysis
object code

This stage makes use of


tree data structures Code generation

This stage enters symbols


in the symbol table Optimisation

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.

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

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

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Extension activity 17A


a) sender recipient
X=3 Y=5
73 (MOD 11) = 343 (MOD 11) 75 (MOD 11) = 16807 (MOD 11)
= 31 remainder 2 = 1527 remainder 10

103 (MOD 11) = 1000 (MOD 11) 25 (MOD 11) = 32 (MOD 11)
= 90 remainder 10 = 2 remainder 10

giving 10 as the encryption key


b) sender recipient
X=7 Y=6
77 (MOD 11) = 823543 (MOD 11) 76 (MOD 11) = 117649 (MOD 11)
= 74867 remainder 6 = 10695 remainder 4

47 (MOD 11) = 16384 (MOD 11) 66 (MOD 11) = 46656 (MOD 11)
= 1489 remainder 5 = 4241 remainder 5

giving 5 as the encryption key

End of chapter questions


1 a) QKD is a protocol used when sending encryption keys over a fibre optic network using quantum
cryptography technology
(b) Order: 10, 2, 6, 1, 5, 9, 3, 11, 8, 4, 7
(2) (a) SSL = secure socket layer
TLS = transport layer security
 TLS is a more modern version of SSL.
 They are client-server applications.
 They are standard cryptographic protocols …
 … to ensure security, authenticated communication.
 SSL encrypts the data.
 User knows if SSL secure due to HTTP and closed padlock.
b) i) Record protocol
 can be used with or without encryption
 contains data being transferred over Internet.
ii) Handshake protocol
 permits website and client to authenticate each other and to make use of encryption
algorithms
 secure session between client and website is established.
iii) Session caching
 avoids need to utilise computer time during each TLS connection
 TLS can establish either a new session or attempt to resume existing session …
 … the latter can save considerable computer time.

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

c) Differences between SSL and TLS


 It is possible to extend TLS by adding new authentication methods.
 TLS can make use of session caching which improves overall performance of computer
compared to using SSL.
 TLS separates handshaking process from record protocol layer (which holds all the data).
3 a) Order: 6, 1, 4, 5, 3, 2
b) Items on a digital certificate
 serial number
 CA that issued the certificate
 CA digital signature
 name of company/organisation
 subject’s public key
 period during which certificate is valid
 version number
 expiry date of certificate
 algorithm identification
 signature algorithm used
 company details/identifier.
(c) All certificate details condensed and put through a hashing algorithm (e.g. MD4/5) then encrypt
the number using the CAs private encryption key.

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 …

… therefore shortest route is: A → F → G → I → J


2

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

3 a)

b) shortest route: E B C D G
4 a) i)

ii) route order: A B C E G J


b) Time = Distance/Speed
 T1 (A to J directly) = 56/95 = 35.4 minutes
 T2 (A, B, C, E, G, J) = 50/80 = 37.5 minutes
 direct route (dual carriageway) is the quickest

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

iv) Active learning


 algorithms can interactively query source data to reach the desired output
 makes use of labelled data and unlabelled data
 makes use mainly of unlabelled data (based on cost reasons).
b) i) Back propagation
 initial system nodes are given ‘weights’
 actual output compared to expected outputs
 if results not satisfactory then ‘weights’ are changed
 ‘weights’ updated until no errors or results are within acceptable limits.
ii) There are two types of back propagation: static and recurrent.
 static maps static inputs to a static output
 mapping is instantaneous in static but this is not the case with recurrent
 training a network/model is more difficult with recurrent than with static
 with recurrent, activation is fed forward until a fixed value is achieved
3 a) i) Supervised learning can decide if emails are junk emails.
ii) In marketing, unsupervised learning can look for patterns in groups of individuals.
iii) Reinforcement learning is used in gaming and robotics.
iv) Semi-supervised (active) learning is used in the classification of web pages.
b) i) artificial intelligence
ii) machine learning
iii) deep learning
iv) unlabelled (data)
v) web crawler (spider bot)
vi) chatbot
vii) back propagation (of errors)
viii) regression
ix) labelled (data)
x) punishment and reward

End of chapter questions


1 a) i) C
ii) D
iii) E

Cambridge International AS & A Level Computer Science 5


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

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

iii) Photographic enhancement


 some of the latest smartphones now use deep learning to give DSLR quality to the
photographs taken by the smartphone
 the technology was developed by first of all taking the same photos using a smartphone
and then using a DSLR camera
 the deep learning system was then trained by comparing the two photographs
 then a large number of photographs already taken by a DSLR camera (but not by the
smartphone) were used to test the model.
3 random weighting
actual output
expected output
error gradients
minimised/removed
removed/minimised
back propagation
static/recurrent
recurrent/static
regression
4 a) Dijkstra’s algorithm will follow the path which is currently the shortest path, but pays no
attention to which direction we’re going in
A* builds on some idea of direction of the end point by adding an extra heuristic (H) value
which how far we have to go to reach the destination

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

b) i)

ii) Route: C A S H N Q
5

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

6) GPS will use A* algorithm:


 to reset heuristic values based on possible alternative route(s)
 re-calculate the shortest path/route based on f(n) = g(n) + h(n)
 disregard any routes that take in nodes M-J, M-A-D-G-F
7 a) i)

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}

Therefore reduced time (maximum) = 71 − 62 = 9 minutes

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 19 Student Book Answers


19.1 What you should already know
1 a) Stack – see Key terms 10.1 page 238
b) Queue - see Key terms 10.1 page 238
c) Linked list - see Key terms 10.1 page 238
2 a) Stack – see 10.4.1 page 251
b) Queue – see 10.4.2 page 253
c) Linked list – see 10.4.3 page 255
3
DECLARE myList : ARRAY[0:19] OF INTEGER
DECLARE upperBound : INTEGER
DECLARE lowerBound : INTEGER
DECLARE index : INTEGER
DECLARE item : INTEGER
DECLARE found : BOOLEAN
upperBound  19
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"
ELSE
OUTPUT "Item not found"
ENDIF

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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]

#enter item to search for


item = int(input("Please enter item to be found "))

found = False

for index in range(len(myList)):


if(myList[index] == item):
found = True

if(found):
print("Item found")
else:
print("Item not found")

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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}

'enter item to search for


Console.Write("Please enter item to be found ")
item = Integer.Parse(Console.ReadLine())

For index = 0 To myList.Length - 1


If (item = myList(index)) Then
found = True
End If
Next

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;

// enter item to search for


System.out.println("Please enter item to be found ");
item = myObj.nextInt();

for (index = 0; index < myList.length - 1; index++)


{
if (myList[index] == item)
{
found = true;
}
}
if (found)
{
System.out.println("Item found");
}
else
{
System.out.println("Item not found");
}

}
}

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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]

#enter item to search for


item = int(input("Please enter item to be found "))

found = False
lowerBound = 0
upperBound = len(myList) - 1

while (not found) and (lowerBound <= upperBound):


index = int((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):
print("Item found")
else:
print("Item not found")

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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}

'enter item to search for


Console.Write("Please enter item to be found ")
item = Integer.Parse(Console.ReadLine())

found = False
lowerBound = 0
upperBound = myList.Length - 1

Do
index = (upperBound + lowerBound) \ 2

If (item = myList(index)) Then


found = True
End If

If item > myList(index) Then


lowerBound = index + 1
End If

If item < myList(index) Then


upperBound = index - 1
End If

Loop Until (found) Or (lowerBound > upperBound)

If (found) Then

Console.WriteLine("Item found")

Else : Console.WriteLine("Item not found")

End If
Console.ReadKey()
End Sub
End Module

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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};

boolean found = false;


int lowerBound = 0;
int upperBound = myList.length - 1;
int index;

// enter item to search for


System.out.println("Please enter item to be found ");
int item = myObj.nextInt();

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;
}

while ((!found) && (upperBound >= lowerBound));

if (found)
{
System.out.println("Item found");
}
else
{
System.out.println("Item not found");
}

}
}

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 19D
Python
#Python program for Insertion Sort
myList = [4,46,43,27,57,41,45,21,14]

lowerBound = 0
upperBound = len(myList)

for index in range(lowerBound + 1, upperBound):


key = myList[index]
place = index -1
if myList[place] > key:
while place >= lowerBound and myList[place] > key:
temp = myList[place + 1]
myList[place + 1] = myList [place]
myList[place] = temp
place = place -1
myList[place + 1] = key

#output the sorted array


print(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

For index = lowerBound + 1 To upperBound


myKey = myList(index)
place = index - 1
If myList(place) > myKey Then
Do While (place >= lowerBound) And myList(place) > myKey
temp = myList(place + 1)
myList(place + 1) = myList(place)
myList(place) = temp
place = place - 1
Loop
myList(place + 1) = myKey
End If
Next

'output the sorted array


For index = 0 To myList.Length - 1
Console.Write(myList(index) & " ")
Next

Console.ReadKey() 'wait for keypress

End Sub

End Module

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
public class ACTIVITY19D {

public static void main(String args[]) {


int myList[] = {4, 46, 43, 27, 57, 41, 45, 21, 14};

int upperBound = myList.length;


int lowerBound = 0;

for (int index = lowerBound; index < upperBound; index++) {


int myKey = myList[index];

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;
}

// output the sorted array


System.out.println(java.util.Arrays.toString(myList));
}

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Sub push(ByVal item)


If topPointer < stackFull - 1 Then
topPointer = topPointer + 1
Stack(topPointer) = item
Else
Console.WriteLine("Stack is full, cannot push")
End If
End Sub
End Module

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

static void push(int item)


{
if (topPointer < stackFull - 1)
{
topPointer = topPointer + 1;
stack[topPointer] = item;
}
else
System.out.println("Stack is full, cannot push");
}

static void pop()


{
if (topPointer == basePointer - 1)
System.out.println("Stack is empty,cannot pop");
else
{
item = stack[topPointer];
topPointer = topPointer - 1;
}
}

public static void main(String args[])


{
push(7);
push(32);
pop();
System.out.println(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);

}
}

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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)

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Public Dim frontPointer As Integer = 0


Public Dim rearPointer As Integer = -1
Public Const queueFull As Integer = 10
Public Dim queueLength As Integer = 0
Public Dim item As Integer

Public Dim queue() As Integer = {Nothing, Nothing, Nothing,


Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}

Public Sub Main()

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;

static void enQueue(int item)


{
if (queueLength < queueFull)
{
if (rearPointer < queue.length - 1)
rearPointer = rearPointer + 1;
else
rearPointer = 0;
queueLength = queueLength + 1;
queue[rearPointer] = item;
}
else
System.out.println("Queue is full, cannot enqueue");
}

static void deQueue()


{
if (queueLength == 0)
Cambridge International AS & A Level Computer Science 14
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

System.out.println("Queue is empty,cannot dequeue");


else
{
item = queue[frontPointer];
if (frontPointer == queue.length - 1)
frontPointer = 0;
else
frontPointer = frontPointer + 1;
queueLength = queueLength - 1;
}
}

public static void main(String args[])


{
enQueue(7);
enQueue(32);
deQueue();
System.out.println(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);

}
}

Cambridge International AS & A Level Computer Science 15


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 19G, 19H and 19I


Python
#Python program for finding an item in a linked list

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

Cambridge International AS & A Level Computer Science 16


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

#enter item to delete


item = int(input("Please enter item to delete from list "))
delete(item)
print(myLinkedList)
print(myLinkedListPointers)

#enter item to add


item = int(input("Please enter item to add to list "))
insert(item)
print(myLinkedList)
print(myLinkedListPointers)

#enter item to search for


item = int(input("Please enter item to be found "))
result = find(item)
if result != -1:
print("Item found")
else:
print("Item not found")

VB
'VB program for a linked list
Module Module1

Public Dim heapStartPointer As Integer = 5


Public Dim startPointer As Integer = 4
Public Const nullPointer As Integer = -1
Public Dim item As Integer
Public Dim index As Integer
Public Dim itemPointer As Integer
Public Dim result As Integer

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}

Public Sub Main()

'enter item to delete


Console.Write("Please enter item to remove from list ")
item = Integer.Parse(Console.ReadLine())
delete(item)
For index = 0 To myLinkedList.Length - 1
Console.Write(myLinkedList(index) & " ")
Next
Console.WriteLine()
For index = 0 To myLinkedListPointers.Length - 1
Console.Write(myLinkedListPointers(index) & " ")
Next
Console.WriteLine()

Cambridge International AS & A Level Computer Science 17


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

'enter item to insert


Console.Write("Please enter item to add to list ")
item = Integer.Parse(Console.ReadLine())
insert(item)
For index = 0 To myLinkedList.Length - 1
Console.Write(myLinkedList(index) & " ")
Next

For index = 0 To myLinkedListPointers.Length - 1


Console.Write(myLinkedListPointers(index) & " ")
Next

'enter item to search for


Console.Write("Please enter item to be found ")
item = Integer.Parse(Console.ReadLine())
result = find(item)

If result <> -1 Then


Console.WriteLine("Item found")
Else
Console.WriteLine("Item not found")
End If
Console.ReadKey()
End Sub

Sub insert (ByVal itemAdd)


Dim tempPointer As Integer
If heapStartPointer = nullPointer Then
Console.WriteLine("Linked List full")
Else
tempPointer = startPointer
startPointer = heapStartPointer
myLinkedList(startPointer) = itemAdd
myLinkedListPointers(startPointer) = tempPointer

End if
End Sub

Sub delete (ByVal itemDelete)


Dim tempPointer, index, oldIndex As Integer
If startPointer = nullPointer Then
Console.WriteLine("Linked List empty")
Else
index = startPointer
While myLinkedList(index) <> itemDelete And index <> nullPointer
Console.WriteLine( myLinkedList(index) & " " & index)
Console.ReadKey()
oldIndex = index
index = myLinkedListPointers(index)
End While

if index = nullPointer Then


Console.WriteLine("Item " & itemDelete & " not found")
Else
Cambridge International AS & A Level Computer Science 18
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

myLinkedList(index) = nothing
tempPointer = myLinkedListPointers(index)
myLinkedListPointers(index) = heapStartPointer
heapStartPointer = index
myLinkedListPointers(oldIndex) = tempPointer
End if

End If
End Sub

Function find(ByVal itemSearch As Integer) As Integer


Dim found As Boolean = False
itemPointer = startPointer
While (itemPointer <> nullPointer) And Not found
If itemSearch = myLinkedList(itemPointer) Then
found = True
Else
itemPointer = myLinkedListPointers(itemPointer)
End if
End While
Return itemPointer
End Function

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;

static void delete(int itemDelete)


{
int oldIndex = -1;

if (startPointer == nullPointer)
System.out.println("Linked List is empty");
else
{

int index = startPointer;


while (myLinkedList[index] != itemDelete && index != nullPointer)
{
oldIndex = index;
index = myLinkedListPointers[index];
}
if (index == nullPointer)
System.out.println("Item " + itemDelete + " not found");
else

Cambridge International AS & A Level Computer Science 19


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

{
myLinkedList[index] = 0;
int tempPointer = myLinkedListPointers[index];
myLinkedListPointers[index] = heapStartPointer;
heapStartPointer = index;
myLinkedListPointers[oldIndex] = tempPointer;
}
}
}

static void insert(int itemAdd)


{
if (heapStartPointer == nullPointer)
{
System.out.println("Linked List is full");
}
else
{
int tempPointer = startPointer;
startPointer = heapStartPointer;
heapStartPointer = myLinkedListPointers[heapStartPointer];
myLinkedList[startPointer] = itemAdd;
myLinkedListPointers[startPointer] = tempPointer;
}
}

static int find(int itemSearch)


{
boolean found = false;
int itemPointer = startPointer;
do
{
if (itemSearch == myLinkedList[itemPointer])
{
found = true;
}
else
{
itemPointer = myLinkedListPointers[itemPointer];
}
}
while ((itemPointer != nullPointer) && !found);
return itemPointer;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);

System.out.println("Please enter item to remove from list ");


int item = input.nextInt();
delete(item);

for (int index = 0; index < myLinkedList.length; index++)


System.out.print(myLinkedList[index] + " ");
System.out.println();

for (int index = 0; index < myLinkedListPointers.length; index++)


System.out.print(myLinkedListPointers[index] + " ");

Cambridge International AS & A Level Computer Science 20


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

System.out.println();

System.out.println("Please enter item to add to list ");


item = input.nextInt();
insert(item);

for (int index = 0; index < myLinkedList.length; index++)


System.out.print(myLinkedList[index] + " ");
System.out.println();

for (int index = 0; index < myLinkedListPointers.length; index++)


System.out.print(myLinkedListPointers[index] + " ");
System.out.println();

System.out.println("Please enter item to be found ");


item = input.nextInt();

int result = find(item);

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

Cambridge International AS & A Level Computer Science 21


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

The linked list, myLinkedList will now be as shown below.

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

Cambridge International AS & A Level Computer Science 22


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 19L
rootPointer itemPointer itemSearch
0 0 55
2
3
5
8

rootPointer itemPointer itemSearch


0 0 75
2
3
5
-1

Activity 19M
leftBranch nextFreePointer itemAddPointer rootPointer itemAdd itemPointer oldPointer
10 10 0 25 0 0
11
TRUE 1 1
FALSE 6 6
FALSE −1

myTree item leftPointer rightPointer

[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

Cambridge International AS & A Level Computer Science 23


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

// initialise linked list


DECLARE myLinkedList : ARRAY [0:29] of linkedList
DECLARE heapStartPointer : INTEGER
DECLARE startPointer : INTEGER
DECLARE index : INTEGER
DECLARE nameToAdd : STRING
heapStartPointer  0
startPointer  -1 // list empty
FOR index  0 TO 28
myLinkedList[index].pointer  index
NEXT index
myLinkedList[29].pointer  -1

// add item to linked list


IF heapStartPointer = -1
THEN
OUTPUT "List Full"
ELSE
OUTPUT "Name to add"
INPUT nameToAdd
myLinkedList[heapStartPointer].name  nameToAdd
myLinkedList[heapStartPointer].pointer  startPointer
startPointer  heapStartPointer
heapStartPointer  myLinkedList[heapStartPointer].pointer
ENDIF

REPEAT
index  startPointer
OUTPUT myLinkedList[index].name
Index  myLinkedList[index].pointer
UNTIL index = -1

Cambridge International AS & A Level Computer Science 24


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 25


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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>();

// using put method


studentdict.put("Leon", 27);
studentdict.put("Ahmad", 78);
studentdict.put("Susie", 64);

System.out.println(studentdict);

// find value at key "Ahmad"


System.out.println(studentdict.get("Ahmad"));

// remove value at key "Ahmad"


studentdict.remove("Ahmad");
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

DECLARE myDictionary : linkedList


DECLARE heapStartPointer : INTEGER
DECLARE startPointer : INTEGER
DECLARE index : INTEGER

Cambridge International AS & A Level Computer Science 26


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 27


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
// Java program recursive factorial function
public class Factorial {

public static void main(String[] args) {


System.out.println(factorial(0));
System.out.println(factorial(5));
}
public static int factorial(int number)
{
int answer;
if (number == 0)
answer = 1;
else
answer = number * factorial(number - 1);
return answer;
}
}
Call number Function call number answer RETURN

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

1 continued factorial(5) 5 5 * 4 * 3 * 2 120

Activity 19T
1 Recursion – see 19.2.1
2 Use of stack for recursive procedures – see 19.2.2

Cambridge International AS & A Level Computer Science 28


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Call number Function call number answer RETURN

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

End of chapter questions


1 a) i)
FOR ThisPointer ← 2 TO 10
// use a temporary variable to store item which is
to // be inserted into its correct location
Temp ← NameList[ThisPointer]
Pointer ← ThisPointer – 1
WHILE (NameList[Pointer] > Temp) AND Pointer > 0
// move list item to next location
NameList[Pointer + 1] ← NameList[Pointer]
Pointer ← Pointer - 1
ENDWHILE
// insert value of Temp in correct location
NameList[Pointer] ← Temp
ENDFOR

Cambridge International AS & A Level Computer Science 29


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 30


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 31


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 32


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science

Chapter 20 Student Book Answers


20.1 What you should already know
1 Absolute/Immediate – uses the operand
Direct – uses the contents of the memory location specified by the operand
Indirect – uses the contents of the contents of the memory location specified by the operand
Indexed – uses the value found at the memory location specified by adding operand to the contents
of the index register
2 LDM #7
ADD #5
3 a) A function has a type and always returns a value.
b) Parameters are values/references included in a call to a procedure or function. Parameters can
be passed by reference (value of variable used can be changed by the procedure/function) or
by value (no change can be made).
c) A procedure definition is made once but the code specified can be used many times in a
program, every time the procedure is called.
4 See answer to Activity 11G

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

Cambridge International AS & A Level Computer Science 1


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 2


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Pseudocode – with procedures and functions


DECLARE base, height, radius : INTEGER
DECLARE area : REAL

FUNCTION square (side : INTEGER) RETURNS REAL


RETURN side * side
ENDFUNCTION

FUNCTION rectangle (side : INTEGER, otherSide) RETURNS REAL


RETURN side * otherSide
ENDFUNCTION

FUNCTION triangle (triBase : INTEGER, triHeight) RETURNS REAL


RETURN triBase * triHeight / 2
ENDFUNCTION

FUNCTION parallelogram (parBase : INTEGER, parHeight) RETURNS


REAL
RETURN parBase * parBase
ENDFUNCTION

FUNCTION circle(circRad : INTEGER) RETURNS REAL


DECLARE CONSTANT Pi = 3.142
RETURN circRad * circRad * Pi
ENDFUNCTION

PROCEDURE printArea (shapeName : String : areaToPrint : REAL)


OUTPUT "Area of ", shapeName, " is ", areaToPrint
ENDPROCEDURE

OUTPUT "Please enter base, height and radius"


INPUT base, height, radius
area = square(base)
printArea ("square", area)

area = rectangle(base, height)


printArea ("rectangle", area)

area = triangle(base, height)


printArea ("triangle", area)

Cambridge International AS & A Level Computer Science 3


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

area = parallelogram(base, height)


printArea ("parallelogram", area)

area = circle(radius)
printArea ("circle", area)

Python – without procedures and functions


#areas iterative program
Pi = 3.142

base = int(input ("Please enter base "))


height = int(input ("Please enter height "))
radius = int(input ("Please enter radius "))

area = base * base


print ("Area of square is ", area)

area = base * height


print ("Area of rectangle is ", area)

area = base * height / 2


print ("Area of triangle is ", area)

area = base * height


print ("Area of parallelogram is ", area)

area = radius * radius * Pi


print ("Area of rectangle is ", area)

Cambridge International AS & A Level Computer Science 4


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Python – with procedures and functions


#areas using prodedures and functions

def square(side):
return side * side

def rectangle(side, otherSide):


return side * otherSide

def triangle(triBase, triHeight):


return triBase * triHeight / 2

def parallelogram(parBase, parHeight):


return parBase * parHeight

def circle(circRad):
Pi = 3.142
return circRad * circRad * Pi

def printArea (shapeName, areaToPrint):


print ("Area of ", shapeName, " is ", areaToPrint)

base = int(input ("Please enter base "))


height = int(input ("Please enter height "))
radius = int(input ("Please enter radius "))

area = square(base)
printArea ("square", area)

area = rectangle(base, height)


printArea ("rectangle", area)

area = triangle(base, height)


printArea ("triangle", area)

area = parallelogram(base, height)


printArea ("parallelogram", area)

area = circle(radius)
printArea ("circle", area)

Cambridge International AS & A Level Computer Science 5


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB – without procedures and functions


' areas imperative program
Module Module1
Public Sub Main()
Dim base, height, radius As Integer
Dim area As Decimal
Const Pi As Decimal = 3.14

Console.Write("Please enter base ")


base = Integer.Parse(Console.ReadLine())
Console.Write("Please enter height ")
height = Integer.Parse(Console.ReadLine())
Console.Write("Please enter radius ")
radius = Integer.Parse(Console.ReadLine())
area = base * base
Console.WriteLine("Area of a square is " & area)
area = base * height
Console.WriteLine("Area of a rectangle is " & area)
area = base * height / 2
Console.WriteLine("Area of a triangle is " & area)
area = base * height
Console.WriteLine("Area of a parallelogram is " & area)
area = radius * radius * Pi
Console.WriteLine("Area of circle is " & area)

Console.ReadKey()

End Sub

End Module

Cambridge International AS & A Level Computer Science 6


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB – with procedures and functions


'areas program with functions
Module Module1
Public Sub Main()
Dim base, height, radius As Integer
Dim area As Decimal
Const Pi As Decimal = 3.14

Console.Write("Please enter base ")


base = Integer.Parse(Console.ReadLine())
Console.Write("Please enter height ")
height = Integer.Parse(Console.ReadLine())
Console.Write("Please enter radius ")
radius = Integer.Parse(Console.ReadLine())
area = square(base)
printArea("square", area)
area = rectangle(base, height)
printArea("rectangle", area)
area = triangle(base, height)
printArea("trangle", area)
area = parallelogram(base, height)
printArea("parallelogram", area)
area = circle(radius)
printArea("circle", area)

Console.ReadKey()

End Sub

Function square(side As Integer) As Decimal


Return side * side
End Function

Function rectangle(side As Integer, otherSide As Integer) As Decimal


Return side * otherSide
End Function

Function triangle(triBase As Integer, triHeight As Integer) As


Decimal
Return triBase * triHeight / 2
End Function

Function parallelogram(parBase As Integer, parHeight As Integer) As


Decimal
Return parBase * parHeight
End Function

Function circle(radius As Integer) As Decimal


Const Pi As Decimal = 3.14
Return radius * radius * Pi
End Function

Sub printArea(ByVal shapeName As String, ByVal areaToPrint As


Decimal)
Console.WriteLine("Area of a " & shapeName & " is " &
areaToPrint)
End Sub
End Module

Cambridge International AS & A Level Computer Science 7


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java – without procedures and functions


import java.util.Scanner;
class ACTIVITY20B
{
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);
final double PI = 3.142;
double base, height, radius, area;
System.out.println("Please enter base ");
base = myObj.nextDouble();
System.out.println("Please enter height ");
height = myObj.nextDouble();
System.out.println("Please enter radius ");
radius = myObj.nextDouble();

area = base * base;


System.out.println("Area of a square is " + area);
area = base * height;
System.out.println("Area of a rectangle is " + area);
area = base * height / 2;
System.out.println("Area of a triangle is " + area);
area = base * height;
System.out.println("Area of a parallelogram is " + area);
area = PI * radius * radius;
System.out.println("Area of a circle is " + area);

}
}

Java – with procedures and functions


import java.util.Scanner;
class ACTIVITY20Bfunction
{
static void printArea (String shapeName, double areaToPrint)
{
System.out.println("Area of a " + shapeName + " is " +
areaToPrint);
}
static double square(double side)
{
return side * side;
}

static double rectangle(double side, double otherSide)


{
return side * otherSide;
}

Cambridge International AS & A Level Computer Science 8


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

static double triangle(double triBase, double triHeight)


{
return triBase * triHeight / 2;
}

static double parallelogram(double parBase, double parHeight)


{
return parBase * parHeight;
}

static double circle(double radius)


{
final double PI = 3.142;
return radius * radius * PI;
}
public static void main(String args[])
{
Scanner myObj = new Scanner(System.in);

double base, height, radius, area;


System.out.println("Please enter base ");
base = myObj.nextDouble();
System.out.println("Please enter height ");
height = myObj.nextDouble();
System.out.println("Please enter radius ");
radius = myObj.nextDouble();

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

}
}

Cambridge International AS & A Level Computer Science 9


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 = student("Mary Wu", 12/10/2012, 67)

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

Public Sub displayExamMark()


Console.WriteLine("Student Name " & name)
Console.WriteLine("Exam Mark " & examMark)
Console.ReadKey()
End Sub
End Class

End Module

Cambridge International AS & A Level Computer Science 10


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

student(String n, LocalDate d, int e){


name = n;
dateOfBirth = d;
examMark = e;
}
public void displayExamMark (){
System.out.println("Student Name " + name);
System.out.println("ExamMark " + examMark);
}
}
public class ATIVITY20C{
public static void main(String[] args) {
student myStudent = new student("Mary Wu", LocalDate.parse("2012-12-
10"), 67);
myStudent.displayExamMark();

}
}

Cambridge International AS & A Level Computer Science 11


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

myFullTimeStudent = fullTimeStudent("Mary Wu", 12/10/2012, 67)


myFullTimeStudent.displayExamMark()
myPartTimeStudent = partTimeStudent("Janet Yo", 23/5/2012, 95)
myPartTimeStudent.displayExamMark()

Cambridge International AS & A Level Computer Science 12


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Public Sub displayExamMark()


Console.WriteLine("Student Name " & name)
Console.WriteLine("Exam Mark " & examMark)
End Sub
End Class

Class partTimeStudent : Inherits student


Private ReadOnly fullTimeStudent = False

Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As Integer)


MyBase.New(n, d, e)
End Sub

End Class

Class fullTimeStudent : Inherits student


Private ReadOnly fullTimeStudent = True

Public Sub New(ByVal n As String, ByVal d As Date, ByVal e As Integer)


MyBase.New(n, d, e)
End Sub

End Class

End Module

Cambridge International AS & A Level Computer Science 13


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

student(String n, LocalDate d, int e){


name = n;
dateOfBirth = d;
examMark = e;
}
public void displayExamMark (){
System.out.println("Student Name " + name);
System.out.println("ExamMark " + examMark);
}
}

class partTimeStudent extends student {


private boolean fullTimeStudent = false;
partTimeStudent (String n, LocalDate d, int e){
super (n, d, e);
}
}

class fullTimeStudent extends student {


private boolean fullTimeStudent = true;
fullTimeStudent (String n, LocalDate d, int e){
super (n, d, e);
}
}

public class ATIVITY20D{


public static void main(String[] args) {
student myFullTimeStudent = new fullTimeStudent("Mary Wu", LocalDate.parse("2012-12-10"), 67);
myFullTimeStudent.displayExamMark();
student myPartTimeStudent = new partTimeStudent("Janet Yo", LocalDate.parse("2012-07-05"), 95);
myPartTimeStudent.displayExamMark();

}
}

Cambridge International AS & A Level Computer Science 14


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

def area (self):


self.__areaValue = self.__side * self.__side
print("Area ", self.__areaValue)

class rectangle(shape):
def __init__(self, length, breadth):
shape.__init__(self)
self.__length = length
self.__breadth = breadth

def area (self):


self.__areaValue = self.__length * self.__breadth
print("Area ", self.__areaValue)

class circle(shape):
def __init__(self, radius):
shape.__init__(self)
self.__radius = radius

def area (self):


self.__areaValue = self.__radius * self.__radius * 3.142
print("Area ", self.__areaValue)

mySquare = square(10)
mySquare.area()

myCircle = circle(20)
myCircle.area()

myRectangle = rectangle (10,17)


myRectangle.area()

Cambridge International AS & A Level Computer Science 15


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Overridable Sub area()


Console.WriteLine("Area " & areaValue)
End Sub
End Class

Class square : Inherits shape


Private side As Decimal

Public Sub New(ByVal s As Decimal)


side = s
End Sub
Overrides Sub Area()
areaValue = side * side
Console.WriteLine("Area " & areaValue)
End Sub
End Class

Class rectangle : Inherits shape


Private length As Decimal
Private breadth As Decimal

Public Sub New(ByVal l As Decimal, ByVal b As Decimal)


length = l
breadth = b
End Sub

Overrides Sub Area()


areaValue = length * breadth
Console.WriteLine("Area " & areaValue)
End Sub

End Class

Class circle : Inherits shape


Private radius As Decimal

Public Sub New(ByVal r As Decimal)


radius = r
End Sub

Overrides Sub Area()


areaValue = radius * radius * 3.142
Console.WriteLine("Area " & areaValue)
End Sub
End Class

End Module

Cambridge International AS & A Level Computer Science 16


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
// ACTIVITY20E polymorphism

class shape {
protected double areaValue;

public void area (){


System.out.println("Area " + areaValue);
}
}

class square extends shape {


private double side;

square (double s){


side = s;
}
public void area (){
areaValue = side * side;
System.out.println("Area " + areaValue);
}
}

class rectangle extends shape {


private double length;
private double breadth;

rectangle(double l, double b){


length = l;
breadth = b;
}
public void area (){
areaValue = length * breadth;
System.out.println("Area " + areaValue);
}
}
class circle extends shape {
private double radius;

circle (double r){


radius = r;
}
public void area (){
areaValue = radius * radius * 3.142;
System.out.println("Area " + areaValue);
}
}
public class ACTIVITY20E{
public static void main(String[] args) {
square mySquare = new square(20);
mySquare.area();
circle myCircle = new circle(20);
myCircle.area();
rectangle myRectagle = new rectangle(10, 17);
myRectagle.area();

}
}

Cambridge International AS & A Level Computer Science 17


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 20F
Python
#ACTIVITY 20F overloading
class greeting:

def hello(self, firstName = None,lastName = None):

if firstName is not None and lastName is not None:


print ("Hello " + firstName + " " + lastName)
elif firstName is not None:
print ("Hello " + firstName)
else:
print ("Hello")

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

Public Overloads Sub hello()


Console.WriteLine("Hello")
End Sub

Public Overloads Sub hello(ByVal name As String)


Console.WriteLine("Hello " & name)
End Sub

Public Overloads Sub hello(ByVal firstName As String, ByVal


lastName As String)
Console.WriteLine("Hello " & firstName & " " & lastName)
End Sub
End Class

End Module

Cambridge International AS & A Level Computer Science 18


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Java
//ACTIVITY 20F overloading

class greeting{
public void hello(){
System.out.println("Hello");
}

public void hello(String name){


System.out.println("Hello " + name);
}

public void hello(String firstName, String secondName){


System.out.println("Hello " + firstName + " " + secondName);
}
}

class ACTIVITY20F{
public static void main(String[] args){
greeting myGreeting = new greeting();
myGreeting.hello();
myGreeting.hello("Christopher");
myGreeting.hello("Christopher","Robin");
}
}

Cambridge International AS & A Level Computer Science 19


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 20


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 20H
Sample Answer in Python
#ACTIVITY20H
class Node:

def __init__(self, item):

self.leftPointer = None
self.rightPointer = None
self.item = item

def insert(self, item):


# Compare the new item with the parent node
if self.item:
if item < self.item:
if self.leftPointer is None:
self.leftPointer = Node(item)
else:
self.leftPointer.insert(item)
elif item > self.item:
if self.rightPointer is None:
self.rightPointer = Node(item)
else:
self.rightPointer.insert(item)
else:
self.item = item

def search(self, item):


while self.item != item:
if item < self.item:
self.item = self.leftPointer
else:
self.item = self.rightPointer
if self.item is None:
return None
return self.item

# Print the tree in order


def PrintInOrder(self):
if self.leftPointer:
self.leftPointer.PrintInOrder()
print( self.item)
if self.rightPointer:
self.rightPointer.PrintInOrder()

# Preorder traversal
def PreorderTraversal(self, tree):

Cambridge International AS & A Level Computer Science 21


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

result = []
if tree:
result.append(tree.item)
result = result +
self.PreorderTraversal(tree.leftPointer)
result = result +
self.PreorderTraversal(tree.rightPointer)
return result

# set up the root node


tree = Node(27)

# Use the insert method to add nodes to


tree.insert(19)
tree.insert(36)
tree.insert(42)
tree.insert(16)

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

Cambridge International AS & A Level Computer Science 22


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

def rectangle(side, otherSide):


return side * otherSide
:
:
def printArea (shapeName, areaToPrint):
print ("Area of ", shapeName, " is ", areaToPrint)

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

def area (self):


self.__areaValue = self.__side * self.__side
print("Area ", self.__areaValue)

Cambridge International AS & A Level Computer Science 23


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

3 a) language(java,highLevel).
language(java,oop).
b) i) fortran
cobol
visualBasic
visualBasic
python
python
ii) false
c) translator(assembler,X).

20.2 What you should already know


1

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"

print ("Name ", myStudent.name)


print ("Address ", myStudent.address)
print ("Class ", myStudent.className)

studentFile.write(myStudent.name + " " + myStudent.address + " " +


myStudent.className + "\n")
studentFile.close()

studentFile = open('student.TXT','r')
print (studentFile.read()) #print all the records in a file
studentFile.close()

#append another record


studentFile = open('student.TXT','a')

myStudent = TStudentRecord()
myStudent.name = "Frank Yang"
myStudent.address = "My bungalow"
myStudent.className ="5X"

print ("Name ", myStudent.name)


print ("Address ", myStudent.address)
print ("Class ", myStudent.className)

studentFile.write(myStudent.name + " " + myStudent.address + " " +


myStudent.className + "\n")
Cambridge International AS & A Level Computer Science 24
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

while recordRead != '':


if (recordRead != "Frank Yang" + " " + "My bungalow" + " " + "5X" + "\n"
):
newStudentFile.write(recordRead)
recordRead = studentFile.readline()

studentFile.close()
newStudentFile.close()

newStudentFile = open('newStudent.TXT', 'r')


print (newStudentFile.read())
newStudentFile.close()
os.remove('student.TXT')
os.rename('newStudent.TXT','student.TXT')

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

myStudent.name = "Ahmad Sayed"


myStudent.address = "My House"
myStudent.className = "5X"
Console.WriteLine("Name " + myStudent.name)
Console.WriteLine("Address " + myStudent.address)
Console.WriteLine("Class " + myStudent.className)
recordWrite = myStudent.name + " " + myStudent.address + " " +
myStudent.className
studentFileWrite.WriteLine(recordWrite)
studentFileWrite.Close()

studentFileRead = New StreamReader("student.txt")


Do
recordRead = studentFileRead.ReadLine
Console.WriteLine(recordRead)
Loop Until recordRead Is Nothing

studentFileRead.Close()

'append another record


myStudent.name = "Frank Yang"
myStudent.address = "My bungalow"
Cambridge International AS & A Level Computer Science 25
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 = New StreamReader("student.txt")


Do
recordRead = studentFileRead.ReadLine
Console.WriteLine(recordRead)
Loop Until recordRead Is Nothing

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

studentFileRead = New StreamReader("newStudent.txt")


Do
recordRead = studentFileRead.ReadLine
Console.WriteLine(recordRead)
Loop Until recordRead Is Nothing
studentFileRead.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

Cambridge International AS & A Level Computer Science 26


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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;

public void TstudentRecord() {


name = "";
address = "";
className ="";
}
}

public static void main(String args[]){


TStudentRecord myStudentRecord = new TStudentRecord();
myStudentRecord.name = "Ahmad Sayed";
myStudentRecord.address = "My House";
myStudentRecord.className = "5X";

System.out.println("Name " + myStudentRecord.name);


System.out.println("Address " + myStudentRecord.address);
System.out.println("Class " + myStudentRecord.className);

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

System.out.println("Name " + myStudentRecord.name);


System.out.println("Address " + myStudentRecord.address);
System.out.println("Class " + myStudentRecord.className);

studentFileWrite = myStudentRecord.name + " " + myStudentRecord.address + "


" + myStudentRecord.className;
try {
FileWriter studentFileWriter = new FileWriter("student.txt", true);
PrintWriter studentWriter = new PrintWriter(studentFileWriter);
studentWriter.printf(studentFileWrite + "\n");
studentFileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
Cambridge International AS & A Level Computer Science 27
© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

FileReader studentFileReader = new FileReader("student.txt");


BufferedReader studentReader = new
BufferedReader(studentFileReader);
String studentFileRead;
while ((studentFileRead = studentReader.readLine()) != null) {
System.out.println(studentFileRead);
}
studentFileReader.close();
} catch (IOException e) {
e.printStackTrace();
}

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;

while ((studentFileRead = studentReader.readLine()) != null) {


if (!(studentFileRead.equals("Frank Yang My Bungalow 5X")) ){
studentWriter.printf(studentFileRead + "\n");
}
}
studentFileReader.close();
studentFileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileReader studentFileReader = new
FileReader("newStudent.txt");
BufferedReader studentReader = new
BufferedReader(studentFileReader);
String studentFileRead;

while ((studentFileRead = studentReader.readLine()) != null) {


System.out.println(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.

Cambridge International AS & A Level Computer Science 28


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

print("Please enter student details")


studentRecord.name = input("Please enter student name ")
studentRecord.registerNumber = int(input("Please enter student's
register number "))
year = int(input("Please enter student's year of birth YYYY "))
month = int(input("Please enter student's month of birth MM "))
day = int(input("Please enter student's day of birth DD "))
studentRecord.dateOfBirth = datetime.datetime(year, month, day)
studentRecord.fullTime = bool(input("Please enter True for full-time or
False for part-time "))
pickle.dump (studentRecord, studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)

studentFile.close()

studentFile = open('students.DAT','rb')

studentRecord = pickle.load(studentFile)

print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)

studentFile.close()

Cambridge International AS & A Level Computer Science 29


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

VB
' ACTIVITY 20L
Option Explicit On
Imports System.IO
Module Module1

Public Sub Main()


Dim studentFileWriter As BinaryWriter
Dim studentFileReader As BinaryReader
Dim studentFile As FileStream

Dim year, month, day As Integer


Dim studentRecord As New student()

studentFile = New FileStream("studentFile.DAT",


FileMode.Create)
studentFileWriter = New BinaryWriter(studentFile)

Console.Write("Please enter student name ")


studentRecord.name = Console.ReadLine()
Console.Write("Please enter student's register number ")
studentRecord.registerNumber =
Integer.Parse(Console.ReadLine())
Console.Write("Please enter student's year of birth YYYY ")
year =Integer.Parse(Console.ReadLine())
Console.Write("Please enter student's month of birth MM ")
month =Integer.Parse(Console.ReadLine())
Console.Write("Please enter student's day of birth DD ")
day =Integer.Parse(Console.ReadLine())
studentRecord.dateOfBirth = DateSerial(year, month, day)
Console.Write("Please enter True for full-time or False for
part-time ")
studentRecord.fullTime = Boolean.Parse(Console.ReadLine())

studentFileWriter.Write(studentRecord.name)
studentFileWriter.Write(studentRecord.registerNumber)
studentFileWriter.Write(studentRecord.dateOfBirth)
studentFileWriter.Write(studentRecord.fullTime)

studentFileWriter.Close()
studentFile.Close()

studentFile = New FileStream("studentFile.DAT", FileMode.Open)


studentFileReader = New BinaryReader(studentFile)

studentRecord.name = studentFileReader.ReadString()
studentRecord.registerNumber = studentFileReader.ReadInt32()
studentRecord.dateOfBirth = studentFileReader.ReadString()
studentRecord.fullTime = studentFileReader.ReadBoolean()

studentFileReader.Close()
studentFile.Close()

Cambridge International AS & A Level Computer Science 30


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Console.WriteLine (studentRecord.name & " " &


studentRecord.registerNumber & " " & studentRecord.dateOfBirth & " " &
studentRecord.fullTime)
Console.ReadKey ()

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;

student( String n, int r, boolean f){


name = n;
registerNumber = r;
fullTime = f;
}
public void showDetails(){
System.out.println(name + " " + registerNumber + " " + fullTime
);
}
}

public class ACTIVITY20L {


public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

String nameIn;
int registerNumberIn;
boolean fullTimeIn;

System.out.println("Please student details");


System.out.println("Please student name ");
nameIn = myObj.next();
System.out.println("Please student's register number ");
registerNumberIn = myObj.nextInt();

Cambridge International AS & A Level Computer Science 31


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

System.out.println("Please enter true for full-time or false


for part-time ");
fullTimeIn = myObj.nextBoolean();

student studentRecord = new student(nameIn, registerNumberIn,


fullTimeIn);
studentRecord.showDetails();
String registerNumberAsString =
Integer.toString(registerNumberIn);
String fullTimeAsString = Boolean.toString(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();
}
}

Cambridge International AS & A Level Computer Science 32


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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 = open('students.DAT','ab') # a for append

print("Please enter student details")


studentRecord.name = input("Please enter student name ")
studentRecord.registerNumber = int(input("Please enter student's
register number "))
year = int(input("Please enter student's year of birth YYYY "))
month = int(input("Please enter student's month of birth MM "))
day = int(input("Please enter student's day of birth DD "))
studentRecord.dateOfBirth = datetime.datetime(year, month, day)
studentRecord.fullTime = bool(input("Please enter True for full-time or
False for part-time "))
pickle.dump (studentRecord, studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)

studentFile.close()

studentFile = open('students.DAT','rb')

studentRecord = pickle.load(studentFile)

print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth, studentRecord.fullTime)

studentFile.close()

Cambridge International AS & A Level Computer Science 33


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

Activity 20N
Python
#ACTIVITY 20N
try:
value = int(input('Please enter an integer value '))

except:
print('Not an integer')

VB
'ACTIVITY 20N
Module Module1

Public Sub Main()


Dim value As Integer
Try
Console.Write("Please input an integer value ")
value = Integer.Parse(Console.ReadLine())
Catch e As System.FormatException
Console.WriteLine("Not an integer")
End Try
Console.ReadLine()
End Sub

End Module

Java
//ACTIVITY20N
import java.io.*;
import java.util.*;

public class ACTIVITY20N {


public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

try {
System.out.println("Please input an integer value ");
int value = myObj.nextInt();
}

catch (InputMismatchException e) {
System.out.println("Not an integer");
}
}
}

Cambridge International AS & A Level Computer Science 34


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Sample see Java Activity 20L

End of chapter questions


1 a) parent(ali, ahmed).
parent(meena, ahmed).
b) P =
ahmed
aisha
c) mother(M, gina).
d) father(F, C)
IF
male(F) AND parent(F, C).
e) brother(X, Y)
IF
male(X) AND parent(A, X) AND parent(A, Y) AND NOT X=Y.
2 a)

Cambridge International AS & A Level Computer Science 35


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

DateOfBirth : DATETIME

ShowDateOfBirth()

FullTimeStuden PartTimeStudent

NumberOfCourses : INTEGER
TelephoneNumber : STRING
Fee : Currency
FeePaid : BOOLEAN

Constructor()
Constructor()
ShowNumberOf Courses()
ShowTelephoneNumber()
ShowFee()
ShowFeePaid()

Cambridge International AS & A Level Computer Science 36


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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

Cambridge International AS & A Level Computer Science 37


© Helen Williams and David Watson 2020
Cambridge International AS & A Level Computer Science Answers

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.

Cambridge International AS & A Level Computer Science 38


© Helen Williams and David Watson 2020

You might also like