Computer Science For IGCSE Cambridge Course Book 2022
Computer Science For IGCSE Cambridge Course Book 2022
UNIVERSITY PRESS
Computer Science
for Cambridge IGCSE™& O Level
COURSEBOOK
UNIVERSITY PRESS
9 781 08 915144 >
Building Brighter Futures Together
Cambridge
UNIVERSITY PRESS
Computer Science
for Cambridge IGCSE™ & O Level
COURSEBOOK
www.cambridge.org
Information on this title: www.cambridge.org/9781108915144
© Cambridge University Press 2021
This publication is in copyright. Subject to statutory exception
and to the provisions of relevant collective licensing agreements,
no reproduction of any part may take place without the written
permission of Cambridge University Press.
First published 2015
Second edition 2021
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
i -
WINNER
Patricia Abril Stanley Manaay Tiffany Cavanagh Helen Comerford John Nicko Coyoca Meera Rangarajan
New Cambridge School, Salvacion National High School, Trident College Solwezi, Lumen Christi Catholic College, University of San Jose-Recoletos, RBK International Academy,
Colombia Philippines Zambia Australia Philippines India
For more information about our dedicated teachers and their stories, go to
dedicatedteacher.cambridge.org
Brighter Thinking
Ma
■'J "
C ambridge
UNIVERSITY PRESS
Better Learning
> Contents
The items in orange are accessible to teachers for free on 4 Software 78
the supporting resources area of Cambridge GO.
4.1 Types of software 80
How to use this book vi 4.2 Operating system 81
4.3 Interrupts 84
How to use this series viii
4.4 Types of programming language 85
Introduction 1 4.5 Translators 87
4.6 Integrated Development Environment
1 Data representation 8 (IDE) 90
1.1 Binary and hexadecimal 10
1.2 Binary manipulation and negative 5 The internet and its uses 94
numbers 16 5.1 The internet and the world wide web 96
1.3 How do computers represent text, 5.2 Requesting and retrieving web pages 97
images and sound? 21 5.3 The purpose of a web browser 100
1.4 Measuring data storage 25 5.4 Digital currency 105
1.5 Data compression 27 5.5 Cyber security 106
GETTING STARTED
This contains questions and activities on subject knowledge you will need before starting this chapter.
TIPS
Command words that appear in the Cambridge Activities give you an opportunity to check your
Assessment International Education syllabus are understanding throughout the text in a more
highlighted in the exam-style questions when they active way, for example, by creating presentations,
are first introduced, and are accompanied with posters or role plays.
their syllabus definitions in the margins. Not all
command words from the syllabus are included At the end of some activities, you will find
in the exam-style questions, but you will find all opportunities to help you assess your own work, or
command word definitions in the glossary at the that of your classmates, and consider how you can
back of the book. improve the way you learn.
Questions REFLECTION
Appearing throughout the text, questions give you a
These activities ask you to think about the
chance to check that you have understood the topic you
approach that you take to your work, and how
have just read about.
you might improve this in the future.
EXAM-STYLE QUESTIONS
Questions at the end of each chapter provide more demanding exam-style questions, some of which may require
use of knowledge from previous chapters.
SELF-EVALUATION CHECKLIST
The summary checklists are followed by T can’ statements which match the Learning intentions at the beginning
of the chapter. You might find it helpful to rate how confident you are for each of these statements when you are
revising. You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
The digital teacher s resource contains detailed guidance for all topics
of the syllabus, including common misconceptions to elicit the areas
where learners might need extra support, as well as an engaging bank of Computer Science
lesson ideas for each syllabus topic. Differentiation is emphasised with for Cambridge IGCSE"-' & O Level
There are three programming books: one for each of the recommended
languages in the syllabuses - Python, Microsoft Visual Basic and Java.
Each of the books are made up of programming tasks that follow a scaffolded
approach to skills development. This allows learners to gradually progress
through ‘demo’, ‘practice’ and ‘challenge’ tasks to ensure that every learner is
supported. There is also a chapter dedicated to programming scenario tasks
to provide support for this new area of the syllabuses. The digital part of each
book contains a comprehensive solutions chapter, giving step-by-step answers
to the tasks in the book.
/ /
1• /
/ 7 1
«
* j/ « J /
♦ I I /» / 7 /•/;'
7 f
*
1 9 * • I -. 4
4
% I / .
/
*
K
X
\A/u'4? • ' ♦
/ ■/
< ♦.</ /
/
'A> */ *
a f
1 t
Z < F 4 4 4 W 4 4
1 A A to to t
M/}>' #
4 « ‘ A 1 4
'U
».‘*A •a 4 >* > M
’ / //.
____ t ___________ 1 _____
Introduction
o
t EV V:
5
1 *
•fl
Jpt
"C
K
E A*
w
>W
*UI
• CT
* .% •t
b* *”*• .J
*
k
• Jr
tuft • *
Computer
case
Optical
drive
Computer
case fan
Central
processing
unit (CPU)
cooling fan Hard
drive
Central
processing
unit (CPU)
(under
the fan)
Computer case
The computer case is the unit in which all the other components are stored. The case
stops too much dust getting to the computer components, which can harm them and
affect the way that they are able to perform. The size of a case is often dictated by the
size of the motherboard that it will store, as this is one of the larger components within
the computer. Computer cases have been made from all kinds of material such as steel,
aluminium, plastic, wood, glass and even Lego!
A computer case
Introduction
Motherboard
The motherboard (shown in the image below) is a very important component in a
computer. All the other components in the computer plug into the motherboard. The
motherboard allows the components to be connected and to communicate in order to
carry out all the operations. It also allows all the components to receive the power that
comes from the power supply unit. It is a large and very important circuit board. It is
often thought of as the backbone of a computer as it holds all the other components
together.
The motherboard has a special unit in which the CPU is seated. It also has lots of
special slots that components such as the RAM and the graphics card are clipped into.
It has lots of pins around the edges where cables can be plugged into to power the
different components.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CPU
The central processing unit (CPU) is a very important component
within a computer. It is known as the brains of the computer. It is
responsible for the operation of each fetch-decode-execute cycle
that the computer carries out. You will learn a lot more about the
CPU and what it does in Chapter 3. You can find it inserted into
a special unit on the motherboard. It’s a very small component
but has a very big job!
PSU
All the components in a computer need power to operate. They
are all connected to the motherboard to get access to power.
There is one component that powers the motherboard to allow
it to pass power to the other components and this is called
the power supply unit (PSU). PSUs can have different levels
of wattage output. The higher the wattage, the more powerful
the PSU. A standard computer will need a PSU that outputs
approximately 300 to 500 watts. A computer that has lots of high
performance components will need a more powerful PSU to
supply a higher level of power. A PSU like this could output over
1000 watts.
RAM
The random access memory (RAM) is the component that
temporarily stores data in a computer that is waiting to be
processed. RAM is plugged into the motherboard and is available
in different storage sizes. A common size of RAM for a computer
to have is 8 GB of RAM. However, if a computer is a high
performance computer, it will have a lot more data that needs
to be processed each second, so it will need a larger amount of
RAM. A computer like this could have 32GB of RAM. The
amount of RAM a computer has can be upgraded. RAM is
commonly available in sizes of 8 GB. So, another 8 GB card can RAM memory modules
be inserted into a RAM slot on the motherboard to upgrade
the amount of RAM by 8GBs. You will learn more about the
purpose of RAM in Chapter 3.
Introduction
Graphics card
A graphics card is the component in the computer that is
responsible for producing the images that you see on your
computer screen. Some computers have a graphics unit built into
the motherboard, this is called a graphics processing unit (GPU).
However, most GPUs are low performing and not capable of
producing the high quality of graphics seen by most computers
today. Therefore, graphics cards are now more commonly used
in computers to produce the high quality of graphics desired by
many users. The graphics card plugs into a special slot on the
motherboard. Like the CPU, a graphics card is responsible for
processing a lot of data, so it normally has built in fans to keep
it cool and stop it from overheating.
Hard drive
The hard drive is where all the files and software that you use
on your computer are permanently stored. Most computers will
either have a hard disk drive (HDD) or a solid state drive (SSD).
It is common in computers now to have approximately 1 TB of
storage, but earlier computers only had 250-500 GB of data
storage. The demand for an increasing amount of storage space
continues as we store more and more data on our computers.
Some companies have predicted this demand and have started to
encourage users to use cloud storage as a result. You will learn
more about the operation of a HDD and an SSD, and cloud
storage in Chapter 3. A hard drive
Optical drive
The final component is an optical drive. This is the device in
which you insert optical media such as CDs into, to be read
by the computer. Optical drives used to be very common
in computers, but more modern computers are often now
manufactured without them. This is because a lot of content
and data is now digitally shared and the need for using CDs to
share data has decreased as a result.
You now know what is inside a computer case, eagerly working
hard to complete all the actions that you ask of your computer.
You now get to learn some exciting information about computer
An optical drive
science, including how some of those components work on
a more detailed level, and you get to learn how to create the
computer programs that are processed by your computer.
Let’s get started!
> Chapter 1
Data
representation
develop an understanding about how binary is used to represent different forms of data, such as text,
sound and images
learn to convert between the number systems denary, binary and hexadecimal
learn to add two binary numbers and understand what is meant by overflow
learn to perform a binary shift and how this affects the number
GETTING STARTED
Working with a partner, write the words 'text', 'sound' and 'image' on a piece
of paper. Around each word, write words that you can think of that are linked
to each of the three words. For example, you could write the words 'sound
wave' next to the word 'sound'.
If the addresses and values were given as binary, rather than as hexadecimal,
then it would be more difficult to identify if an error has occurred. For
example, it is easier to see if an address contains a valid value, e.g. F2A5,
rather than 1111001010100101.
CONTINUED
Discussion questions
1 Do you think that you have ever seen or used hexadecimal before? If you
have, can you provide an example of where you have seen or used it?
As humans, we process data that is called analogue data. Everything we see, hear, feel analogue data:
and smell is a continuous stream of analogue data to our senses. a continuous
stream of data that
is processed by
Questions humans.
1 Can you think of three examples of analogue data? logic gate: a very
2 Why is analogue data described as continuous data? small component in a
computer system that
controls the flow of
The components that process data in a computer are made up of very small logic gates. electricity.
These gates cannot process analogue data, they can only process digital data. This data
is stored in registers. You can find out more about logic gates in Chapter 10. Digital data digital data: discrete
is discrete data that only has two values, 1 and 0. Any data that we want a computer to data that only uses
process must be converted into digital data. This type of data is also called binary data. the values 0 and 1.
register: a small
component in a
Number systems computer system that
in our daily lives we mostly use a denary number system. This is called a base-10 is used to temporarily
number system and uses the digits 0-9. The units in a denary number system are ones, store data.
tens, hundreds and thousands. Each time the unit increases by the power of 10. denary: a base-10
For example, the denary number 123 has: number system that
uses the values 0-9.
Increases by power of 10 Increases by power of 10
z \ Z \
One hundred Two tens Three ones
1 2 3
Computers use a binary number system. This is called a base-2 number system and
uses the digits 0 and 1. The units in a binary number system increase by the power of 2.
Any denary values need to be converted to binary values so that they can be processed
by a computer.
1 Data representation
The size of a binary number is referred to by the number of bits it has. A 4-bit binary
number will have 4 values that are either l or 0, for example, 1001. An 8-bit binary number
will have 8 values that are also either 1 or 0. Binary values can get very large, some have as
many as 64 bits; now that’s a very big number! You will need to be able to understand binary
numbers that have as many as 16 bits.
First, focus on converting denary numbers to 4-bit binary. To convert denary numbers to
4-bit binary the units that you need to use are 1,2, 4 and 8. You can indicate with a 1 or a 0
whether that unit is required. For example, if you convert the denary number 13 to a 4-bit
binary number you can use the following steps:
Write down the binary units from 8 to 1. An easy way to do this is using a table.
8 4 2 1
Do you notice how the units increase by the power of 2 each time (going from right to left)?
Compare the denary number (13) to the first binary unit (8) to see whether it is equal to or
greater than the denary number. 13 is greater than 8, which means that the unit 8 is required
and you can write a 1 beneath it. 8 can then be subtracted from the denary value, 13-8 = 5.
8 4 2 1
1
Now compare the denary number (5) to the next binary unit (4) to see whether it is equal
to or greater than the denary number. 5 is greater than 4, which means that the unit 4 is
required and you can write a 1 beneath it. 4 can then be subtracted from the denary value,
5-4=1.
8 4 2 1
1 1
Then compare the denary number (1) to the next binary unit (2) to see whether it is equal to
or greater than the denary number. 1 is not greater than 2, which means that the unit 2 is not
required and you can write a 0 beneath it. No subtraction is needed this time as you haven’t
used the unit.
8 4 2 1
1 1 0
Finally, compare the denary number (1) to the last binary unit (1) to see whether it is equal
to or greater than the denary number. 1 is equal to 1, which means that the unit is required
and you can write a 1 beneath it. 1 can then be subtracted from the denary value. 1-1=0.
8 4 2 1
1 1 0 1
11 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
This means that if you convert the denary number 13 to 4-bit binary, you get the
binary number 1101.
Questions
1 What is the largest denary number that can be created with a 4-bit binary
number?
2 Convert the denary number 6 to a 4-bit binary number.
3 Convert the binary number 9 to a 4-bit binary number.
To convert denary numbers to 8-bit binary the units that you need to use are 1,2, 4,
8, 16, 32, 64 and 128. You can indicate, again, with a 1 or a 0 whether that unit is
required. For example, if you convert the denary number 150 to an 8-bit binary
number you can use the same method as before:
Write down the binary units from 128 to 1:
128 64 32 16 8 4 2 1
Compare the denary number (150) to the first binary unit (128) to see whether it is
equal to or greater than the denary number. 150 is greater than 128, which means
that the unit 128 is required and you can write a 1 beneath it. 128 can then be
subtracted from the denary value, 128-150 = 22.
128 64 32 16 8 4 2 1
1
Next, compare the denary number (22) to the next binary unit (64) to see whether it
is equal to or greater than the denary number. 22 is not greater than 64, which means
that the unit 64 is not required and you can write a 0 beneath it. No subtraction is
needed this time as you haven’t used the unit.
128 64 32 16 8 4 2 1
1 0
Then compare the denary number (22) to the next binary unit (32) to see whether it
is equal to or greater than the denary number. 22 is not greater than 32, which means
that the unit 32 is not required and you can write a 0 beneath it. No subtraction is
needed this time as you haven’t used the unit.
128 64 32 16 8 4 2 1
1 0 0
Now, continue this process until you have compared all the binary units. Remember to
subtract the unit from the denary number if it is required. You should end with the
following result:
128 64 32 16 8 4 2 1
1 0 0 1 0 1 1 0
1 Data representation
CONTINUED
This means that if you convert the denary number 150 to 8-bit binary, you get the
binary number 10010110.
A quick check that you can do on your calculation is to look at the last unit on the
right of your binary number. If the denary number you are converting is an odd
number, this number should be 1. If the denary number you are converting is an
even number, this number should be 0.
Questions
4 Convert the denary number 58 to an 8-bit binary number.
5 Convert the denary number 123 to an 8-bit binary number.
If you need to convert a binary number into a denary number, you can use simple
addition. You just need to add together all the units that are represented by the value 1.
Try converting the binary number 1010. A simple way to do this is to use a table.
You can write the units above and the binary number below:
8 4 2 1
1 0 1 0
You just need to add together all the units that have a 1 below. This means the
calculation is 8 + 2= 10. Therefore, if you are converting the binary number 1010 to
denary, you get the denary number 10.
If you need to convert an 8-bit binary number, you need to extend the units so that
you have 8 of them. Remember to increase by the power of 2 each time.
Try converting the binary number 10011001. You can write the values in a table
again to make it clearer:
128 64 32 16 8 4 2 1
1 0 0 1 1 0 0 1
You just need to add together all the units again that have a 1 below. This means the
calculation is 128+ 16 + 8+1 = 153. Therefore, if you are converting the binary
number 100011001 to denary, you get the denary number 153.
Questions
6 What is the largest denary number that can be created with an 8-bit REFLECTION
binary number?
How did you know
7 Convert the 8-bit binary number 01100011 to a denary number.
how to add in the
8 You need to be able to convert up to 16-bit binary values. Fill in the missing correct missing units
units in the table and calculate the denary number for the given binary number. for Question 8? How
256 128 64 32 16 8 4 2 1 did you work out
each unit?
0 1 1 0 0 0 1 0 1 0 0 0 1 0 0 1
13 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Hexadecimal
Hexadecimal is also a number system. Humans can use hexadecimal, but computers
cannot process it. Like denary numbers, hexadecimal numbers also need to be
converted to binary to be processed by a computer.
Hexadecimal is a base-16 system and uses 16 symbols, these are the numbers 0-9
and the letters A-F. This is to allow the denary values 0-15 to be represented in
hexadecimal. This is shown in Table 1.1.
Denary 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Hexadecimal 0 1 2 3 4 5 6 7 8 9 A B c D E F
Table 1.1: Hexadecimal representations of denary numbers
The reason for using the symbols A-F for the denary numbers 10-15 is so only one
symbol is needed for the denary number in hexadecimal.
8 4 2 1
0 1 1 1
To convert the binary number to hexadecimal you can use simple addition again.
4 + 2+ 1 =7. If you look at the symbol table (Table 1.1), you can see that the
hexadecimal for 7 is also 7. Therefore, the denary number 7 is 0111 as binary and 7
as hexadecimal.
So, what happens with denary numbers that are greater than 9?
First convert the denary number 12 to 4-bit binary.
8 4 2 1
1 1 0 0
To convert the binary number to hexadecimal you can use simple addition
again. 8 + 4= 12. If you look at the symbol table (Table 1.1), you can see that the
hexadecimal for 12 is C. Therefore, the denary number 12 is 1100 as binary and 12
as hexadecimal.
Converting the denary number to binary first isn’t necessary for denary numbers
that are less than 16, but it makes the process easier when you need to convert larger
denary numbers.
So, how do you convert a larger denary number to hexadecimal?
1 Data representation
CONTINUED
First, convert the denary number 201 to 8-bit binary. You know you can use 8-bit
binary because the denary number is less than 256.
You then convert each 4-bit binary number again using simple addition.
8 + 4=12
8+1=9
The hexadecimal for 12 is C and the hexadecimal for 9 is 9. Therefore, the denary
number 201 converted to binary is 11001001 and to hexadecimal is C9.
To convert a hexadecimal number to a binary number of a denary number you can
just reverse the process.
To convert the hexadecimal number 5E to a binary number you need to convert
each symbol to 4-bit binary. Remember E is the number 14.
8 4 2 1 8 4 2 1
0 1 0 1 1 1 1 0
5 E
Therefore, the hexadecimal 5E converted to a binary number is 01011110.
To convert the hexadecimal 5E to denary, you can use the binary number that you
have just calculated.
128 64 32 16 8 4 2 1
0 1 0 1 1 1 1 0
You can add all the units together to get the denary value. 64+16 + 8 + 4 + 2 =v94.
The hexadecimal 5E converted to a denary number is 94.
Questions
1 Convert the hexadecimal A2 to a binary number.
2 Convert the binary number 100111010001 to hexadecimal.
3 Convert the denary number 350 to hexadecimal.
4 Convert the hexadecimal 3AC to a denary number.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Each computer has a MAC address. This MAC address is written in MAC address: a
hexadecimal. This is one of the ways that hexadecimal is used in unique address that is
computer science. given to a computer
at the manufacturing
Use the internet to find three more uses of hexadecimal in computer science. stage that can be
used to identify the
computer.
Rule 2 is l + 0= l
Rule 3 is 1 + 1 = 10 (this is because 10 in binary is 2)
Rule 4 is 1 + 1 + 1 = 11 (this is because 11 in binary is 3)
You can apply these rules to add the binary numbers 10010100 and 00011110.
10 0 10 10 0
0 0 0 1 1 1 1 0
You need to start at the right and begin applying the rules. The first calculation
is 0 + 0. Rule
The next calculation is 0 + 1. Rule 2 means the result is 1.
1 0 0 1 0 1 0 0
0 0 0 1 1 1 1 0
1 0
The next calculation is 1 + 1. Rule 3 means the result is 10. You need to write the 0 in
the answer section and carry the 1 to the next calculation.
1 0 0 1 0 1 0 0
0 0 0 1 1 1 1 0
0 0
The next calculation is 1+0+1, which results in 1 + 1. Rule 3 means the result is 10.
Write the 0 in the answer section again and carry the 1.
1 0 0 1 0 1 0 0
0 0 0 1 J 1 1 £
0 0 1 0
The next calculation is 1 + l + 1. Rule 4 means the result is 11. Write 1 in the answer
section and carry 1.
1
+ 1 0 0 1 0 1 0 0
0 0 0 2 j i 2 £
1 0 0 1 0
The next calculation is 1+0 + 0, which results in 1+0. Rule 2 means the result is 1.
Write 1 in the answer section. There is no carry this time.
1 1
+ 10 0 1 0 10 0
________ 0 0 0 2 2 _______ i_______ i_______ o
1 1 0 0 10
) CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
The next calculation is 0 + 0. Rule 1 means the result is 0. Write 0 in the answer section.
1 1 1
+ 10 0 1 0 10 0
0 0 0 1 J 1 1 0
0 1 0 0 10
The final calculation is 1+0. Rules 2 means the result is 1. Write 1 in the answer section.
1 1
1 0 0 1 o 1 o 0
0 0 2 2 j i i 2
1 0 1 1 0 0 1 0
Therefore, when the binary numbers 10010100 and 00011110 are added, the answer is
10110010.
Questions
3 Add the 8-bit binary values 00011001 and 01000011.
4 Add the 8-bit binary values 00100110 and 01010111.
You should now know that the largest number that can be stored in an 8-bit binary
register is 255. What happens when two 8-bit binary values are added, and the result is
larger than 255?
The following example, which is almost complete, is very much like the previous
calculation with a slightly different binary number. Can you spot the difference?
1 0 0 1 0 1 0 0
1 0 0 1 1 1 1 0
0 0 0 10
If you now try and do the final calculation, that would be 1 + 1 = 10. You write 0 in the
answer section, but there is nowhere to carry the 1. This is because the two 8-binary KEY WORD
binary values are added the result is 306, which is greater than 255. Therefore, the
number cannot fit in the 8-bit register and an overflow error is created. overflow error: a
type of error that
1 occurs when a
1 0 0 0 0 0 number larger than a
register can store is
generated.
Overflow error
Each computer has a predefined limit, for example, 16-bit registers. What is the
largest number that could be stored in a 16-bit register? If a number larger than this is
generated in a process, an overflow error will occur.
1 Data representation
0 0 1 0 1 1 0 0
If a logical binary shift to the left is performed on the binary number, each value in the
binary number is moved one place to the left. The result would be:
0 1 0 1 1 0 0
You should notice that the left most 0 has been removed from the register. This is
because there was no place to the left to shift this value. You should also notice that
there is now an empty section in the register at the right. When a binary number is
shifted, the resulting empty sections are filled with a 0.
0 1 0 1 1 0 0 0
If you convert the first binary number to denary, you get the denary number 44. If you
convert the binary number after the logical left shift has been performed, you get the
denary number 88. This means that each logical shift to the left multiples the binary
number by 2.
Consider the binary number again:
0 0 1 0 1 1 0 0
If a logical shift to the right is performed on the binary number, each value in the
binary number is moved one place to the right. The result would be:
0 0 1 0 1 1 0
You should notice that the right most 0 has been removed from the register. This is
because there was no place to the right to shift this value. You should also notice that
there is now an empty section in the register at the left. When a binary number is
shifted, the resulting empty sections are, again, filled with a 0.
0 0 0 1 0 1 1 0
You already know that the first binary number converted to a denary number is 44. If
you convert the binary number after the logical right shift has been performed, you get
the denary number 22. This means that each logical shift to the right divides the binary
number by 2.
Consider another binary number:
) CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
When the first binary number is converted to a denary number, the result is 236.
When the binary number is converted after the logical shift to the left has been
performed, the denary value is 216. You should notice that 236 multiplied by 2 is not
216. Therefore, one of the problems with a logical shift is that data can lose its integrity
as vital bits can be removed from the register.
More than one logical shift can be performed on a register. For example, two logical
shifts to the left can be performed. This time, each value in the register is shifted two
places to the left.
The binary value:
1 1 1 0 1 1 0 0
would become:
1 0 1 1 0 0 0 0
Questions
5 Describe what happens in a logical binary shift.
6 Perform two logical shifts to the right on the binary number 11101100.
0 0 1 0 0 0 1 1
1 1 0 1 1 1 0 0
1 1 0 1 1 1 0 1
11011101 is the binary representation of -35 using the two’s complement method.
1 Data representation
ACTIVITY 1.2
Use the internet to find an example of an ASCII character set and a Unicode
character set. What kind of different characters are represented? Are upper
and lowercase letters the same?
Using the ASCII table, try to decode this message:
01000011011011110100110101110000011101010111010001100101011100
100101001101
10001101101001010001010110111001100011011001010110100101110011
011001100111
01010110111000100001
Remember, each letter will be represented as an 8-bit binary number.
Try writing a message for your friend to decode.
An image is made up of tiny dots called pixels. If an image was simply created using pixel: a very small
the colours black and white, each pixel would be either black or white. The binary dot of colour that is
value 1 could be used to represent the colour black and the binary value 0 could be displayed with many
used to represent the colour white. others to create an
image.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
If each pixel is converted to its binary value, a data set such as the following could
be created:
0011111000100000101000000011001010011000000011010001011001110010100000100
01111100
If the computer is informed that the image that should be created using this data is
9 pixels wide and 10 pixels high, it can set each pixel to black or white and create the KEY WORDS
image (See Figure 1.2). The type of data that is used to provide information, such as
the dimensions and resolution of an image, is called metadata. resolution: the
dimensions of an
image.
metadata: additional
data that is stored
with an image
that can provide
information such as
the dimensions of the
image and the time
and date the image
was taken.
Figure 1.2: An image created just from black and white pixels
Most images use a lot more colours than black and white. Each colour has its own
binary values. Colours are created by computer screens using the Red Green Blue
(RGB) colour system. This system mixes the colours red, green and blue in different
amounts to achieve each colour.
ACTIVITY 1.3
Use the internet to find an RGB colour scale. You should notice that each
colour in the scale is first presented as hexadecimal. The first two hexadecimal
values are the amount of red, the second two the amount of blue and the last
two the amount of green.
Practise your hexadecimal to binary conversion by converting your favourite
colour to its binary value.
1 Data representation
Most images are created using thousands of pixels. Each of those pixels needs
quite a lot of data. Multiply that by the thousands of pixels that make up the
image and that is a huge amount of data. This is why image files can often be so
large in size.
Each image has a resolution and a colour depth. The resolution is the number
of pixels wide and the number of pixels high that are used to create the image.
The colour depth is the number of bits that are used to represent each colour.
For example, each colour could be represented using 8-bit, 16-bit or 32-bit binary
numbers (see Figure 1.3). The greater the number of bits, the greater the range
of colours that can be represented.
If the colour depth of an image is reduced, the quality of the image is often reduced.
Can you see how the quality of the image is reduced in comparison to the number of
bits used?
If the resolution or the colour depth of an image is changed, this will have an effect
on the size of the image file. If the resolution is increased, the image will be created
using more pixels, so more data will need to be stored. If the colour depth of the
image is increased, each pixel will need more data to display a greater range of
colours so more data will need to be stored. Both will result in a larger file size for
the image.
People often have to sacrifice the quality of their images when displaying
them online. This is because having files that are very large in size can take
more time to download. This may frustrate users as it may mean they have to
wait for a website to load, due to the number of large files it contains.
Time sample 1 2 3 4 5 6 7 8 9 10 11 12
Sound value 9 13 9 3.5 4 9 1.5 9 8 5 8 5.5
Each sound value is converted to binary to be processed by the computer. Each sound
value is then used to playback the sound, when the recording is played. If the recorded
sound wave is played it would now look like Figure 1.5:
You will notice that the two sound waves look different. This is because the number of KEY WORDS
samples taken is too far apart, so vital data in between time samples has been lost. This sample rate: the
will result in a lack of accuracy in the sound that is recorded. Therefore, more samples number of samples
need to be taken each second to improve the accuracy of the recorded sound. The recorded each
number of samples taken in a second is called the sample rate. Sample rates are second.
measured in hertz. 1 hertz is equal to 1 sample per second. A common sample rate is
44.1 khz (kilohertz), this would require 44 100 samples to be taken each second. That is sample resolution:
a lot of data! If the sample rate is increased, the amount of data required for the the number of bits
recording is increased. This increases the size of the file that stores the sound. that are used to
record each sound
Further data is required to represent sound, and this is the sample resolution. This is the
sample.
number of bits that are used to represent each sample. A common sample resolution is
24 >
1 Data representation
16-bit. The higher the sample resolution, the greater the variations in amplitude that can
be stored for each sample. This means that aspects such as the loudness of the sound
can be recorded more accurately. This will also increase the amount of data that needs
to be stored for each sample. This increases the size of the file that stores the sound.
There are times when you will need to know the size of a data file, such as when
you are attaching a file to an email. Most email providers have a file size limit, so
you need to know the size of that file, to know if it can be attached to your email
Data is measured using different units, which are shown in Table 1.2.
Unit Description
Bit This is the smallest measurement for data
Nibble There are 4 bits in a nibble
Byte There are 8 bits in a byte
Kibibyte (KiB) There are 1024 bytes in a Kibibyte
Mebibyte (MiB) There are 1024 Kibibytes in a Mebibyte
Gi bi byte (GiB) There are 1024 Mebibytes in a Gibibyte
Tebibyte (TiB) There are 1024 Gibibyte in a Tebibyte
Pebibyte (PiB) There are 1024 Tebibytes in a Pebibyte
Exbi byte (EiB) There are 1024 Pebibytes in an Exbibyte
Table 1.2: Data measuring units
Although most computers will calculate the size of a file for you, you need to be able
to show that you can do this manually for the exam. This is just for an image file and
a sound file.
There are several pieces of information that you need to know to calculate the size
of an image file, these are:
• the number of images in the file
• the resolution of the image
• the colour depth of the image.
25 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
When you know this information, you can perform a simple calculation to get the
size of the image file, which is:
width of image x height of image x colour depth of image x number of images in file
Therefore, if you have the following information about an image file:
• 10 images in the file
• image resolution is 100 x 150
• colour depth is 8-bit colour,
you can calculate the size of the image file as follows:
• 100 x 150 = 15,000 (this means there are 15 000 pixels in the image)
• 15 000 x 8 = 120,000 (this means that there are 120 000 bits in each image)
• 120 000 x 10 = 1 200 000 (this means there are 1 200 000 bits in the image file).
You will be asked to calculate the size of an image file to a certain unit of
measurement. The answer given here (1 200 000) is the number of bits that are in the
image file. If you wanted to know how many bytes are in the image file, you need to
divide the final answer by 8, as there are 8 bits in each byte, for example:
1 200 000-8=150 000 bytes
If you wanted to know how many kibibytes the file was, you need to divide the
answer in bytes by 1024, for example:
150 000 1024 = 146.5 KiB (to 1 decimal place)
Questions
1 How many times would you need to divide the answer in bytes by 1024 to find
the answer in Gibibytes?
2 How many pixels would there be in an image that has a resolution of 1000 x 1500?
There are several pieces of information that you need to know to calculate the size
of a sound file, these are:
• the length of the soundtrack
• the sample rate of the soundtrack
• the sample resolution of the soundtrack.
When you know this information, you can perform a simple calculation to get the
size of the sound file, which is:
sample rate x sample resolution x length of soundtrack
Therefore, if you have the following information about a sound file:
• length of 30 seconds
• sample rate of 44,100 hz
• sample resolution of 8 bits,
you can calculate the size of the sound file as follows:
• 44 100 x 8 = 352 800 (this means there are 352 800 bits per second)
• 352 800 x 30= 10 584 000 (this means there are 10 584 000 bits in the sound file).
1 Data representation
CONTINUED A
You will be asked to calculate the size of a sound file to a certain unit of
measurement. The answer given (10 584 000) is the number of bits that are in the
sound file. If you wanted to know how many bytes are in the sound file, you need to
divide the final answer again by 8, as there are 8 bits in each byte, for example:
10 584 000 - 8 = 1 323 000 bytes
If you wanted to know how many mebibytes the file was, you need to divide the
answer in bytes by 1024, then by 1024 again, for example:
1 323 000- 1024- 1024= 1.3 MiB (to 1 decimal place)
SELF ASSESSMENT
What were the points that you thought about regarding lossy compression to
answer question 7? Did you relate these points back to why lossy compression
is not suitable for a text file, or did you just make points about the drawbacks
of lossy compression in general?
Lossless compression uses a compression algorithm to reduce the size of the file,
without permanently removing any data. A common method that can be used to
do this is by finding repeating data in the file and grouping this data together.
For example, consider the following message:
Excluding the spaces between the words and the full stops, the message has a total of
62 characters. 1 character requires 1 byte of storage, so 62 bytes of storage would be
needed to store this message.
When you look at the message, you should notice that it consists of words that are
mostly repeated. Instead of storing all 62 characters individually, the words and the
positions at which they occur in the message can be stored in a lookup table,
for example:
The lookup table needs 1 byte for each character in each word and 1 byte for each
position the word occurs in the message. Therefore, 33 bytes are needed to store the
words and 13 bytes to store the positions, giving a total of 46 bytes. This is much less
than the 62 bytes we required with our original method. No data has been lost and we
have reduced our storage requirements by 26%, quite a saving! To recreate the message,
the computer simply retrieves the words and places them in the positions allocated.
KEY WORD
A similar process can be applied to an image file with a lossless compression algorithm
called run length encoding (RLE). This algorithm will group together repeating pixels run length encoding
and store how many times they occur. For example, consider the simple image in (RLE): An algorithm
Figure 1.6: that groups together
repeating patterns
and indexes them.
1 Data representation
If W is white, Y is yellow, R is red and G is green, RLE could compress the image into
the following data:
12W, 3Y, 5W, 2Y, 1R, 2Y, 3W, 2Y, 3R, 2Y, 3W, 2Y, 1R, 2Y, 5W, 3Y, 7W, 1G, 5W, 2G,
1W, 1G, 1W, 2G, 4W, 3G, 7W, 1G, 4W.
This means that the amount of data can be reduced as pixels are grouped together
and the data for each pixel does not need to be stored. The resolution of the image is
stored with the data, so that the computer knows the size to recreate it when the data
is decompressed.
ACTIVITY 1.4
Why don't you try creating a simple image and writing out the RLE data for
it? You could then give it to your friend, along with the image resolution,
and they can have tun trying to recreate your image.
Peer Assessment
Ask your friend whether you got the RLE correct for your image in Activity 1.4.
Ask them if you could have done anything to make your RLE any clearer. Ask
them if you missed any important data.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SUMMARY
Computers require any data to be converted to binary before it can be processed by the computer.
Different number systems exist such as denary, binary and hexadecimal.
Hexadecimal is used in computer science for uses such as aiding programmers and representing MAC addresses.
Binary numbers can be added using four rules. If this creates a result greater than 255 for 8-bit binary numbers,
an overflow error occurs.
Logical binary shifts can be performed on binary numbers. These can shift left or shift right and can be done
multiple times. This changes the binary number and can affect the accuracy of the binary number.
Text is converted to binary using a character set such as ASCII or Unicode.
Images are converted to binary by taking each pixel and providing it with a colour code that is converted to a
binary value. The larger the resolution and colour depth of an image, the greater the amount of data that will
need to be stored in the image file. This also increases the quality of the image.
Sound is converted to binary by sampling the sound at a set time interval. The value of each sound sample is
converted to binary. The greater the sample rate and resolution of the sound, the greater the amount of data
that will need to be stored in the sound file. This also increases the accuracy of the recording.
Data is measured in different units such as bits, bytes and mebibytes.
Data can be compressed, using lossy or lossless compression, to reduce the size of a file.
This means it will take up less storage space and it can be quicker to transmit the file.
EXAM-STYLE QUESTIONS
COMMAND WORDS
1 There are two different types of data, known as analogue data and digital data,
a State what is meant by analogue data. [1 ] state: express in
b State what is meant by digital data. [1] clear terms.
[Total: 2] describe: state the
2 Describe the difference between a denary number system and a points of a topic I
binary number system. [4] give characteristics
3 A music venue has a small display screen built into the top of each seat. and main features.
The display screen displays the number of the seat. Each seat number is
displayed as hexadecimal.
a Convert the two given seat numbers into 12-bit binary values. [4]
• 21A
• 90D
b Write the seat number that would be displayed for the binary
number 000010011100. [2]
[Total: 6]
4 Two registers store the given 8-bit binary values. Register 1
stores 00110111 and register 2 stores 01110011.
a Add the two binary values and write the result of the calculation.
Show all your working. [3]
1 Data representation
COMMAND WORDS
calculate: work
out from given
facts, figures or
information.
give: produce an
answer from a given
source or recall I
memory.
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
Data
transmission
K?
IN THIS CHAPTER YOU WILL:
learn how data is broken down into packets to be transmitted, including the contents of each packet
learn about the universal serial bus (USB) interface and how it is used to transmit data
be able to describe how data is encrypted using both symmetric and asymmetric encryption.
) CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
GETTING STARTED
Your data is transmitted to other devices, sometimes all over the world, on a
regular basis. Have you thought about how it gets there? Draw a diagram to
represent how you think data travels from your device to your friend's device
when you send them a message. It doesn't matter if you don't think you know
how this is done, just draw what you think happens and you can see at the
end of the chapter how close you were with your diagram.
The importance of checking for errors in data transmission can costs banks a lot of money. It takes
very large and powerful systems to check the millions of transactions that are made every day. However,
it would cost them even more in compensation money, if they messed up the data of their customers,
and possibly their money, so they put a lot of time, money and effort into the process.
Discussion questions
1 How would you feel about having a bank account with a bank that did not have any error detection
systems in place? What problems do you think this could cause?
2 Do you think it is right that the bank is responsible for checking errors in the transmission of data?
Much of the hardware, that will be used to transmit the data from one device to another, will not be
owned by them. So, why do you think the bank should be made responsible for checking for errors if
the errors may occur using hardware that isn't theirs?
34 >
2 Data transmission
The payload of the data packet is the actual data from the file that you are sending. payload: the actual
The data is broken up into many small units to be sent as the payload in each packet. data that the user
is sending to the
The trailer section of the packet is sometimes known as the footer. This contains two
receiver.
main pieces of information. The first is the marker to indicate it is the end of the
packet and also the data for any error detection systems that are being used. trailer: a section of
You will learn more about this in Section 2.2. a packet of data that
contains information
about any error
Questions checking methods
that may be used.
1 Can you name the three main sections of a data packet?
2 What information does the packet header contain?
3 Which part of the data packet is the actual data from the file?
4 Why does data need to be broken down into packets to be transmitted?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ACTIVITY 2.1
Ask your teacher if you are allowed to use a packet tracer. Your teacher may
want to complete this activity together as a class. Use the packet tracer to
send data to another device and look at the data that the packet tracer
software provides. What kind of information does it give you? What route did
your packets take to get to the destination device?
network: computers
and devices that are
joined together using
cables or wireless
technology.
router: a network
component that
examines a data
packet to obtain its
destination address
and then forward
the packet to this
address.
The packets of data start at device A, they could be transmitted down any of the
pathways between device A and device B. Each packet can be sent using a different
pathway. When a packet reaches a router, the router decides which pathway to send
the packet along next. This will continue until all the packets have arrived at device B.
It is likely that the packets will arrive out of order. Once all packets have arrived, they
are reordered to recreate the file.
2 Data transmission
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Device A Device B
Each bit of data is transmitted one at a time
along a single wire
Advantages Disadvantages
As data is sent one bit at a time, it As data is sent one bit at a time, the
should arrive in order of sequence. This transmission of data is slower.
means there is less chance of the data
being skewed.
KEY WORD
As data is sent along a single wire, Additional data may need to be sent to
there is less chance of interference. indicate to the receiving device when interference:
This means there is less chance of error the data transmission has started and disruption, such as
in the data. stopped. These are called a start bit electromagnetism,
and a stop bit. to data when it is
Only one wire is needed for a serial transmitted.
transmission cable, therefore, it is
cheaper to manufacture and also
cheaper to buy.
Serial transmission has less chance of data being skewed and less chance of interference.
This makes it more suitable for the transmission of data over long distances.
Advantages Disadvantages
As data is sent multiple bits at the As data is sent multiple bits at the
same time, the transmission of data is same time, bits do not arrive in order
quicker. and need to be reordered after
transmission. This increases the risk of
the data being skewed.
Many computers and devices use As data is sent along multiple wires,
parallel data transmission to transmit there is more chance of interference.
data internally. Therefore, there is no This means there is more chance of
requirement to convert this to serial error in the data.
data transmission to transmit the data
across a network.
Multiple wires are needed for a parallel
transmission cable, therefore, it is more
expensive to manufacture and also
more expensive to buy.
Parallel transmission has an increased chance of data being skewed and an increased
chance of interference. This makes it more suitable for the transmission of data over
shorter distances. This is often limited to approximately 5 metres.
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Question
5 A marketing company prints leaflets to deliver to people’s houses. The leaflets
are designed on a computer and sent to a large printer that is 3 metres away.
Large numbers of leaflets need to be printed in a short period of time, to makes
sure that they are ready for delivery. Would you use a serial or a parallel data
transmission cable to connect the computer to the printer? Why would you choose
this type of cable?
KEY WORDS
Simplex, half-duplex and full-duplex transmission involve the direction in which the simplex: a
data is transmitted. transmission
method where data
is transmitted in a
Simplex data transmission single direction only.
In simplex data transmission, data is transmitted from one device to another in one half-duplex: a
direction only. Figure 2.5 shows an example: transmission method
where data is
transmitted in both
directions, but only
one direction at a
time.
full-duplex: a
transmission method
where data is
Figure 2.5: Simplex data transmission
transmitted in both
directions at the
You would only use this type of data transmission when there is no need to send data same time.
both ways between the devices. One example is connecting a keyboard to a computer.
Simplex data transmission can be used to do this as data only needs to be sent from
the keyboard to the computer, so that the computer screen can display the keys that
are pressed. There is no reason why the computer would need to send data to the
keyboard, so a simplex data transmission connection is used.
Figure 2.6: Simplex data transmission is used between a computer and a keyboard
2 Data transmission
You would use this type of data transmission when you need to send data in both
directions between the devices, but there is no requirement for this to be at the same
time. It can also be used when the communication between two devices needs to have
a high level of performance. This is when two half-duplex connections can be set up
between devices to allow data to be transmitted in both directions at the same time, but
using two different channels of communication. Can you work out how this would be
set up?
ACTIVITY 2.3
You would use this type of data transmission when it is essential for data to be both sent
and received by each device, at the same time. One example is a telephone conversation.
The person speaking into Device A can speak at the same time as the person speaking
into Device B. It may be a little bit of a chaotic conversation if you both try and speak
at the same time all the time though! However, during most conversations, people do
sometimes speak at the same time, so full-duplex data transmission is needed.
When a connection is created between two different devices it will either be a serial or
parallel data connection. It will also be a simplex, half-duplex or full-duplex connection.
This means that a connection can be, for example, a serial simplex connection, or a
parallel half-duplex connection, or possibly a serial full-duplex connection. You need to
understand when each of the different methods of transmission are most suitable.
Questions
6 Which method of data transmission sends data along a single wire?
7 Which method of data transmission sends data multiple bits at a time?
8 If a data transmission connection sends data one bit at a time, in both directions,
but not at the same time, what kind of data transmission methods are used?
9 What are two advantages of serial data transmission?
10 What are two disadvantages of parallel data transmission?
11 A business manager transmits data about its customers to a central file server. The
file server is 100 metres away from the business manager’s office. They need to be
able to send and receive customer data to and from the server, at the same time. The
accuracy of the customer’s data is imperative. Which methods of data transmission
should be used to create the connection between the business manager’s computer
and the file server? Why would you choose those methods?
ACTIVITY 2.4
Write a data transmission scenario like the one given in Question 11. Think
about which data transmission methods could be used for your scenario and
why they would be the most suitable.
Peer Assessment
Give the scenario to a friend and ask them which data transmission methods
they would use. Are they the same methods that you thought should be used?
If you have chosen different methods, discuss and come to an agreement
about which methods should be used. If you chose the same methods, see if
you had the same reasons for choosing those methods.
42 >
2 Data transmission
The concept of USB can be a little confusing, as it is used to describe several aspects. USB: an industry
You may have heard of a USB connection, a USB cable, or maybe you call a storage standard that is used
device ‘a USB'. You need to understand the difference between several of these aspects. to transmit data.
A USB interface includes items such as a USB port, a USB cable, a USB connection
USB port: a socket
and a USB device.
that is a part of a
A USB device, such as a USB memory stick, is a device that uses the USB interface. device or computer
It plugs into a USB port on a computer and it transmits data using a USB connection. that enables you to
A USB cable can be used to connect devices, such as a mouse, to a computer. insert a USB cable.
A USB connection uses serial data transmission to transmit data between the devices. USB cable: a type of
However, it a special type of serial data transmission connection that is used that is transmission media
designed to transmit data at high speeds. that uses the USB
method to transmit
ACTIVITY 2.5 data.
One of the issues with serial data transmission is the transmission speed is USB connection: a
slower than parallel. Research how a USB connection is able to transmit data collective name for
at a faster rate. using a USB cable
plugged into a USB
port to transfer data
from one device to
COMPUTER SCIENCE IN CONTEXT another.
Many devices are connected using a USB cable. This is because the USB USB device: the
interface is an industry standard, which means that manufacturers don't need name of a device that
to worry about compatibility issues when connecting devices. One of the most plugs into a USB port
recent versions of the USB interface to be released is USB 4. on a computer.
ethernet: another
type of connection
ACTIVITY 2.6 that can be used to
transmit data within a
Research the data transfer speed of USB 4; is this different to USB 1,2 and 3?
network.
What other differences can you find between the different versions of USB?
There are several advantages and disadvantages of the USB interface, see Table 2.3:
Advantages Disadvantages
It is a simple interface. The USB cable to device can The length of a USB cable is limited, normally to
only fit into the USB one way. Therefore, it means less 5 metres.
errors in connecting devices are likely to be made.
The speed of a USB connection is relatively high, so The transmission speed is relatively high for a USB
data can be transferred quickly. connection, but it isn't as high as other types of
connection, such as ethernet.
(continued)
43 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Advantages Disadvantages
The USB interface is a universal standard for
connecting devices, therefore a USB port is included
in many different devices.
When a USB device to cable is inserted into a USB
port, it is automatically detected. The first connection
will normally involve the download of drivers to
operate the hardware that has been connected. Each
connection after this the driver should not need to be
downloaded again.
A USB connection can also be used to power a
device, so it does not need another power source. It
can also use this to charge a device, such as a mobile
phone.
Questions
12 What does USB stand for?
13 What type of data transmission method does a USB interface use?
14 What are two advantages of using the USB interface?
15 Can you name five devices that are connected using a USB interface?
16 What is the length a USB cable limited to? Can you think why it is limited to
this length?
There are several error detection methods that can be used, these include:
• parity check
• checksum
• echo check.
Each of these methods is designed to check for errors after the data has been
transmitted from one device to another.
A parity check can use an odd or even check method. Each byte of data has 7 bits and parity check: a type
1 extra bit that is called a parity bit (see Figure 2.11). The parity bit is normally the of error detection
first or last bit of data in the byte. method that adds an
additional bit to each
byte to create an odd
or even sum.
Figure 2.11: The parity bit is the first bit of data in this byte
Before transmission begins, the parity check is set to be either odd or even parity.
The number of Is in the 7 bits of data is totalled. In the example in Figure 2.11, the
result of that would be 2. If an odd parity check is used, then a 1 is added as a parity
bit. This is because all the Is in the byte now add up to 3, which is an odd number.
If an even parity check is used a parity bit of 0 would have been added instead. This
is because all the Is in the byte would then add up to 2, which is an even number.
When the parity bit has been added to each byte, the data can be transmitted. After
transmission, the receiving device will check each byte of data for errors. If an odd
parity check has been used and the device finds a byte that has an even number of Is,
then it knows that an error has occurred with this byte of data. The error is detected!
Questions
17 Which of these bytes would have been transmitted incorrectly if an even parity
check has been used?
a 10111011
b 01110111
c 10101000
18 Which of these bytes would have been transmitted incorrectly if an odd parity
check has been used?
a 00110001
b 10110101
c 10001000
19 Can you think of an instance in which an error could occur in the data, but this
would not be detected by a parity check?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Once the checksum value has been calculated it is added to the data to be transmitted
with it. After transmission, the receiving device uses the same method to calculate a
value from the received data. If the values match, then the device knows that no error
has occurred during transmission. If the values do not match, the device knows that an
error has occurred during transmission. The error is detected!
Questions
20 What is the checksum value calculated from?
21 What happens to the checksum value when it has been calculated before
transmission?
22 Why would checksum values that do not match show that an error has occurred?
An echo check involves a simple comparison of the data sent to the data received. echo check: a type
The sending device transmits the data to the receiving device. The receiving device of error detection
then transmits the data it receives back to the sending device. The sending method that sends
device compares the data it sent to the data it has received back from the a copy of the
receiving device to see if they match. If they do, then no error has occurred. transmitted data back
If they don’t match, then the sending device knows the data was received with error. to the sender to be
The error is detected! compared with the
original data sent.
ACTIVITY 2.8
Question
23 If the data does not match that which is sent back by the receiving device, will this
always mean that the receiving device did not receive the data correctly? How do
you know that?
2 Data transmission
A method called automatic repeat request (ARQ) can be used to do this. There are two automatic
main ways that an ARQ can operate and each method uses either a positive or negative repeat request
acknowledgement and a timeout. (ARQ): a type of
error detection
In a positive acknowledgement method:
method that uses
• The sending device transmits the first data packet. acknowledgement
and timeout to see
• The receiving device receives the data and checks it for errors.
if data has arrived
• Once the receiving device knows it has received the data error free, it sends a correctly after
positive acknowledgement back to the sending device. transmission.
• When the sending device receives this positive acknowledgement, it knows the acknowledgement: a
receiving device has received the data packet error free and it sends the next data message that is sent
packet. from one device to
• If the sending device does not receive a positive acknowledgement within a set another to indicate
timeframe, a timeout occurs. whether data is
received correctly,
• When a timeout occurs, the sending device will resend the data packet. It will keep
doing this when a timeout occurs, until it receives a positive acknowledgement, timeout: a period of
or sometimes a limit (such as 20 times) is set and when this limit is reached it will time that is set and
stop resending the data. used to wait for an
acknowledgement to
be received.
ACTIVITY 2.9
47 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
With a partner, discuss and write down the differences between a check digit
and a checksum.
2.6 Encryption
You have learnt a lot about how data is transmitted in this chapter. You have also
learnt why it is important for data to be received correctly and how errors can be
detected to make sure this happens. You also need to understand that the data that is
transmitted often needs to be protected during transmission. This is because data
is valuable, especially when it contains our personal details and information that is
personal to us. A hacker may try and steal the data during transmission so that they KEY WORDS
can use it for their own gain. One method of protection that can be used when
transmitting data is encryption. encryption: a
method of securing
Data before encryption takes place it is called plain text. An encryption algorithm,
data for storage
called an encryption key, is used to scramble the data and make it meaningless. This
or transmission
meaningless data is called cipher text. The cipher text can then be transmitted from
that scrambles
one device to another. The receiving device uses the key to decrypt the cipher text and
it and makes it
return it to its plain text form. This means the data will have meaning again if read.
meaningless.
One important thing to note about encryption is that is does not stop a hacker
stealing the data that is transmitted. It just means that the data that is stolen will be plain text: the name
meaningless, as it will be encrypted and therefore scrambled. They will not understand given to data before
any of the data in the file. encryption.
There are two main methods of encryption that can be used symmetric and encryption key: a
asymmetric. type of algorithm that
is used to encrypt
The process for symmetric encryption is: data.
• Plain text is encrypted into cipher text using an encryption key.
cipher text: the
• The cipher text and the encryption key are sent separately to the receiving device. name given to data
after transmission.
• The same key is then used to decrypt the cipher text back into its plain text form.
This is the simplest method of encryption and is still used for data that is not of a high symmetric: a type
level of importance. It is sometimes used by people just wanting to encrypt the data that of encryption that
they store on their own computer or external storage device, as it isn’t being transmitted uses the same key to
across a network. However, people began to worry that it could be too easy for a hacker encrypt and decrypt
to intercept both the cipher data and the encryption key if it is sent across a network, or data.
the internet, so a more secure method was developed called asymmetric encryption. asymmetric: a type
The process for asymmetric encryption is: of encryption that
uses two different
• Plain text is encrypted into cipher text using a public key. This is also a type of
keys to encrypt and
encryption algorithm.
decrypt data.
• The cipher text is transmitted to the receiving device.
• The cipher text cannot be decrypted using the public key, it is decrypted using a
private key.
A person who uses an asymmetric method of encryption has a public encryption key.
This is called a public key because it is made public for the encryption process. Making
something public means that anyone can see and use it. Any device that wants to send
you encrypted data may obtain your public key and encrypt the data using your public
key. You also have a private key. Any encrypted data that your device receives that has
been encrypted with your public key can be decrypted with your private key. They act
as a pair. Your private key is always kept private though, your device does not make it
available to any other unless authorisation is given to do so.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
The process can work in reverse as well (a private key is used to decrypt and a
public key is used to decrypt), and this is what can occur in processes such as digital
signatures. These are used in security protocols such as SSL (secure sockets layer).
You will learn more about these in Chapter 5, about applications of the internet.
A bank uses asymmetric encryption for all the banking transactions that are
completed on a daily basis. As you can imagine, the data that is transmitted
for these banking transactions is very sensitive and personal data, so the bank
has to make sure that they use a very secure method of encryption for this
process.
Questions
24 What is the name given to an encryption algorithm?
25 What is the name given to data that has been encrypted?
26 Does encryption stop data being stolen by a hacker? Why or why not?
27 Why is asymmetric encryption a more secure method of encryption than symmetric?
SUMMARY
Data is broken down into packets to be transmitted from one device to another.
Each packet contains three parts: the packet header, the payload and the trailer.
The packet header includes the destination address, the packet number and the originator s address.
The payload is the data the sender wants to transmit.
The trailer contains data such as the error detection method to be used.
A process called packet switching can be used to send the data from one device to another across a network.
Data is transmitted using serial or parallel transmission.
Data is also transmitted using simplex, half-duplex or full-duplex transmission.
An interface called USB can be used to transmit data.
This is often used to connect hardware such as a keyboard to a computer.
Errors can occur when transmitting data due to interference.
Methods are required to detect any errors in transmission.
A parity check is an error detection method that uses a parity bit to detect errors.
An odd or even parity check method can be used.
A checksum is an error detection method that uses a calculated value to detect errors.
An echo check compares data that is sent and received to see if they match, to detect errors.
2 Data transmission
CONTINUED
An ARQ can be used to monitor whether data is received correctly after transmission.
------------------------------------------------------------------ -------------------------
I A check digit is an error detection method that is used for data entry.
Data can be encrypted to keep it secure during transmission.
Encryption can be performed using a symmetric or asymmetric method.
---------------------------------------------------------------------------- —-----------------------------------------------------
Symmetric encryption uses the same key to encrypt and decrypt the data.
Asymmetric encryption uses different key, a public and a private key, to encrypt and decrypt the data.
1 Identify two items of data that would be included in the header of a packet identify: name I
of data. [2] select / recognise.
2 Explain why and how packets of data are reordered after packet switching explain: set out
has been used to transmit data across a network. [2] purposes or
3 Describe how data is transmitted using serial half-duplex data transmission. [4] reasons / make
4 Give two benefits of using the USB interface to connect hardware devices the relationships
to a computer. [2] between things
5 A company has a central file server that is located 500 m away from the evident / provide
main office where employees work at their computers. why and / or how and
support with relevant
Employees send and retrieve files to and from the file server on a daily basis,
evidence.
often at the same time.
Identify the type of data transmission that would be most suitable for the describe: state the
given context. Explain why this would be the most suitable method of points of a topic I
transmission. [6] give characteristics
6 Four statements are given about error detection methods. and main features,
Tick (^) to show which statement applies to which error detection method. give: produce an
Some statements may apply to more than one error detection method. [4] answer from a given
source or recall /
Statement Checksum Echo check Parity check memory.
This method checks for errors
in data after it has been
transmitted.
This method can use an odd
or even process.
This method sends data
back from the receiver to the
sender to compare the data to
check for errors.
This method uses a value that
is calculated from the data to
check for errors.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
52 >
2 Data transmission
CONTINUED
> Chapter 3
Hardware
• develop an understanding of the role of the central processing unit (CPU) in a computer, including the
fetch-decode-execute cycle
• learn the role of each of the components in a CPU that has a Von Neumann architecture
• develop an understanding of what an embedded system is and be able to identify devices in which they
are used
• understand what an input device and an output device is and why they are needed
• learn the role of a sensor and the purpose of a range of different sensors, including how they capture data
• learn the role of random access memory (RAM) and read only memory (ROM)
• learn the role of secondary storage including the operation of the different types
• learn how cloud storage is used and the advantages and disadvantages of storing data in the cloud
• study the main components and types of address that are used when connecting a computer to a network.
■
3 Hardware
GETTING STARTED
Describe to a partner how you think a computer processes an instruction. Ask
your partner how they think a computer processes an instruction. Do you both
agree? If not, discuss the differences you have and come to an agreed process
and write this down. You can check at the end of the chapter how accurate
your initial understanding was.
KEY WORD
Internet of Things:
the connection of
computer systems
and everyday
devices, using
the internet, to
allow data to be
exchanged.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
3 Work with a partner and design your own smart device. What would you microprocessor: an
want it to do? What computer hardware would it need? integrated circuit that
is able to perform
many of the functions
of a CPU.
3.1 The role of the CPU embedded system: a
The CPU (central processing unit) is one of the fundamental parts of a computer. computer system that
Many people say it is the most important part, as it is where all the data and performs a dedicated
instructions are processed. This means it is a little bit like your brain, as that is where function.
you process all the data and instructions that you sense on a daily basis.
fetch-decode-
All computers have a form of CPU. In devices such as personal computers (PC) and execute cycle: the
laptops, this is normally a separate component in the computer. In devices such as cycle through which
those found in our houses, e.g. our washing machine, a similar type of component data and instructions
exists called a microprocessor. This performs a similar role to a CPU, but on are processed.
a smaller scale. Whereas a CPU can process thousands of complex instructions, a
microprocessor will process a much more limited set of instructions. A general purpose architecture: the
computer, such as a PC or a laptop, has a CPU and is able to perform a wide variety of design of a computer
tasks. A microprocessor is often built into a system that is designed to perform a very system, including
specific task. This type of system is called an embedded system. There are examples of the components it
embedded systems in many different areas of our lives, for example, a traffic light, contains.
a washing machine and a digital alarm clock.
When an instruction is processed by a computer, the method that is
used to do this is called the fetch-decode-execute cycle.
You need to understand what happens in the different
stages of the cycle and which components are used.
You’ll learn some interesting information about
how a computer works. How exciting!
You will learn the operation of the
architecture of a Von Neumann computer
system, which is one of the most common types
of modern architecture for a computer system.
Fetch: This is
the stage where the
instruction is fetched
into the CPU KEY WORDS
(
Execute: This is
the stage where the
■ Decode: This is
M the stage where the
input device: a
device that allows
data to be entered
into a computer
system.
instruction is M instruction is decoded
executed by the CPU Hj within the CPU RAM (random
access memory): a
Figure 3.3: The fetch-decode-execute cycle component in the
CPU that holds data
and programs that
Individual processes happen at each of these stages, using different components, to carry are currently in use.
out the cycle. So, what happens at each stage? We will explore this in the next sections.
hard drive: a storage
device that stores
data permanently,
3.2 The fetch stage until it is deleted by
the user.
Data and instructions are given to the computer through the use of input devices.
You will learn about these later in the chapter. When the data and instructions are program counter
input, they are stored in RAM (random access memory). If a user wants to open a file (PC): a component in
that is stored on the hard drive, this data will be brought from the hard drive into the the CPU that stores
RAM, also. the address of the
next instruction to be
In order for the data and instructions to be processed, they need to be brought processed,
from the RAM into the CPU. This is what happens at the fetch stage of the cycle. A
component within the CPU, called the program counter (PC), stores an address. This address: a memory
location in RAM.
component is an example of a register. The address stored by the PC is the address of
the next instruction that needs to be processed. The details of this address will be a memory address
location within the RAM. register (MAR): a
component in the
This address stored in the PC needs to be sent to another component in the CPU called CPU that holds the
the memory address register (MAR). This is another example of a register in the CPU.
address of the data
The address is transported from the PC to the MAR using the address bus. or instruction to be
Once the MAR has received the address it now knows where to find the instruction in located in RAM.
the RAM. To retrieve the instruction the MAR needs to send the address to the address bus: wires
location in RAM. It uses the address bus again to do this. Once the address is received used for the trans
at the location in RAM, the data stored in this location, e.g. the instruction, is sent to a mission of addresses
between components
in a computer.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
component within the CPU called the memory data register (MDR). This is also an
example of a register in the CPU. The instruction is sent to the MDR using the data KEY WORDS
bus. When the MDR has received the instruction, it sends it to the current instruction memory data
register (CIR). This is another example of a register in the CPU. The MDR uses the register (MDR): a
data bus to send the instruction to the CIR. This register is part of a component within component in the
the CPU called the control unit (CU). It is the CU that is responsible for the next stage CPU that holds the
of the cycle, the decode stage. data or instruction
Figure 3.4 shows the operation of the fetch stage of the cycle: that are fetched from
RAM.
data bus: wires used
for the transmission of
data and instructions
ALU between components
in a computer,
ACC current instruction
register (CIR): a
register that is built
into the CU that holds
the current instruction
that is being
processed in the CPU.
control unit (CU):
the component in the
CPU that controls all
the operations in the
Figure 3.4: How the fetch stage operates CPU.
of calculations are required, the data used in the process is sent to the arithmetic logic
KEY WORDS
unit ALL ). This is a component within the CPU that is responsible for any calculations.
Interim values may be created whilst these calculations are being performed, the ALU arithmetic logic
has a special register built into it called the accumulator (ACC ). It is this special register unit (ALU): the
that will store the interim values that are created in any calculations. Once any component in the
calculations have been performed, the actions for the instruction can be performed, CPU that performs all
e.g. the file can be opened or the letter typed can be displayed. the mathematical and
How do all the different components know what they are doing in the fetch-decode- logical operations
execute cycle? They have a conductor! This conductor is the CU. It sends signals to all required when
the components within the CPU to tell them when they need to perform their different processing data and
roles. The CU uses the control bus to send these signals. instructions.
accumulator (ACC):
ACTIVITY 3.3 a register that is
built into the ALU
Add the ALU and the ACC to your diagram (from Activity 3.2) then label it to that stores the
show the process for the decode and execute stages of the cycle. result of any interim
calculations.
Peer Assessment
control bus:
Exchange diagrams from Activities 3.2 and 3.3 with a friend and use the
wires used for
description of the fetch-execute-decode cycle to check whether their diagram
the transmission
is correct.
of control signals
between components
in a computer.
Questions
1 Where is data stored before it is fetched into the CPU?
2 Which component in the CPU is responsible for making sure the fetch-decode-
execute cycle is performed correctly?
3 What is the role of a bus?
4 Why does the ALU need the ACC? What would have to happen if it didn’t have
this special register?
5 Copy the table below and fill in a description for each component in the CPU:
Component Description
Program counter (PC)
Memory address register (MAR)
Memory data register (MDR)
Control unit (CU)
Current instruction register (CIR)
Arithmetic logic unit (ALU)
Accumulator (ACC)
Address bus
Data bus
Control bus
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ACTIVITY 3.4
A CPU contains an internal clock that controls the speed at which instructions are
processed. The speed is measured in hertz. A CPU that has a clock speed of 1 hertz is
able to process one instruction per second. If your CPU had a clock speed of 1 hertz
you'd be waiting rather a long time for any tasks to be completed!
Most modern computers have a clock speed that is measured in gigahertz (GHz).
A CPU with a clock speed of 2 GHz can process 2 billion instructions a second. That
is definitely a busy CPU! If a computer has two cores, each core can process 2 billion
instructions a second.
ACTIVITY 3.5
A CPU also contains a cache. The cache is a type of data storage within the CPU.
Instructions and data that the computer uses most can be stored in the cache.
This means that the CPU doesn’t need to fetch this data from the CPU, just from the
cache, so that process will be quicker. If the CPU can get the data and instructions
quicker, the performance of processing those instructions will improve. If a
computer has a larger cache, so it has more storage space to store the instructions and
data it uses most, then it can store more of them, so will need to spend less time going
to the RAM.
Some people need very powerful processors in their computer, as they need
to process a lot of data in a very short time period. One example would be
an architect. They need to be able to use a computer to create a 3D model of
their building design. It takes a lot of data to render these models, so a very
powerful processor is needed to do this. 'Render' simply means to make the
model. The computer does this by putting it together bit by bit.
Questions
6 Which CPU can process more instructions at the same time, a quad core or a
dual core?
7 How many instructions per second can a dual core 2.4Ghz CPU process?
8 If the cache size of a CPU is too big, this can actually have a negative effect on the
performance of the CPU. Why might this happen?
61 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
• optical mouse
• QR code scanner Quick Response Code
• scanner (2D and 3D)
• touch screen (resistive, capacitive and infra-red).
Question
9 Copy the table below that includes the examples of the input devices. For each
input device, describe the kind of data that it allows to be input and give an
example of when it is used. The first one has been done for you.
An output device is any device that allows the result of the data processing to be seen
or heard.
Common examples of output devices are:
• actuator
• digital light processing (DLP) projector
3 Hardware
• inkjet printer
• laser printer
• light emitting diode (LED) screen
• liquid crystal display (LCD) projector
• liquid crystal display (LCD) screen
• speaker
• 3D printer.
Question
10 Copy the table below that includes the examples of the output devices. For each
output device, describe the kind of data that it allows to be output and give an
example of when it is used. The first one has been done for you.
Questions
11 Is a sensor an example of an input device or an
output device?
12 Can you name five different types of sensor?
13 Can you think of one application for each of the
following sensors?
a Light
b Magnetic field
c Temperature
14 Can you think of two ways that the use of sensors is
of benefit to humans?
15 How could an accelerometer be used to protect the Figure 3.8: Art galleries use temperature and humidity
hard drive on a computer? sensors
Figure 3.9: Technician changing a computer's RAM Figure 3.10: The inside of a hard disk drive
Did you know that there are also different types of RAM and ROM? You do not magnetic storage:
need to know what these are for the exam, but it is interesting to find out what a type of secondary
they are. Use the internet to research the different types of RAM and ROM storage that uses
and when they are used. the properties of
magnetism to store
data.
Secondary storage is a category of storage that is not directly accessed by the CPU.
optical storage: a
This means that data and instructions need to be sent from secondary storage into
type of secondary
primary storage in order for it to be processed. Secondary storage is also a type of
storage that uses
non-volatile storage. Can you remember what this means? There are three main types
lasers to store data,
of secondary storage, these are magnetic, optical and solid-state storage.
solid-state storage:
Magnetic storage relies on the properties of magnetism to store data. A modern
magnetic storage device normally has circular plates called platters that spin to allow a type of secondary
storage that uses
data to be read and written. The platters are separated into tracks and sectors. It has
transistors to store
a read/write head that moves across the platters to read or write the data. It uses an
electromagnet to magnetise dots on each platter that store the data. If a dot is data.
magnetised it stores the binary value 1. If a dot is demagnetised it stores the binary
value 0. Each platter has billions of these magnetised dots. An example of this type
device is called a hard disk drive. REFLECTION
After completing
ACTIVITY 3.7 Activity 3.7:
You have just learnt that a hard disk drive is a type of magnetic storage and What kind of search
how it operates. There are older types of magnetic storage called magnetic data did you use to
tape and floppy disks. What can you find out about them? find out the data for
the activity? Do you
Can you also find out what the largest storage capacity is for a hard
think you could have
disk drive?
improved your search
data?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
In 1956, a technology company called IBM sold the first hard disk drive. It had a
storage capacity of just 5 MiB of data and cost $50 000! Thankfully, hard disk
drives have become much cheaper to buy and have a much larger storage capacity
now. Another type of storage that became available to buy around 1982 is optical
storage. People originally thought optical storage would replace hard disk drives,
but soon realised that they could not be made with a high enough capacity to
do this.
Optical storage uses lasers to read and write data to and from a circular disk. The
disk spins and a read/write heads moves across the surface to allow data to be read
or written. To write data, a laser burns pits into the surface of the disk. These pits
are organised in a spiral track that starts at the centre of the disk. The surface of the
disk between each pit is called a land. A laser is also used to read the pits and lands
to obtain the data that they store. Examples of optical media are a CD, DVD and a
Blu-ray. Two of those examples are read using a red laser and one is read using a blue
laser, can you guess which is which?
ACTIVITY 3.8
Although optical storage is still used today, it is mostly used to archive data or as a
cheap way to physically distribute files to users that require them. They didn’t replace
hard drives in the way that it was first thought they would. As portable devices
developed, people began to realise there was a disadvantage with hard disk drives.
This disadvantage came from the fact that they have moving parts. This made them
vulnerable to wear and tear and also damage if they were dropped. As a result, a new
type of storage was developed called solid-state storage.
Solid state storage doesn’t have any moving parts. Instead it is created using
semiconductor chips. Solid-state storage is sometimes known as flash memory. This
is because of the ways that the data is read and written to the chips, it is said that it
is ‘flashed’ onto them, but how does that happen? Solid state storage contains
cells and transistors that are laid out in a grid. The transistors can be wired together
in two different ways. In a NOR flash structure, the cells are wired together in a
parallel structure. In a NAND flash structure, the cells are wired together in series.
The intersection of the rows and columns of transistors are the cells. One of the
transistors is called a control gate and one of the transistors is called a floating gate.
The control gate sits on top of the floating gate. When a solid state storage device is
first created, all the transistors are set to the binary value 1. The electric current
reaches each control gate and then flows through to the floating gate to be stored.
When data is stored in a transistor, it is converted to the binary value 0. A solid
state drive is one example of a solid state storage device. You probably use another
KEY WORD
example on a regular basis too, it’s called a USB flash memory drive (also known as
USB stick, memory stick or a thumb drive). semiconductor
chips: an electronic
circuit, where
transistors are set
on a semiconductor
material, such as
silicon.
3 Hardware
Organisations have a growing need to store more and more data. This data
is often vital to the operation of the organisation. Data storage development
companies are constantly trying to develop storage devices that have larger
storage capacities. Due to this need, researchers have started to look at other
methods of data storage including a revolutionary method called holographic Figure 3.12: A USB flash
data storage. This type of data storage would allow approximately a terabyte memory drive
of data to be stored in a single crystal that is about the size of a grain of sugar.
KEY WORDS
Four pages of data are sent to RAM There is only space for 3 pages in RAM.
Page C isn't immediately needed
Figure 3.13: Pages of data are transferred to the virtual memory so that RAM doesn't become full
If the RAM became full and the computer did not have the ability to transfer pages
of data to the virtual memory, this could cause it to crash, as it may not be able to
complete the task it is currently working on.
Despite a common misconception that many people have, cloud storage does not store cloud storage: data
our data somewhere up in the clouds. So how did it get that name? It is more in relation storage that is owned
to the very large collections of data that are stored being like clouds of data, think by a third party and
clouds of millions of raindrops! accessed by the user,
using the internet,
As technology has developed, and continues to do so, people have found that they want
and need to store larger amounts of data, and data storage is quite expensive to buy, server: a component
keep and maintain. that acts as a central
You might be able to make sure that your 2 Terabyte hard drive at home is safe in your resource for the
house and is checked regularly for security issues, but it’s likely you only have a relatively storage of data and
small amount of data to store. Some multinational businesses have huge amounts of applications or for
data to store. This can require large rooms that are needed to house expensive hardware, providing a service.
such as computer servers, to store all the data that the company requires. This could be
the details of millions of their customers and all the online transactions they have made
to buy products. They would also need staff to maintain this equipment and keep that
data safe. These kinds of costs could amount to many thousands of pounds a year for a
business. Therefore, cloud storage offers them an alternative.
70 >
3 Hardware
Cloud storage companies created a service in which they set up very large buildings
that house and maintain thousands of computer servers. They spend 24 hours a day
making sure the servers are maintained and secure. A company can then pay a fee
to the cloud storage company for their service, to be allowed to store their data on
their servers and pass the responsibility to the company to keep it secure until it is
required. The company then accesses this data, when it is required, using the internet.
Cloud storage is a collection of third party hardware (hardware
that is owned by another person or organisation), such as
computer servers, that individuals and companies can use to store
data, and for a range of other services. When data is stored within
the buildings and hardware owned by the individual or business,
this is known as storing the data locally. When data is stored in
hardware owned by a third party and accessed using the internet,
this is known as storing data remotely.
Cloud storage began as a simple way to offload the responsibility
of storing data. Since it was first used, it has developed into use
for other services. For example, a business can now use cloud
storage in connection to its website. The cloud storage company
can offer a service whereby when demand is high for a website, such
as they have a big sale, then they can use cloud storage to extend
the capabilities of the web servers to be able to process the large
amounts of data and requests that are being sent to the website.
This means that the company can use hardware they do not own, on
occasions when the demand for their business is high. This means
they do not need to own all the hardware used, and have the extra
hardware not being used, and therefore wasting money for them, Figure 3.14: Data can be stored in cloud storage
when their business demand is lower. Helpful for business costs!
Individuals are making increasing use of cloud storage. This allows portable
devices to remain fairly small, as they do not need to store very large amounts
of data locally within the portable device, e.g. their mobile phone. Companies
such as Microsoft also offer access to software using cloud storage now,
e.g. Office 365. This means that people do not need to download large
software applications onto their portable devices.
Some people do have concerns about cloud storage. They think it is a big risk
to give someone else the responsibility for looking after their data. Table 3.3 gives
comparisons of some advantages and disadvantages of storing data in the cloud and
storing it locally.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Within your computer or device is a piece of hardware called a NIC. This may be
a wired or wireless NIC. This means that either a cable will be plugged into the
hardware to connect to a network, or it will have a
wireless component that allows it to make a wireless
connection. Most modern NICs are
wireless NICs (WNICs).
Each NIC is given an address called a media access control (MAC) address. media access control
This address can be used to identify a device on a network. (MAC) address: the
unique address that
A MAC address is assigned by the manufacturer and is never normally changed. It will
is given to a NIC by
remain assigned to the device whilst it is in use. A MAC address is made up of two main
the manufacturer.
parts. These are the manufacturers ID code and the Serial ID code for the device. This
creates a unique address for each device. The address is represented as hexadecimal and
normally has six pairs of numbers, separated with either a dash or a colon, for example:
34:4D:EA:89:75:B2
When a device with a network interface card transmits data across a network, it will
send the MAC address of that device with the data. This means that it is possible to
tell, from inspecting the data, which device on the network the data was sent from.
When data is sent across a network, a hardware device can be used to make sure that
the data arrives at the correct destination. You can use a hardware device called a router
to do this. Will a router have a NIC? Does this mean it will have a MAC address? See if
you can find out! Each device that wants to connect to the internet will also need to do
this by connecting to the router. This could be a wired or wireless connection. KEY WORD
A router is a hardware device that reads each data packet that it receives. Details about data packet: a unit
data packets and their structure was covered in Chapter 2. The router reads the data of data that is used to
packets to find out the destination of the data. It can use the MAC address to do this, transmit data across a
network.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
but that will normally only be used if the data is sent to another device that is part of
the same local network (this is a network that is contained within a specific area, such
as your house). As a router is also used to connect a device or a local network to the
internet, it is the internet protocol (IP) address of the destination device that is
normally read and used to forward the data to its correct destination.
This IP address can also be used to locate your device on a network, and it is also a unique
address. It is different in structure to a MAC address, as it is assigned by the network,
rather than by the manufacturer. In a local network, such as a home network, it is often
the router that assigns the IP address to a device, when it is connected to the router.
An IP address can have different structures, such an IPv4 or IPv6 structure. IPv4 was
the first structure created for an IP address. This structure was created back in 1983 and
uses 32-bits to create each numerical IP address. Even though it is now an old structure,
there are still many devices that have an IPv4 address. An example of an IPv4 address is:
12.244.233.165
As more and more devices started connecting to networks, the number of available
IPv4 addresses started to rapidly decline. As each IP address needs to be unique to the KEY WORDS
device, they were rapidly running out, due to the number of devices worldwide. IPv6
was created as result, to create more available IP addresses. IPv6 uses 128-bits to create static IP: an IP
an IP address. IPv6 addresses can also contain hexadecimal characters. This created address that does not
much more possibilities for IP addresses and allowed them to remain unique to the change each time the
device. An example of an IPv6 address is: device connects to a
network.
2001:0db8:0000:0000:0000:ff00:0042:7879
dynamic IP: an IP
You will also notice that an IPv4 address is separated by full stops, but an IPv6 address
address that can
is separated by colons.
change each time the
An IP address can also be either static or dynamic. Most devices are assigned a device connects to a
dynamic IP address. This means that the address can change each time the device is network.
connected to a network. The device may be given that IP address for a single session
3 Hardware
that it connects to the router, or it may be given it for several sessions before it changes,
but it will change at some point. It is possible to obtain a static IP address for your
device. This means that the IP address for your device will be the same every time that
you connect your device to a network, it will not change, until you request it to be
changed, it will always remain the same. It is normally your Internet Service Provider
that will provide you with a static IP address for your device.
ACTIVITY 3.12
Can you find out what kind of devices a static IP address is normally used for?
Can you also find out what the benefit is of having a static IP address?
SUMMARY
Hardware is all the physical components that you can see and touch in a computer system.
The CPU is the component in a computer system that processes all the instructions and data.
It uses an instruction set to do this.
The CPU has several component parts, these include the ALU, CU, PC, MAR, MDR, CIR, ACC and buses.
The CPU is responsible for carrying out the fetch-decode-execute cycle.
The number of cores, the clock speed and the cache size can all affect the performance of the CPU.
Computers also need input and output devices to be able to provide a system with data, then obtain the results
when it has been processed.
Sensors are a type of input device that can be used to capture data from the immediate surrounding environment.
A computer has both primary and secondary storage.
Primary storage is directly accessed by the CPU and consist of RAM and ROM.
Secondary storage is not directly accessed by the CPU and there are three types, magnetic, optical and solid-state.
Virtual memory is created by portioning part of the hard drive. It is used when RAM is full.
Cloud storage is when data is stored remotely on servers and storage that is owned and maintained by a
third party.
A network is created when two or more devices are connected.
A device needs a NIC to connect to a network. Each NIC has a MAC address.
A router is used in a network to forward packets of data to their correct destination.
A router can assign an IP address to each device.
There are two types of IP address, IPv4 and IPv6.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
EXAM-STYLE QUESTIONS
a i Identify the name of the component where an instruction is stored identify: name I
immediately before it is fetched into the CPU. [1 ] select I recognise
ii Identify the name of the component that stores the address of
describe: state the
the next instruction that will be processed. [1 ]
points of a topic I
iii Describe what happens at the decode stage of the cycle. [3] give characteristics
b The computer has a 2 GHz single core processor. The students wants to and main features,
improve the performance of the computer by replacing the CPU.
explain: set out
The student selects a new CPU that is a 3.4GHz dual core processor. purposes or
i Identify how many cores are in the new CPU. [1 ] reasons / make
ii Explain why the performance of the new CPU would be better. [2] the relationships
c The computer has both random access memory (RAM) and read between things
only memory (ROM). evident I provide
why and/or how and
i Identify if these are examples of primary or secondary storage. [1 ] support with relevant
ii State what each of these components store. [2] evidence.
[Total: 11]
state: express in
2 Give the most appropriate sensor for use in each of the given clear terms.
scenarios. A different sensor must be given for each scenario. [3]
give: produce an
Scenario Most appropriate sensor answer from a given
To monitor the amount of pollution in
source or recall /
a river. memory.
3 A small business uses optical data storage to archive their customers’ data.
a i Give two examples of optical storage. [2]
ii Describe how data is stored on optical storage. [6]
b The business currently has a local archive for their data. They are
considering storing their customer data in cloud storage instead.
i Give one advantage of storing the customer data in cloud storage,
rather than local storage. [1 ]
ii Give two disadvantages of storing the customer data in cloud
storage, rather than local storage. [2]
[Total: 11]
4 A computer connects to the internet and is assigned an IP address.
The IP address has an IPv4 structure.
Describe the structure of an IPv4 address. [2]
3 Hardware
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
Software
GETTING STARTED
Work in pairs to make a list of all the different pieces of software that you
have used. Can you think of a way to categorise these pieces of software?
For example, by what they do or how they are used?
As a class create a mind-map of the different programming languages that
you have used, or come across. Discuss whether any of these have specific
uses, or do they allow for any type of program to be written?
Computers need software to allow the user to do something useful. You will use software: a series of
software each time you use a computer, whether this is a PC, a laptop, tablet or mobile instructions written
phone. Software is a series of instructions that tell the computer what to do, created in a programming
using programming languages.. language that
performs a function,
system software:
a type of software
Figure 4.3: System software manages the running of hardware; application software runs on
that manages the
top of system software hardware and software
in a computer.
Software can be put into different categories, depending on their purpose and use operating system
(Figure 4.3 shows the link between hardware and software). (OS): a program
System software manages the running of the hardware and other software, and allows
that manages the
communication between these components. These are tasks that help the computer
computer, allows the
user to communicate
perform its functions and improve or maintain its efficiency. Two types of system
with the computer,
software are the operating system (OS) and utility programs.
and allows software
Examples of utility programs are not required but useful to know. These are programs to be run.
that maintain the computer system, for example:
utility programs:
• System clean-up-searches for and removes un-used programs and data. system software that
• Defragmentation-rearranges files so that they are located together (contiguously) performs house
and that the free spaces is located together. keeping activities.
Application software allows the user to perform a task - it provides the services for the application software:
user, for example, write a letter, view a website, etc. software that allows
the user to perform a
Application software have generic names, as well as the brand names. It is important
useful task.
that you know the generic names, some of the common ones are:
word processor: a
• A word processor allows the user to create written documents.
type of application
• A spreadsheet allows the user to perform calculations on data. software that
• A database allows the user to store and search a set of data. allows the user to
create text-based
• A web browser allows the user to view and navigate websites. documents.
spreadsheet: a
type of application
software that performs
calculations on data,
database: an example
of application
software to store and
manipulate data.
web browser: a piece
of software that
retrieves and displays
web pages.
4 Software
The application software cannot run on a computer without an operating system. KEY WORDS
The operating system cannot run unless there instructions given to it, these are
provided by the firmware. The firmware cannot run unless it is told to run, this is firmware:
done using the bootstrap program, which is loaded when the computer first turns on. instructions that are
This process can be represented as shown in Figure 4.5 on the right. stored in the ROM
and are loaded when
ACTIVITY 4.1 the computer starts,
Log onto a computer, tablet or mobile phone. Make a list of the different bootstrap: the first
types of application software that are installed. Remember not to use commands loaded
brand names. when a computer
starts, it checks
hardware and loads
the firmware.
Providing an interface
KEY WORDS
The OS allows the user to enter data, and outputs data to the user, all through the
interface. There are different types of interface: interface: the
• Graphical 1 ser Interface (GUI) has windows, icons, menus and pointers (WIMP). method by which a
It is what you will be familiar with from PCs, mobile phones, etc. This is most user communicates
with a computer.
useful for novices because it is often intuitive. An example is Windows.
• A command line interface requires the user to enter text as commands. This is most Graphical User
useful for expert users because the commands entered must be exact. An example Interface (GUI): a
is Linux. type of operating
system that includes
• A natural language interface allows the user to enter any text commands, or speak windows, icons,
commands. The OS then analyses what has been entered and performs the action. menus and pointers.
command line
interface: a type of
operating system
where the user types
commands.
natural language
interface: a type of
operating system
that allows the user
to type or speak
commands.
Figure 4.6: A Graphical User Interface Figure 4.7: An image of a command prompt
who made it - not the developer of the OS. This means that it may not be compatible
KEY WORD
(for example, it may use a different interpretation of binary). A driver is software that
translates data from the computer to the peripheral, and vice-versa. The OS allows the driver: a program
installation of these drivers and the sending of data to and from it. that controls a
device, for example,
a printer or a
Managing memory keyboard.
A computer uses memory to store data. This can be using
secondary or primary memory.
The OS manages the movement
of data to and from hardware,
primarily RAM. It also checks
the processes being carried out
and makes sure that they have
enough memory allocated to
perform their function. The OS
will also make sure that two
processes do not try and access
the same memory location.
Managing multitasking
A single processor can only ever execute one instruction at a time. The processor
does this so fast that it appears to be doing several tasks at once. For example,
you might be listening to music from a computer, typing a document into a word
processor, and the computer is outputting what you are doing. The OS allows this
to happen by deciding which processes should be executed next and how long they KEY WORD
can spend being processed before switching to another process. The OS does this
using interrupts. interrupt: a signal
sent to the processor
to tell it that its
Managing interrupts attention is required.
An interrupt is a signal sent to the processor to tell it that something needs its
attention. The OS decides which interrupt to run and then performs the actions
required. There is more about interrupts in Section 4.3.
4.3 Interrupts
An interrupt is a signal to the processor to tell it that something needs its attention.
An interrupt can be software or hardware based. Table 4.1 has several examples
of each.
Software Hardware
Division by 0. Data input, e.g. key pressed on a
keyboard, mouse click.
Two processes attempting to access Error from hardware, e.g. printer out of
the same memory location. paper.
Program request for input. Hardware failure.
Output required. Hard drive signal that it has read data.
Data required from memory. New hardware device connected.
Table 4.1: Interrupt examples
Questions
1 Give two examples of application software.
2 State the purpose of system software.
3 Describe the relationship between application software and the bootstrap.
4 Identify three tasks the file management of an Operating System can perform.
5 Give two examples of software interrupts, and two examples of hardware interrupts.
6 Describe the process that happens when an interrupt is sent to the processor.
4 Software
ACTIVITY 4.2
Choosing a language
High- and low-level languages have their own benefits and drawbacks. Some of these
are shown in Table 4.2.
Questions
7 Describe what is meant by a high-level language.
8 Three examples of program code are given. Identify whether each example is a
high-level language, assembly language, or machine code.
• If it is, it executes the statement and moves to the next. compiler: a translator
that converts a high-
Interpreters are most useful when writing the program, because it will stop at an error, level language into a
allow you to correct it, and then continue executing from the same position. low-level language.
Interpreters are not as useful for whole-system testing, or when the program is It checks all code
complete. This is because all of the code needs to be interpreted every time the before running the
program is run, even if there are no errors. program.
A compiler checks all the code, by going through one-line after the other. If there are executable file: a
any syntax errors, they are all reported to the user and the program is not executed. file produced by a
If there are no errors, then an executable file is created. An executable file uses compiler that can be
intermediate or object code derived from the high-level language code. The actual run independent of
program code is not included so if someone has the executable file, they cannot view or translator software
amend the original code. The executable file can be run without having to re-translate and does not include
the code. the source code.
Compilers are useful when you have finished the program or need to test a working
element repeatedly. This is because the code does not need to be translated each time,
the executable file is run repeatedly.
Table 4.3 shows the comparisons of interpreters and compilers.
Interpreter Compiler
Translates one line of code into machine code and Translates all lines of code into machine code, before
then executes (runs) it. executing the program.
Reports a syntax error as soon as it is picked up, and Reports all syntax errors at the same time, the
stops the program running until corrected. program is not run until all errors are corrected.
Useful when writing a program. Useful when a program has been finished and is ready
for testing or distribution.
Code needs to be re-translated each time the Code does not need re-translating each time the
program is run. program is run.
Does not produce an executable file. Produces an executable file.
Source code is required to run the program. Source code is not required to run the program, only
the executable file.
(continued)
4 Software
Interpreter Compiler
Interpreter software is required to run the program. No other software is required to run the executable file.
You can test part of a program without completing You need to have finished a section of code before
it all. testing it.
Examples:
Saria is writing a computer game program that allows a character to move through
different worlds collecting coins.
Which translator should Saria use when writing the code?
• It is more appropriate to use an interpreter. This will allow her to see when an
error is identified, correct it and then continue running the program from the same
position.
• A compiler can be used, but then all the errors would appear at the start and she
would need to correct all of them before seeing how any of her program runs.
• An interpreter is considered more appropriate, but you could justify the use of a
compiler in this situation.
Which translator should Saria use once she has finished programming the computer
game and wants to sell it to users?
A compiler should be used, because she can produce an executable file.
There should be no syntax errors at this point, so correcting the code line-by-line is
not required. The executable file can be distributed to people and they can then run
the program without need to retranslate the instructions every time. The executable
file also means that no-one will be able to see her code, so it is protected.
An interpreter would not be an appropriate choice here, because the end user
would need the interpreter software and the source code, and will need to wait for
it to be interpreted each time. It also means the users can access the source code,
and then copy it or change it.
ACTIVITY 4.3
Write a computer program in a language that uses an interpreter, and one that
uses a compiler. You might need to use a different programming language for
each one. For example, Python usually has interpreters, whilst VB.NET and
Java usually have compilers. Which translator did you prefer to use?
Peer Assessment
Discuss the reasons why you preferred the translator you chose. Did anyone
give you some reasons that you hadn't thought of? Can you expand your own
answer any further?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
JUSTIFYING CHOICE
In an exam you may need to make a decision and then justify your choice. To
answer this type question you will need to consider the context of the question and
how each of the possible choices will impact the context. When you are justifying
your decision you need to relate every reason back to the scenario.
Consider the choice of translator.
• An interpreter is most useful during the development of a program because:
KEY WORDS
• you can fix errors in real time
Integrated
• the program will stop at each error to allow you to fix it
Development
• you can run small sections of the program when incomplete. Environment (IDE): a
• A compiler is most useful when a program is complete because: piece of software that
allows a user to write,
• it produces a .exe file test and run program
• the program does not need to be interpreted each time it is run code.
• the program can be distributed without the source code. editor: a feature of
an IDE that allows
Questions the user to enter
Saria is writing a computer program. and amend program
code.
1 Why is it more appropriate for Saria to use an interpreter while writing a program?
2 Why is it more appropriate for Saria to use a compiler when the program is auto-completion:
complete? a feature of an
editor that gives the
user options when
they start typing a
4.6 Integrated Development command.
An IDE can also provide debugging features, or error diagnostics, these help you find
the problems in your code. Some examples are:
• Break points; the user sets these points and the code stops running on that line.
This lets you check the values and output from the code to that point.
• Variable watch window; the values of the variables are displayed while the code is
running, so they can be checked whether they are correct.
• Stepping; the program will run one line at a time, and the user has to tell the
program to move on to the next line, so it can be checked line by line. REFLECTION
You can write and run programs without an IDE. You can write your code in a basic After completing
text file without any formatting, and then run it (usually) through a command line Activity 4.4, it can be
interface by entering the correct instructions. An IDE is much more user friendly, helpful to think about
with lots of tools to help you write, amend and correct your code. how you approached
it and ways you
COMPUTER SCIENCE IN CONTEXT could improve your
research skills for
You may not always get a choice of whether to use an interpreter or a future activities.
compiler. If you use an IDE (Integrated Development Environment) it will
probably come with one, or the other. If your IDE has an interpreter and you 1 Discuss how you
want to make an executable then you might need to download another IDE to approached the
compile it. investigation
of the features.
Did you test out
the features,
ACTIVITY 4.4 or search the
Open up the IDE that you use to write programs. Identify the features that are internet to
mentioned in this chapter. Are there any different ones? If so, find out what find out what
these do. they did? Do
you think your
approach
was the most
Questions appropriate?
10 Name three types of translator. Would you try a
11 Nasrat is writing a program in a high-level language that she wants to sell to make different way if
money. Identify when Nasrat could use an interpreter, and when she could use a the activity was
compiler. Justify your decisions. repeated?
12 Describe two features of an IDE that help the user to test the program they Discuss how
have written. this activity has
helped you
SELF ASSESSMENT to identify the
features. Does
Question 11 required you to justify your choice. Did you give generic points, practically using
or did you relate each point you made to the scenario in the question? them help you to
When a context is given, always try and go back to the question each time. remember them?
y CAMBRIDGE 1GCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SUMMARY
EXAM-STYLE QUESTIONS
1 Tick one box in each row to identify if the software is an example of system
software or application software.
CONTINUED
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
The internet
and its uses
learn what the difference is between the internet and the world wide web
understand what is meant by a URL and study the purpose of each of its component parts
discover the purpose and operation of the hypertext transfer protocol (HTTP) and the hypertext transfer
protocol secure (HTTPS)
learn about the different functions that a web browser performs, including the use of cookies
discover how web pages are requested, retrieved and displayed on your computer or device
understand what is meant by a digital currency and how blockchain is used to track digital currency
transactions
learn about a range of cyber security threats and how a range of different solutions can be used to
data safe from these threats.
5 The internet and its uses
GETTING STARTED
Think about what you already know about keeping yourself safe on the
internet (e-safety). Create a poster for a younger audience to tell them how to
use the internet safely and what to do if they find something that upsets them.
On average, there are approximately 2500 cyber security attacks that happen each day.
Malware is used in many of these attacks and over 90% of this malware is delivered using email.
WannaCry is the name of a large scale cyber
security attack that occurred in 2017. Malware was
used to take over computer servers in systems
across Britain, Spain, Russia, Ukraine and Taiwan.
The type of malware used in the WannaCry attack
is called ransomware. The malware blocked
users and organisations from accessing files and
accounts. It did this by encrypting the tiles. It
wanted the organisations to pay money to the
creators of the malware in order to be able to
gain access to their files and accounts again. The
payment demanded was in Bitcoin.
As organisations were not able to gain access
to their files and accounts until the ransom was Figure 5.2: Malware prevents users from accessing their
paid, mass disruption was often caused to the files and data
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
daily processes in these organisations. One example of this was the National Health Service (NHS)
in Britain. British hospitals were forced to turn away some patients who could not be treated until
their personal information could be accessed again.
WannaCry malware was based on a set of malware code called EternalBlue. There have been
several malware attacks since WannaCry based on this same EternalBlue code.
Discussion questions
1 Do you think it is the organisation's fault that the malware infected their systems and caused issues?
2 Do you think it is completely the hacker's fault for being able to put the malware on the systems?
3 How would you feel if your files were encrypted and you couldn't access them?
Would you pay the ransom, or would you take a different action?
The world wide web was invented by Tim Berners-Lee in 1989. He was
motivated to do so by a problem that he had. He is a Computer Scientist
and found that at the time he had several computers that all had different
information stored on them. He found that he would have to keep logging
onto the different computers to obtain the particular information that he
needed. He saw a way to solve this issue that he realised could be used
universally. Lots of computers were already being connected together
into networks and he realised that he could share information using an
emerging technology at the time called Hypertext. By October of 1990 he
had developed the three fundamental parts that create the world wide web:
HyperText Markup language (HTML), uniform resource locator (URL) and the
Hypertext Transfer Protocol (HTTP). By the end of 1990, the first web server
was set up and the first web page displaying information about the world
wide web project was created.
ACTIVITY 5.1
Have a look at what the first web page looked like. Type 'the world wide web
project' into your browser and look for the 'info.cern' link.
KEY WORDS
uniform resource
locater (URL):
another name for the
text-based address
tor a website.
web browser: a
Figure 5.4: HTML piece of software that
retrieves and displays
web pages.
Web browser
renders the HTML Data for web page KEY WORDS
and CSS and runs
the active script to hypertext transfer
display the web protocol secure
page (HTTPS): a secure
Figure 5.7: The web browser requests a web page and renders the HTML and CSS version of the HTTP
that encrypts data for
transmission.
encryption: a
Questions method of securing
1 What is a URL? data for storage
2 What is an IP address? or transmission
3 What are the three main parts of a URL?
that scrambles
it and makes it
meaningless.
Another protocol can be used to request the data for the web pages that will require an
additional process to take place. This protocol is the hypertext transfer protocol secure digital certificate:
(HTTPS). This protocol has an additional layer of security that encrypts any data that a certificate that is
is transferred. It involves the use of digital certificates. This is a certificate that the awarded to a website
owners of the website need to apply for from a certificate authority. A certificate if they can prove
authority is an organisation that checks whether a website is authentic and trustworthy. that they are a real
If the certificate authority believe the website is authentic, they will issue them with a organisation and take
digital certificate. This is how the additional layer of security is created. measures to securely
transmit their data,
• Before the web browser sends a request to the web server to ask for the web pages,
it sends a request to the web server asking it to provide a digital certificate. certificate authority:
the awarding
• The web server sends a copy of the digital certificate to the web browser. organisation that
• The web browser checks if the digital certificate is authentic. checks if another
organisation is real
• If the certificate is authentic, the web browser will allow communication to continue
and secure before
with the web server and any data that is transmitted between the two is encrypted.
awarding them a
• If the certificate is not authentic, the web browser will report that the website is digital certificate.
not secure.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Web browser
authenticates the Digital certificate sent
certificate. If
authentic, encrypted
data transmission
Figure 5.8: A web browser requests a digital certificate to allow encrypted data transmission
KEY WORDS
The HTTPS protocol is the standard HTTP protocol with a layer of security
combined, that is either the secure sockets layer (SSL) or transport layer security (TLS) secure sockets layer
protocol. TLS is a newer version of SSL. This is the protocol that is used to create the (SSL) protocol: a
encryption. You can check visually whether a website is secure by seeing if it uses the type of protocol
HTTPS protocol. If it does, you will see this at the start of the URL in the address bar that encrypts data
in the web browser. You will also see a small padlock before the start of the URL. for transmission. It
Most web browsers also have an option for you to view the digital certificate for the is the protocol, that
website. This is often found by right clicking your mouse on the padlock. is combined with
the HTTP to create
ACTIVITY 5.2 HTTPS.
Use the internet to research why the TLS protocol was developed to replace transport layer
the SSL protocol. security (TLS)
protocol: an updated
version of the SSL
protocol.
Questions render: the method
4 What is a digital certificate and how is it used in the HTTPS protocol? of processing all the
5 Does the web browser or the web server authenticate the digital certificate? web page data, such
as HTML, to display
the web page.
produce search engines too. One example of this is Google. Google produce a search
engine called google, that you can use to find information on the world wide web,
however this is not a browser. The browser that Google produce is Google Chrome.
This is the software that allows you to open web pages, such as the google search
engine. Why don’t you test your friends and see if they know the difference?
KEY WORDS
Did you know that there are lots of other things that a web browser can do? tab: a website
This is a list of some of the main functions of a web browser, how many have you function that allows
used before? you to open multiple
web pages in the
• It provides an address bar that you can use to type in a URL. same window.
• It keeps a record of all the web pages that you have visited.
window: a viewing
This is called user history.
area that is created
• It allows you to bookmark web pages and set web pages as your favourites. in which a software
These can then be displayed on the toolbar of your web browser to allow you application or file can
to access them much more quickly. It means you can just click the bookmark or be opened.
favourite icon and it will take you straight to the web page.
navigate: move
• It allows you to open multiple tabs at a time. The browser itself opens around web pages, or
into a window on your computer. Without tabs, you would need to open move back or forward
multiple windows if you wanted to open more than one web page at a time. to previous web
Tabs allow you to open multiple web pages in the same browser window which pages.
makes it easier to navigate between the different web pages that you have open.
cookie: small text file
• It allows you to navigate between web pages. The buttons that are most
that is used to store
commonly available on a web browser are forward, back and reload the page. personal data, by a
• It stores cookies and manages the process of transmitting them. web browser.
You will learn more about cookies next!
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Cookies! Sadly, not the tasty kind, but a useful function of a web browser. So, what
exactly is a cookie? A very simple explanation is that it is a small text file that is used to
store data, normally about you.
They are very useful as they can store data that you may regularly use on the
internet. This means that you do not need to enter this data every time. Examples of
this are:
• Storing your username and password for accounts such
as your social media.
• Storing your bank card details for buying products and
services online.
• Storing products in a virtual shopping cart when
you are buying multiple products from an online
company. It can also save the items in your cart so that
you can buy them at a later date if you don’t want to
buy them now.
Cookies can be used to tailor your online experience with
websites. Some websites allow you to format the website
in the way that you want it to look, for example, changing
the colour of text and boxes that appear on the web page.
Cookies can also be used to track the different content that
you look at on the world wide web. For example, if you
look at web pages about your favourite hobby or interest,
you will find that advertisements appear on web pages that
are about your favourite hobby too. This is called targeted Figure 5.12: Many websites use cookies
advertising.
5 The internet and its uses
Cookies are created when you visit a web page and then they are stored by
KEY WORDS
your web browser. There are two main types of cookie, session cookies and
persistent cookies. session cookie: a
Session cookies are temporary files that are created when you visit a web page. As type of cookie that
soon as you close your web browser, these cookies are deleted. If you open your web is deleted when
browser again and go back to the same web page, the web page will not recognise the web browser is
you. That means that it will not be sent any cookies by your web browser, about closed.
your personal details or preferences, as this type of cookie are not saved by the persistent cookie: a
browser once it is closed. You might have experienced this type of cookie when you
type of cookie that
are online shopping. You may have added several items that you wanted to buy
is stored by the web
to a shopping cart on a website, you then close your web browser. You then open
browser until it is
your web browser at a later date and go back to the web page, only to find that the
deleted by the user
items you put in the online shopping cart are no longer there. This is because it is a
or because it has
session cookie that is used to temporarily store them. This process is summarised in
expired.
Figure 5.13.
Persistent cookies are permanent files that are created when you visit a web page.
These are stored by your web browser onto the hard drive of your computer.
When you visit the same web page again, the cookie file is sent back to the web
server that stores the web pages to provide the data about your personal details
or preferences. This will allow your login details to be automatically entered, for
example. These cookies will remain stored on your hard drive until you manually
delete them, or your browser deletes them because they have expired. Each
persistent cookie file is sent with an expiration date. When this expiration date is
reached, the web browser will delete this cookie from your hard drive. This process
is summarised in Figure 5.14.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Persistent cookies
are permanently
stored by user's
web browser until
the user or the
web browser
deletes them.
Questions
6 What is a cookie used for?
7 What is the difference between a session Figure 5.15: Cookies can be a privacy concern
cookie and a persistent cookie?
8 Why do some people have an issue with
cookies being used?
Each company that creates a web browser will often have a slightly different
aim as its focus. Some web browser development companies focus on the
security of the transmission of data, whereas others focus on how quickly the
web pages are rendered and displayed.
5 The internet and its uses
Figure 5.16: Digital currency exists electronically and can be sent between computers
ledger is also encrypted. This prevents anyone being able to change the data.
However, anyone who wants to view the data in the digital ledger is able to do so.
Payment 1
Payment 2
User sends payment The payment arrives
using a type of digital Payment 3 with the intended user
currency called a and only exists
cryptocurrency. The electronically.
data is encrypted
before it is sent.
The details of the payment are added
to digital ledger, including a digital
signature, time and date stamp. The
data is stored for the digital ledger is
encrypted and cannot be changed.
Figure 5.18: A blockchain keeps a digital ledger of transactions
There are as many as 2000 different digital currencies that exist. Many of these
are different types of cryptocurrency. How many do you think you could name?
software program that will automatically cycle through many different combinations
until the correct one is found.
The perpetrator usually does this to gain access to your computer or account in the hope
that they can either steal some personal data that they can use for criminal activity,
or they may try to use your account to purchase items online as though it was their
own account.
There are several cyber security solutions that you can put in place to help prevent
a brute-force attack on your computer or account. The first is to make sure that you
have a strong password to protect your data. A strong password is created by mixing
different uppercase and lowercase letters, numbers and symbols. Ideally mixing these
in a way that does not form any kind of word or phrase. A long string of a mixture of
all these characters is the best protection that you can give your data. This will make it
much more difficult for any perpetrator or software program to guess your password.
It can be easy to find out some simple information about you, for example, that you
have a rabbit called Mr Snuffles. Therefore, if your password is mrsnufflesO 1, this is not
going to be difficult for a perpetrator to guess. Make life a bit more difficult for them,
your data is precious! An example of a strong password is:
1 gH6dk@dnlwm!dosTsjlpa
Many web browsers now have a function that will suggest a strong password for you,
mixing a combination of characters like this. They will also save the password for you,
so you don’t need to keep remembering the string of characters.
Another security solution that can be used to help prevent a brute-force attack is
limiting the number of times a password can be entered before the account is locked.
You may have had this issue before. You type in what you think you had as a password
for the account, but it is rejected, so you try another and that gets rejected, then you try
a third one and that is rejected, and you now get a message saying you are locked out
of your account. How frustrating! However, be very thankful for this security solution,
however annoying it can be. It is likely that for a perpetrator to brute-force their way
into your account, it will take more than three guesses at your password. Therefore, if
the number of attempts is limited before the account is locked, this can prevent many KEY WORDS
guesses being made to try and find out the password.
biometric password:
A third security solution that can be used is a biometric password. A biometric device is a type of password
one that needs your biological data to be input. An example is a fingerprint scanner, that uses a person's
which requires your fingerprint to be input. Our biological data is unique to us, it is biological data, such
highly unlikely that you will find another person that has exactly the same fingerprint as their fingerprint.
as you. Therefore, if you secure your computer or account with a biological password,
such as your fingerprint, no amount of guessing your password would allow a biometric device: a
perpetrator to brute-force their way into your account. They would need to somehow device that allows a
obtain your fingerprint, which is a much more difficult task. user to record and
input a biometric
A fourth security solution that can be used is two-step verification (sometimes known password.
as two-factor authentication). This is a method that puts two tasks in place in order
to enter an account. The first task is entering the password, but then a second step is two-step
added that will require an additional input task to enter the account. The second piece verification:
of data is often a code or word that is sent to you that you will need to enter. This is a process that
normally sent to either your mobile phone number or your email address. This means involves inputting
that a perpetrator will not only need to guess the password for your account, but that two different kinds
they will also need to have access to your mobile phone or your email, this is an added of data to enter an
difficulty. Some banks also have a small card reading device that provide you with the account or device.
data for the second step. You put your bank card into the reader, enters a PIN code
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
or password and this generates the code for the second step for you to input. It is
advisable that you look at the privacy and security settings for your online accounts,
especially ones like your email and social media. Many companies have an option for
you to turn on the feature of two-step verification which helps keep your personal data
more secure.
In summary:
What happens? Multiple guesses are made at your password to try and
break into your computer or account.
What is the aim? To steal your precious personal data or to use your
account to buy products online.
What security solutions A strong password, a limited number of attempts
can be used? at entering a password, a biometric password and
two-step verification.
ACTIVITY 5.4
Think about one of your passwords that you use to access an account online.
How strong do you think that password is? Do you think that you could
improve that password?
Create a three-slide presentation that can be given to your peers to tell them
how to create a strong password and what the importance is of doing so.
Peer Assessment
Take a look at your partner's presentation. Do you think the information is
presented clearly? Have they made it clear how to create a strong password?
Do you think they have missed any information about doing this? Do you think
they have made it clear how important it is to set a strong password? Have
they included information about what might happen if a person does not set a
strong password?
Tell your partner your answer to these questions when you have looked at
their presentation.
The main security solution that you can use to keep data secure that is sent over a
network is encryption. Data is normally encrypted using the SSL protocol that you
learnt about earlier in Section 5.2. This security solution will not stop the data packets
from being intercepted, but it will mean that if the data packets are intercepted, the
data contained in the packets will be meaningless to anyone who tries to read them.
Remember, you can check to see if a website encrypts your data before transmission by
looking to see if the URL uses HTTPS. It is also often possible, in your web browser
settings, to set your web browser to only connect to websites that use encryption to
transmit data.
Have you ever gone into a cafe or a store and thought, ‘Excellent, free Wi-Fi!’ and you
immediately connect to it? Perpetrators can also use this kind of incentive to get you to
connect to the network through a system of theirs. Any data that you send using this
connection can be intercepted by the perpetrator. It is advisable, if you see a free Wi-Fi
connection, to ask the cafe or store if it is their free Wi-Fi before you connect to it.
In summary:
KEY WORDS
What happens? Data packets are intercepted and examined through distributed denial
the use of software such as a packet sniffer. of service (DDoS)
attack: a type of
What is the aim? To steal your precious personal data for criminal cyber threat that
activity such as identity theft or fraud. targets a web server
to cause it to crash
What security solutions Encryption such as the SSL protocol and visually
and prevent access to
can be used? checking the URL of a website to see if it uses the
the web pages that it
HTTPS protocol.
stores.
botnet: a network of
ACTIVITY 5.5 bots that are created
Use the internet to find out how a virtual private network (VPN) can be used to to carry out a DDoS
help prevent data interception. attack.
malware: a type of
malicious software
that is downloaded
Distributed denial of service (DDoS) attack onto a user's
To carry out a DDoS attack, a perpetrator will first create a botnet (bot network, see computer or device.
Figure 5.20). This is done by sending malware to many computers to try and get you to
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
accidentally download it. Once you have downloaded the malware, the computer can
then be used as a bot by the perpetrator. Whilst the bot is not being used it is often KEY WORDS
called a zombie. Once the perpetrator wants to carry out the attack, they ‘wake up’ all bot: the name given
the zombies to be used as bots. Each bot will begin sending multiple requests to access to a computer that
a web server. They are all set to send requests to the same web server all at the same has had malware
time. This floods the web server with too many requests and it begins to struggle to downloaded onto it
deal with each request. The web server can only deal with a certain number of requests that will cause it to
at a time and if it is sent too many it will begin to slow down and eventually crash. be used in a DDoS
This will mean that users can no longer access the website. This causes a denial of attack.
service to any normal requests to access the web server. This type of attack is normally
carried out on a web server, but it could be used to target other types of server and zombie: the name
network hardware. given to a bot that has
malware downloaded
There are several reasons a perpetrator may carry out a DDoS attack. They may
onto it to allow it to
make a demand for money to the company to get them to pay to stop the attack from
be used in a DDoS
happening. They may want to punish the company for something that they perpetrator
attack, but it currently
thinks they have done wrong, such as an unethical issue. This would be in an act of
isn't being used in this
revenge or activism.
way. It is effectively a
The main security solution that a company can use to stop a DDoS attack occurring dormant or sleepingdormant
on their web server is to use a proxy server. A proxy server can be used as a barrier to bot. 休眠的;蛰伏的;
a web server by getting all the requests for the web server to pass through the proxy
server first. The proxy server can examine each request and forward it on to the web proxy server: a 暂停活动的
server to allow access. If the proxy server begins to receive many requests, it can begin method of cyber
to allow them to pass at a slower rate to avoid the web server being flooded with all security that examines
the requests at the same time. This may mean access to the website is slower, but still requests sent by
possible by users that want to legitimately access it. A proxy server can also use a devices to access the
feature called caching. This feature can help prevent a DDoS from being successful as web pages stored on
once the proxy server has received a request the access the website from a certain IP a web server.
address, it will stop any repeated requests for a short period of time from the same IP anti-malware: a type
address. Therefore, if a bot is sending multiple requests, not all of them will be passed of software that scans
onto the web server as some will be stopped by the proxy server. This makes it more a computer or device
difficult for a perpetrator to flood the web server. with the purpose of
As a user, you can try and prevent your computer ever being used as a bot in a DDoS finding and removing
attack by regularly scanning your computer with anti-malware software. This is a type malware.
of software that scans all of the files in your computer to see if any of them are known
to be malware. It does this by comparing each file against a known list of malware to
see if any of the files on your computer match. If it finds a file that matches, it will put
it in a special area called a quarantine area. It will then inform you that it has found
what it thinks is malware and will ask you if you want to delete the file. By scanning
your computer with anti-malware software on a regular basis, you can help make sure
that your computer is free from any malware that might be used to turn it into a bot in
a DDoS attack.
5 The internet and its uses
Botnet
Bot
In summary:
ACTIVITY 5.6
Use the internet to find out about a huge DDoS attack that was carried out on
21 st October 2016, and which companies it affected.
in y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
What happens? A hacker gains unauthorised access to your data by exploiting a vulnerability
in your computer or network.
What is the aim? The aim is to steal, corrupt or leak your data for criminal activity.
What security solutions can A firewall, automatic software updates, strong or biometric passwords and
be used? two-step verification.
5 The internet and its uses
There are several security solutions that you can use to protect against the threat of the
different types of malware. KEY WORD
An anti-virus software can be used to scan your computer for viruses. This is a type of anti-virus: a type of
software that scans all of the files in your computer to see if any of them are known to software that scans a
be a virus. It does this by comparing each file against a known list of viruses to see if computer for viruses
any of the files on your computer match. If it finds a file that matches, it will put it in a with the purpose of
special area called a quarantine area. It will then inform you that it has found what it finding and removing
thinks is a virus and will ask you if you want to delete the file. By scanning your them.
computer with anti-virus software on a regular basis, you
can help make sure that your computer is free from any
viruses. It is also important to update your anti-virus 1100010100110100101010101001001001000101
software. Perpetrators are constantly developing new 110111010010001010101011101010010010110
viruses. The anti-virus software developers are constantly 010001001111010100, ! nnpl0100111010
finding these and update their database used in the scan. 11101010001110001 J 1U1UUU 9010001010
You need to make sure that you are updating your loiioiiioioiuc ni nni nrnioioioo
anti-virus to make sure that the database is up to date 00101001001110 01001010
1110110111010K V I K I IS 00101010
and all the viruses are found.
10100011100011( - ’ <01010101
Anti-malware software can be installed and used to scan 101110101110101 ' 1011 lull 010100100
your computer and network for other types of malware, nooiwu 10101r ’ nnm nMooioiono
such as worms, spyware, adware and ransomware. This nn' OOHlUUlUiiioiooiOOOl
operates in a similar way to the anti-virus software by 01110101001010001001111010
scanning, quarantining and deleting any malware found. 11101010010100100100101001
The anti-malware that looks specifically for spyware is 00110101110111010010001010
called anti-spyware. Figure 5.22: Anti-virus software should be kept up to date to
find any and all viruses
A firewall can be used to help prevent malware being
downloaded onto your computer. The data coming into
and out of your computer can be examined against the criteria set for the firewall. If
the data looks malicious, the firewall will reject it and stop it from being downloaded
onto your computer. It is useful that a firewall examines both the data incoming
and outgoing data from your computer, especially in the prevention of spyware. As
the firewall is examining the data leaving your computer as well, it may recognise a
malicious program that is trying to leave your computer that contains all the keypresses
that you have made on your keyboard. If the firewall rejects this data, it will not be able
to leave your computer, preventing it being sent to the perpetrator to be analysed.
• • • •• • .
• • internet
• • • . • •
User
Figure 5.24: A firewall protects a user's computer from security threats on internet
You can make sure that you are very cautious when clicking any links and downloading
any software online. Malware is often hidden in what looks like an innocent piece
of software or link, for example, a game that looks enticing to play. There could
be malware hidden inside a trojan horse in the game that may not be detected by a
firewall. If you download the game, it will download the trojan horse, allowing other
malware to be released onto your computer. You should only ever download software
from companies and sources that you know can be trusted, no matter how fun or
enticing it may look. KEY WORD
You can also store a backup of your data that is not attached to your computer or data backup: a copy
network on a constant basis. This means that if your data is damaged by malware, or of data that is stored
encrypted using ransomware, you still have access to a copy of your data. This can separate from the
prevent you needing to pay a ransom to gain access to your data again, but it will not computer.
stop the perpetrator from leaking your data. Therefore, it is advised not to keep any
personal data on your computer that could be accessed and leaked by a perpetrator of
ransomware. If you do keep personal data stored on your computer, you should
encrypt the data yourself, so if the perpetrator did gain access to the data, it would be
meaningless to them and they wouldn’t be able to leak it.
To avoid the risk of personal data, such as passwords, being sent to a perpetrator,
you could use an onscreen virtual keyboard rather than a physical one to enter
passwords. This means that you don’t need to make any key presses, so these are
not recorded for your password, so any data that was sent to a perpetrator would
not contain your passwords. Some companies also add drop down boxes for you to
select characters from to input your password. They may also ask you for random
characters from your password, and not your whole password. This is to prevent you
needing to enter your full password and to stop your full password being sent to the
perpetrator.
115 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
In summary:
Pharming is used by perpetrators to try and get your personal data, such as your pharming: a type
username and password for your online accounts. They can then log into the account, of cyber threat that
pretending to be you, and use your account to buy products online with your money. involves downloading
It can also be used to get more personal details from you, such as your address, that malicious software
can be used by the perpetrator for identity theft and fraud. onto a user's hard
drive, that redirects
The perpetrator will try and entice you into clicking a link or icon to start a download.
a request aimed at a
This could be done in various ways including sending an email, creating a pop up advert
genuine website to a
or just having a link available on a web page. When you click the link, a download will
fake website instead.
begin and as part of that download, malicious software will be downloaded onto your
The fake website will
hard drive. This malicious software is designed to redirect certain website requests you
encourage the user to
have to go to a fake website instead (see Figure 5.26). The perpetrator will set up a fake
input their personal
website to look very similar to a genuine website, such as PayPal or your social media
data, allowing it to be
page. When you next type in the URL to request the web page, the malicious code that
stolen.
has been downloaded on your hard drive will redirect the request to the fake website
instead. The perpetrator will hope that you think you have opened the genuine website hard drive: a storage
and when you type in your login details, these will be sent to the perpetrator instead. device that stores
If you notice that the website is fake after typing in your login detail, it is very data permanently,
important that you change your password for that website immediately. This can help until it is deleted by
stop the perpetrator being able to log into your account. the user.
As pharming uses malicious code that is installed on your hard drive, you can use anti
malware software to remove it. The anti-malware software will scan the files stored on
5 The internet and its uses
your computer and will help to find the file that is redirecting you to the fake website. The
anti-malware software will quarantine this file and let you delete it. When you type in the
URL now the redirection should stop and you should be taken to the genuine website.
One thing that you can do to help prevent pharming is to only download software or
click links that you know are from a trusted source. You should also thoroughly check
any website before you enter your personal details. You can look to see:
• If the URL at the top of the screen is the correct one.
• If the site is secured using HTTPS.
• If the website looks like it normally does. Are all the usual colours, images and
text there in the same places?
If you are in any doubt at all whether the website is genuine, close the website
without entering any of your details and scan your computer immediately with anti
malware software.
Figure 5.26: Pharming is a cyber threat where fake websites are used to steal data
In summary:
pretending to be you and use your account to buy products online with your money. It
can also be used to get more personal details from you, such as your address, that can
be used by the perpetrator for identity theft and fraud.
The perpetrator will again try and entice you into clicking a link. In phishing, this is
done by sending you an email. The perpetrator will create an email that looks like it is
from a genuine company, such as your bank. The email will try and get you to click a
link that will take you to a website. The email will try and get you to click the link by
telling you things like:
It looks like there has been unusual activity on your account, please click the link
and log in to check.
You have won a prize, please click the link and enter your details to claim the prize.
Confirmation is needed that you have made this purchase, please click the link and
log into your account to confirm whether or not you have made this purchase.
You are being paid a refund on your taxes, please click the link and enter your
credit card details so that you can claim the refund.
The link will take you to website that will not be the genuine website, it will be a
fake website that has been made to look like the genuine one. If you then input your
personal details these will be sent to the perpetrator and they will be able to access your
account or try and build a profile to steal your identity.
You can help prevent yourself getting fooled by any phishing scams by checking:
• The spelling and tone of the text in the email. Is everything spelt correctly? Is the
email written in a professional tone? Most genuine companies will spend a lot of
time making sure their emails are professionally written.
Whether the email has been personalised or if it is addressed in a generic way, e.g.
Dear customer. Many phishing emails are sent out in bulk and this often means
they are not individually addressed.
• The URL that is attached to the link. If you hover your mouse pointer over the
link, you should be able to see the URL that the link is connected to. Check if this
is the correct URL for this company.
• If the URL at the top of the screen is
the correct one.
• If the site is secured using HTTPS.
• If the website looks like it normally
does. Are all the usual colours, images
and text there in the same places?
Most companies will not ask you to provide
your personal details over the internet in this
way. If you are in any doubt at all whether
the website is genuine, close the website
without entering any of your details. If you
have entered any of your details and realise
after that you think it is a phishing scam,
make sure that you change the password to
your account and any other accounts that
Figure 5.27: In a phishing scam perpetrators will try to get your password
use that password immediately.
5 The internet and its uses
Question
12 What are three things that you can look for to identify if an email is a phishing scam?
Social engineering relies on manipulating and deceiving people into providing social engineering:
confidential or personal data that can be used in criminal activity such as identity theft a cyber threat that
and fraud, and hacking into computers systems or networks. Social engineering can involves manipulating
take many different forms. Phishing is also one form of social engineering, in that it or deceiving people
manipulates you into providing your personal data. into providing
confidential or
Have you ever seen one of those quizzes on social media that ask you to provide lots of
personal data.
fun details about you, like your favourite colour, the name of your pet and your favourite
food? These quizzes are often created by perpetrators trying to find out key information
about you. Many people base their passwords around this type of information, so a
perpetrator can gather lot of information like this about you every time you fill in one of
these quizzes on your social media. They can then use this data along with a brute-force
password program to try and get into your online accounts. Advice for the future, do
not fill out these quizzes! This is another form of social engineering, it manipulates and
deceives you into thinking you are filling out a fun quiz to learn more about your friends,
but you are actually providing key information that a perpetrator can use against you.
One way that you can limit a perpetrator’s access to your data on social media is to have
your privacy settings set to the highest level of privacy. This will normally mean that only
people that you are connected to will be allowed to see your data.
Social engineering can be used to target companies for their data too. A perpetrator
could make contact with the company and try and manipulate and deceive employees
into providing key information that can be used to hack the company systems. Here are
two examples of how this could be done:
Example 1
Large companies often have quite a large IT department that are often not too well
known by all the employees. It is a common occurrence that an employee may have an
IT issue with their computer in a morning. They will normally report this issue to the IT
department in their company and will be told
someone will contact them from the department,
shortly. Therefore, a perpetrator can try and
use this situation. They get hold of a list of all
the telephone numbers of the employees in the
company and begin to call them. They will say
that they are from the IT department in the
company and say that they are aware of the IT
issue that they have reported. Most employees
will probably just say they haven’t reported an
issue, but if they happen to call an employee
that has, that employee will think it is the IT
department calling to sort their problem. The
perpetrator will then say that they just need the
employees login details to access their system
to see what is wrong with it. The employee may Figure 5.28: Employees of large companies can be contacted by
be tricked into providing their login details and perpetrators claiming to be from the IT department
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
now the perpetrator can get into the computer systems of the business and steal any data
that they think could be useful to them, or look to introduce malware.
ACTIVITY 5.7
Discuss with a partner what you think the employee could do to stop
themselves being the target of a social engineering scam like this one.
Example 2
Employees often go for dinner together or out for a relaxing coffee after work on a Friday.
A perpetrator finds out where employees do this for the company that they want to target.
The perpetrator places themselves close to where the employees will normally sit. They
will start a conversation with the employees and become friendly with them. They will
start to ask lots of questions about the company an employee works for. The employee
may mistake this as the person taking an interest in their life. Over a few what seem like
accidental meetings with the employee the perpetrator has asked lots of questions that has
allowed them to build up a profile about the company, such as information about where
they store their data and what kind of security systems they have. The perpetrator can use
this information to hack into the company systems and network.
KEY WORD
One way that companies can help protect against the threat of social engineering is to How did you come
use access level for their data. This is where employees are given different levels of to a decision about
access to the data in the company. What this normally means is that an employee will what the employees
only have access to the data that they directly use on a daily basis. It also often means could have done in
that the only people that have access to more confidential data are the more senior Activities 5.7 and 5.8?
employees in the company. Levels of access are linked to an employee username.
5 The internet and its uses
The username will have data connected to it that will show the computer system which
KEY WORD
data the employee is allowed access to. This means that if an employee is targeted by a
social engineering scam and fooled by it, the data that the perpetrator can gain access username: a text
to may be limited. A company can also train employees to recognise social engineering based identification
to make them more aware of when it might be happening to them. that is given to a user
In summary: that identifies the
level of access that
What happens? A perpetrator will try and manipulate and deceive you they have to stored
into providing them with personal or confidential data. data and resources.
What is the aim? To get data to commit criminal activity, such as stealing
your money, hacking into a computer network and
identity theft or fraud.
What security solutions Access level and awareness of how social engineering
can be used? is conducted.
SUMMARY
The internet is the infrastructure that is used to access the world wide web.
The world wide web is the collection of all the web pages that are available.
A URL is a text based address for a web page that contains the protocol, the domain name and the web page
name or file name.
The HTTP protocol is used to transmit data between a computer and a web server.
This data is not encrypted when sent using this protocol.
The HTTPS protocol is the encrypted version of the HTTP protocol. It uses the SSL protocol to encrypt the data.
The main purpose of a web browser is to render HTML to allow a user to view web pages. It also has other
functions such as recording a user’s history and storing bookmarks, favourites and cookies.
Cookies are used to save your personal data and track your online preferences. They can be session or
persistent based.
Web pages are located, retrieved and displayed using a web browser, a DNS and a web server.
A digital currency is a currency that only exists electronically. An example can be cryptocurrency
and this kind of digital currency is tracked using blockchaining. This is a type of digital ledger that
records all payments made using the currency.
There are several cyber security threats that exist such as brute-force attacks, data interception,
DDoS, hacking, malware, pharming, phishing and social engineering.
The aim of most of the cyber security threats is to steal your personal data to commit identity theft
and fraud, or as an act of revenge or activism.
There are a range of cyber security solutions that can be used to help keep your data safe from security
threats such as anti-malware software, firewalls, proxy servers, encryption, authentication (including biometric
passwords and two-step verification), privacy settings, automated software updates, access levels and visual
checks such as checking the URL that is connected to a link or download.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
8 Draw a line to connect the security solution to the correct description. [3]
Security solution Description
This is a protocol that encrypts data that is sent
across the internet.
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
CONTINUED
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■Mi 1■
1 can... See Needs Getting Confident
topic more work there to move on
explain what is meant by a digital currency. 5.4
explain how blockchaining is used to track certain
5.4
digital currencies.
describe how a brute-force attack is carried out, what
the aim of it is and what security solutions can be used 5.5
to help prevent it happening.
describe how data can be intercepted, what the aim of
5.5
it is and how to help prevent it happening.
describe how a DDoS is carried out, what the aim of
it is and what security solutions can be used to help 5.5
prevent it happening.
describe what is meant by hacking, what the aim of
it is and what security solutions can be used to help 5.5
prevent it happening.
describe what is meant by a virus, what the aim of it is
and what security solutions can be used to help prevent 5.5
it being downloaded.
describe what is meant by a worm, what the aim of it is
and what security solutions can be used to help prevent 5.5
it being downloaded.
describe what is meant by a trojan horse, what the aim
of it is and what security solutions can be used to help 5.5
prevent it being downloaded.
describe what is meant by spyware, what the aim of
it is and what security solutions can be used to help 5.5
prevent it being downloaded.
describe what is meant by adware, what the aim of it is
and what security solutions can be used to help prevent 5.5
it being effective.
describe what is meant by pharming, what the aim of
it is and what security solutions can be used to help 5.5
prevent it happening.
describe what is meant by phishing, what the aim of
it is and what security solutions can be used to help 5.5
prevent it happening.
describe what is meant by social engineering, what the
aim of it is and what security solutions can be used to 5.5
help prevent it happening.
> Chapter 6
Automated
and emerging
technologies
na
X
IN THIS CHAPTER YOU WILL
V
learn about the use of automated systems in context
explore how automated systems use sensors, microprocessors and actuators
explore the advantages and disadvantages of automated systems in context
learn about the use of robotics
learn about the characteristics of a robot
explore the use of robots in context
learn about what is meant by artificial intelligence
explore the characteristics of artificial intelligence systems
describe the use of machine learning in artificial intelligence
explore the features of, and use of, expert systems.
■wjB
A
L J
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
GETTING STARTED
WHAT IS INTELLIGENCE?
An automated system performs actions without interaction with humans. They are automated: a device
used in small systems such as the heating or air-conditioning in buildings, all the way that is operated
up to flying aeroplanes and building items such as cars. without human
interaction.
There are a lot of different sensors that you need to know about - you can find more
KEY WORDS
information on these where they were covered in Chapter 3, Section 6. You will need to
identify which sensor is most appropriate in a given context. sensor: a type of
For example: a system needs to monitor the pollution in a river. input device that is
used to capture data
Consider what could be measured. The temperature of the water using a temperature from its immediate
sensor. The amount of light reaching the bottom using a light sensor. The pH of the environment.
water using a pH sensor.
microprocessor: an
Sensors just do one job, they read the environment and send the data onwards.
integrated circuit that
They do not process the data. That is done by the microprocessor. There is a problem
is able to perform
though, the sensor reads analogue data (real-world data such as 23.5 °C), but the
many of the functions
microprocessor only understands binary (01101010). The sensor first sends the data
of a CPU.
to an analogue-to-digital converter, to turn the reading into binary (digital).
Then, the digital data is sent to the microprocessor. analogue: continuous
Before the system is started, data will be stored in the microprocessor. This could be data that can be any
a single value, for example, the value from an infra-red sensor to state that there is value within a range.
movement. There could be several values, for example, the minimum temperature and digital: discrete data
maximum temperature for a greenhouse. Or there could be a whole range of data. that is stored as 1 s
The microprocessor takes the data from the sensor and compares it to its value, or and Os.
values. The result of the comparison determines the next step. For example, in a actuator: a
burglar alarm, if the sensor is outside of the stored range then an alarm will need
mechanical part
turning on. In a house, if the temperature is below the minimum the heating turns on,
that causes another
and if its above the maximum it turns the heating off.
device or part to
If the microprocessor decides an action is needed (e.g. turn the heating on), it sends move.
a signal to the actuator, which then performs the action. The whole process is then
repeated until the system is turned off.
Example
A set of doors in a building automatically open when a person is detected.
1 What type of sensor could be used?
An infra-red to detect movement, or a pressure sensor to detect if someone is
standing near it.
2 What happens to the analogue data?
The analogue data is converted into digital.
3 Where does the data go?
The data is sent to the microprocessor.
4 What happens in the microprocessor?
It compares the received data with the stored data. If it is out of range, it sends a signal
to an actuator to open the doors. If it is not out of range, it does nothing.
This process continues until the system is turned off.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Figure 6.2: The process in which doors open automatically when a person is detected
6 Automated and emerging technologies
When considering a control or monitoring system you need to determine the inputs,
processes and outputs as you would in a computer program:
The inputs from the sensors.
The processes.
The outputs from the system.
Using these you then need to create the ‘story’ (see Figure 6.4) about how the
sensors gather the appropriate data, what this is compared to, and how this
influences the outputs.
For example:
An automatic door will open when a person is detected. The door stays open for 5
seconds if no more people are detected.
Take each point in turn:
• Inputs:
A pressure sensor can be used to detect if a person is standing on a specific point.
A motion or infra-red sensor can be used to detect if a person is in a specific
place.
• Processes:
Analogue data from the sensor will be converted to digital.
The microprocessor will store the value where a person is detected on the
pressure sensor, and/or the result identifying that a person (movement) has
been detected.
• Output:
A signal will go to an actuator to open the door.
This will stay for 5 seconds, and is reset each time another person is detected.
Questions
1 Describe how the sensor will monitor its environment.
2 Describe how the processor will work out if the door needs to be opened.
3 When will the door close?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Questions
1 What type of data does a microprocessor process?
2 What tasks does a sensor perform?
3 An automated system makes cakes by positioning a cake tin below a funnel where
the cake mix comes through to fill the tin.
a Identify a suitable sensor for this system.
b The sensor has read the data. Identify the function that happens next.
c Where is the data sent?
d Describe the actions the microprocessor performs.
e How many times does the system run?
The automation of systems has both benefits and drawbacks, and these are different automation: the
depending on the system. You need to be able to think about the context and the use of automated
benefits and drawbacks in that scenario. equipment in a
process, e.g. a
When evaluating the use of automation you can consider:
factory.
• initial cost
• running cost
• safety
• replacing people’s jobs
• continuous work all day every day
precision.
Example 1, industry
Car manufacturing.
• Initial cost: this will be high because the robots need
purchasing. The software will also need developing
and could be expensive.
• Running cost: this could be high because the
systems need maintenance, but it could perform
actions more efficiently than humans which could
save money. However, there may be fewer employees,
therefore saving money long-term.
• Safety: it should be safer because they can monitor
their environment and stop if there is any danger,
whereas people can be distracted, and more Figure 6.5: A car manufacturing factory
accidents could happen.
• Replacing people’s jobs: jobs that the system now performs will be lost, but more
jobs will be made to maintain the system.
• Continuous work all day every day: this would mean that more cars can be built.
• Precision: human errors will not be made so there are less faulty cars.
no y
6 Automated and emerging technologies
Example 2, science
Nuclear power plant.
• Initial cost: will be high because of the purchase of the devices and development
of the system.
• Running cost: may be lower because fewer people are needed, however
maintenance might be expensive.
• Safety: less risk of human error therefore increasing the safety, also people will not
need to work in dangerous places.
• Replacing people’s jobs: some jobs will be replaced for the functions the system
does, but new jobs will be made to maintain the system.
• Continuous work all day every day: it is important that the power plant is
monitored all day every day without getting tired and
therefore less errors.
• Precision: this is important in a high-risk scenario
and an automated system will measure and perform
actions with more precision, therefore fewer errors.
Example 3, agriculture
Growing conditions within a greenhouse.
• Initial cost: this may be high for the installation and
programming.
• Running cost: there will be a cost for electricity and
maintenance but it is a small system so may not be high.
• Safety: this may not be relevant because it is not a
dangerous process.
• Replacing people’s jobs: it might replace jobs of
people who monitored the conditions, but this is unlikely to be a large number.
• Continuous work all day every day: this will allow the system to adapt as soon as
there is a problem, instead of waiting for a person to check and make changes.
• Precision: this may not be as important, but it will allow readings to be more
accurate and instant changes to be made.
Questions
4 An auto-pilot system will fly an aeroplane without input from a person.
Identify two benefits and two drawbacks of using the auto-pilot.
5 A weather station records and stores data about the current weather conditions.
Describe the advantages and disadvantages of using the automated system.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
robot: a machine
What are robots? that replicates human
actions or movement.
A robot is a mechanical device that performs an action, usually an action that a human
would perform. Robotics is an area that covers the design, construction and operation robotics: an area of
of robots. computer science
that looks at the
A robot can be controlled by a person, or they might be automated, or a mixture of the
creation and use of
two.
robots.
One example is a drone. This is a robot, it can be controlled by a person, and it can be
programmed to be perform movements depending on its surroundings. programmable: a
computer that will
Another example is the machines that build components in industry, for example, run the commands
manufacturing devices. The robots that put the components together can be automated stored in it.
so that they can build the components without human interaction.
Robots have a range of features:
• A mechanical structure or framework. This is the body of the robot.
• Electrical components such as:
• Sensors to record its environment, for example, the position of the
component it is building.
• Microprocessors, to take the reading from the sensor and decide the action
to perform.
• actuators, to make the robot move.
Robots are also programmable; a program can be written for the robot to follow.
Robots in agriculture
Developments include automated tractors and other machines, they can make use
of satellites and satellite navigation to guide their movements and then perform the
required actions. This means that a farmer can be performing other actions, whilst the
machines perform the repetitive tasks that would take up their time otherwise.
Robots can also be used to plant seeds, remove weeds, check and adjust the
environment where the plants are growing. All of these can be carried out 24 hours
a day, 7 days a week, whereas a person may only be working 8 hours a day.
Robots in agriculture are often used for the repetitive tasks that people would
otherwise spend a lot of time performing. The upfront cost might be high, and there
will be maintenance required. However, it might also replace a worker who would
otherwise be performing these actions.
Transport
A self-driving car is a robot. It reads its environment
and moves accordingly. This is still being developed, but
eventually people may not need to drive cars, this could
improve safety because the robot can react faster than a
person. It is an expensive up-front cost, and there is the
threat of what happens if someone accesses the program
of a car and changes it.
Robots are commonly used in factories to transport
items. For example, in a factory, robots can move boxes
of product to the lorries. These can be completely
automated, keeping people away from the movement
of products that could be dangerous. They do replace
peoples jobs, but also provide new jobs to run and Figure 6.9: A self-driving car
maintain the system.
Industry
Industry is the manufacture of goods from raw materials. This could be
from the building of a pencil, to the building of an aeroplane and everything
in-between.
Some factories are completely automated with robots. A car production line can
involve many different robots, each performing a specific role. The car being built
moves from one robot to the next without the need for human interaction. This means
that the factory can run all day, every day. The robots do not need to rest and can be
more precise because they are not prone to human error. However, their roles were
previously carried out by people who may now be without a job. Instead a smaller
number of people are required to monitor and maintain the robots, with a different
skill set than those who have been replaced. The initial cost is also very large as the
equipment needs to be purchased, and the program produced.
Robots don’t always manage all parts of a process. Some robots can:
Manage the packing of items, for example, putting packets of biscuits into boxes
of 24 packets.
Test products, for example, checking the temperature of products when they come
out of an oven.
Perform tasks that are minute in size and require exact precision, for example,
the building of circuits.
Entertainment
There are many robots that can be bought as toys, such as robot dogs for people to
interact with. There are also those that are educational, for example, where a child can
build a robot and then program it to perform specific functions. These allow people
to engage with technology, and in some cases learn about how robots work and be
introduced to programming.
6 Automated and emerging technologies
Domestic
Domestic robots are those that perform tasks around a home. The most common
one is the robot vacuum cleaner. It will make its way around a room, turning when it
detects obstacles and changing direction. This can save people time as they will not
need to perform the task themselves, however they still need monitoring and cannot go
up and down steps. A robot lawnmower works in the same way, monitoring the area it
is mowing to make sure it does not miss any spaces.
ACTIVITY 6.1
Find more examples of robots that are used in each of the sections; medicine,
agriculture, transport, industry, entertainment and domestic. List the benefits
and drawbacks of each of the robots. Share your findings with the class and
see how many different robots you have all found.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
REFLECTION
After completing Activity 6.1, it can be helpful to think about how you
approached it and ways you could improve your research skills for future
activities.
Discuss the sources you used to find examples of robots. How did you
make sure these sources were reliable, up-to-date and accurate? What
would you do differently if you had to find further examples?
Discuss whether finding your own examples might help you answer exam
questions. Is it helpful to find your own contexts instead of relying on
those given in class?
Questions
6 Define the term robot.
7 Identify two ways robots can be used in industry.
8 Give one benefit and one drawback of the use of domestic robots.
9 Discuss the use of driverless cars.
Artificial intelligence (Al) is the development of programs to simulate human artificial intelligence
behaviour. There is a broad range of areas within Al: (Al): a part of
computer science
• Image recognition; to identify objects or people in an image.
that looks at creating
• Speech recognition; to identify words spoken and store them. machines that can
think and perform
• Natural language; to receive a command or instruction that is not in a set format
tasks a person would
and perform the required response.
usually perform.
• Computer games; to move elements or characters independently based upon the
environment.
• Diagnosis systems; for example, medical diagnosis.
You have probably used natural language systems, for example, on a smartphone or a
web browser. You can enter your request in dozens of different ways. Let’s say you want
to find out what time the sun sets today. You could enter “sunset today time”, or “what
6 Automated and emerging technologies
time does the sun set today?” or “today when does the sun set?” or many other ways.
The software needs to understand what you have asked to decide how it will answer.
Some simple questions could be hard-coded. That means every possible way of
asking a question is written in the program, so it just has to select the correct one.
The problem is, how many ways are there? Is it possible to hard-code every possible
question or statement that anyone in the world could ever give? This would be
impossible. So instead, the artificial intelligence program has to be able to adapt to
whatever is entered. This could be done by comparing it with similar phrases, or
picking out key words and grammar, or it could use neural networks which attempt to
simulate the human brain to process the words entered.
ACTIVITY 6.2
Identify any programs you have used that might make use of artificial
intelligence. This could be computer games where you play against the
computer, or natural language interfaces. Discuss how you think these may
have been programmed and how the problems can be simplified into smaller
parts to make the task easier to tackle.
Components of Al
Artificial intelligence programs can be simplified to the four key features:
1 Collection of data: A program will need data input, this might come from a user
(e.g. speech recognition) or from its sensors (e.g. a robot that uses infra-red sensors
to work out its position and where it can and can’t move).
2 A set of programmed rules: These are stored for the program to use to make
decisions. For example, a calculation to determine which decision to make. A rule
that if an object is in front of the sensor, turn to the right.
3 The ability to reason: Reasoning is an area of logic, where you have rules, and
from these you can develop facts. For example, all dogs eat meat. Fred is a dog.
Therefore, Fred must eat meat.
4 The ability to learn and adapt: Not all Al systems will do this, this is a specialist
area known as machine learning. Systems can be programmed to learn, and
change their own rules and logic. This often involves training. If you want a
program to differentiate between an image of a dog and a horse, you can train the
system by showing it images of dogs and horses and telling it what the images are
showing. The program will then learn the characteristics of a horse and a dog, so
when it is tested with a new image it will hopefully identify the animal.
Unsupervised means that data is input, and then the program learns from the data.
An example of this is clustering. The data is plotted on a graph, and then the program
identifies which items of data are close to each other. In image recognition, the shapes in
the images could be input and then the features plotted, the program can then group the
images according to these features. This is done without any human interaction needed.
ACTIVITY 6.3
Find and play a computer game where you are competing against the
computer. Discuss how you think the computer's character was controlled. Did
it just repeat the same movements over and over, or did it change what it did
based on your move? Discuss how you think it was created and programmed.
6 Automated and emerging technologies
REFLECTION
After completing Activity 6.3, it can be helpful to think about how you
approached it and ways you could improve your research skills for future
activities.
1 How did you approach this task? Did you play the computer game
without thought to the character? Did you try lots of different moves to
see how the computer reacted?
2 What programming knowledge did you use to discuss how the
computer's character was programmed?
An expert system is a special type of system that attempts to emulate the expertise of expert system: a
a human, for example, an engineer, or doctor. The system asks the user questions to system that attempts
determine the solution or answer. Depending on each answer, the system will ask a to replicate the
different question. knowledge of an
expert.
For example, a program to help you fix a printer might first ask:
‘Is there a green light on the printer?’ knowledge base:
part of an expert
If the user says No, then they may be told, ‘Press the button to turn the printer on.’ system that stores
If the user says Yes, then they may be asked, ‘Is there a red light underneath the the facts.
paper picture?’ rule base: part of
An expert system has four key features: an expert system
that stores the rules
1 A knowledge base. This is a list of facts, for example, there is a green light below based upon the
the power symbol. knowledge.
2 A rule base that links the facts. For example, If the green light is on then the
printer has power. inference engine:
part of an expert
3 Inference engine. This is the part of the program that decides which question to
system that makes
ask next, or which answers it gives.
the decisions.
4 The user interface. This is the part that outputs questions and statements to the
user, and allows the user to enter data.
Organisations often use expert systems to allow people to find help without
having to communicate with people. These are usually repetitive problems
that people may encounter. If you have a home internet connection and it is
not working, then troubleshooting can tell you what actions to perform to fix it.
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ACTIVITY 6.4
Create an expert system to determine the difference between a cat and a dog.
Ask the user questions depending on their previous answers. This can be written
as a computer program using a programming language of your choice, or as a
flowchart showing which questions to move to depending on each answer.
Peer Assessment
Test each other's expert systems. How useable was the system? Were there
any questions that you couldn't answer? Did it give you the correct answer?
Questions
10 Define the term artificial intelligence.
11 Describe what is meant by machine learning.
12 State the purpose of an expert system.
13 Give two examples of where expert systems can be used.
14 An expert system has an inference engine and interface. Describe the two other
component parts of an expert system.
SUMMARY
1 a Give one example of where an expert system can be used. [1 ] give: produce an
b Complete the sentences about expert systems by filling in the answer from a given
missing words. source or recall /
memory.
An expert system is made up of four parts. The
base is the set of The base identify: name /
is a set of logical rules. The select I recognise,
applies the two bases to decide what questions to ask next and to work out
the response. The is the elements that allow the describe: state the
user to data and to output data to the user. [7] points of a topic /
give characteristics
[Total: 8]
and main features.
2 Identify three characteristics of a robot. [3]
3 A car has a proximity detection system. If an object is within a set distance
from the car, an alarm is sounded in the car.
Describe how the automated system detects objects and alerts the driver. [6]
4 An artificial intelligence program uses machine learning.
Describe machine learning using an example. [2]
5 A factory that builds furniture is thinking about buying robots to replace
the workers.
Discuss the advantages and disadvantages of the factory replacing the
workers with robots. [6]
6 Identify two ways that robotics can be used in transport. [2]
7 Describe how machine learning can be used to develop speech
recognition systems. [4]
8 A farmer is thinking about implementing software into his machines to
turn them into automated systems, for example, a tractor that navigates
its own way around the field to plough the field.
a Identify one other automated system the farmer could make use of. [1 ]
b Give two benefits to the farmer of using automated systems. [2]
c Give two drawbacks of implementing automated systems in the farm. [2]
[Total: 5]
9 A film company want to video animals in the wild acting naturally.
They decide to create life-like robots that use artificial intelligence to
react naturally with their environment. The robots have cameras inside
that record the interactions.
a Describe how artificial intelligence can be used to allow the robots
to react to their environment. [6]
b Discuss the use of robots to record the animals. [6]
[Total: 12]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
learn about the use of, and stages in, the program development life cycle
use decomposition to split a system into sub-systems
create structure diagrams, flowcharts and pseudocode algorithms
explain how a bubble sort and linear search works
describe and produce algorithms that include finding the maximum, minimum and average values
understand the need for validation and verification and write programs that use both
identify appropriate test data for an algorithm
complete a trace table for an algorithm
learn how to check a program for errors and amend the program
learn how to explain the purpose of an algorithm.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
GETTING STARTED
Set up an obstacle course using chairs and other objects. Write down a set of
instructions to guide a friend through the obstacle course, for example, stating
how many steps to take, which way to turn, etc.
Give the instructions to a friend and ask them to follow the instructions safely
(e.g. stop if they are about to hit something). Amend the instructions until your
friend can successfully get through the obstacle course.
Consider what is meant by an algorithm. If you search for algorithm then you will find answers such
as a process, or a set of rules, that are followed. This does not mean they are limited to computers.
You can find algorithms in all areas of life. You will have followed many of these without even
considering that they are algorithms. For example, in mathematics you will have followed a series
of steps to solve a problem.
Algorithms can take many forms, and use a variety of words or structures.
Computers follow algorithms. Programs are written as a series of instructions that the computer
then follows. Algorithms for software might be millions of lines long, and they have to make use of
specific instructions to tell the processor what to do.
A computer can only run machine code, that is binary. If you enter a command into the computer,
this has to be converted into binary for the processor to execute (run) it.
Different programming languages have different focuses. Some different types are shown:
Declarative
This declares rules and you can ask it questions and it will give an answer based upon the rules.
For example, here are some facts:
From this you could ask who Jennifer is friends with, and it will return Tyler.
Object-oriented
This allows the user to create objects that have features (attributes) and processes (methods).
For example, you could have a car as an object. Its features are colour, engine size, number of doors.
Its processes are move forward, move backwards, turn.
Event driven
Some programs use buttons, text boxes and other items that the user can interact with. An event
driven language has code that is only run when one of these items is clicked, or changed. The code
is not run from start to finish, each item has its own code.
7 Algorithm design and problem solving
CONTINUED
Procedural
This has statements that are run in the order that they are written. It makes use of subroutines
(procedures and functions) that can be called from other parts of the program. This is the type
of language that you are most likely to start learning to program with.
Discussion questions
1 What are the key features of an event driven language?
2 Why do you think there is a need for different types of programming language?
Can you think of any types of problem that lend themselves to one type of language?
KEY WORDS
7.1 Program development life cycle program
When a person, or organisation, creates a new computer program they will use a development life
structured, organised plan of how to create the program. This is called the program cycle: a series of
development life cycle. structure step I
activities that are
There are several varieties of life cycle, including cyclic, spiral, waterfall and rapid
followed to produce
development. These all include the stages analysis, design, coding and testing.
a system.
analysis: the first
stage of the program
development life
cycle that involves
investigating the
problem.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
1
Input Output
Figure 7.3: Input, process and output are added to Figure 7.4: Expanding the input subprograms
the calculator structure diagram
7 Algorithm design and problem solving
Calculator
1
Process M Output
Or the variable names from the input can be used (Figure 7.6):
Calculator
r I 1
Process Output
numberl
symbol
number2
Figure 7.6: An alternative way of representing the algorithm shown in Figure 7.4
KEY WORD
Both of these are valid. There are lots of ways you can decompose a problem, and decompose: the
everyone could do it slightly differently but the solution is still valid. action of performing
decomposition;
Finally, the output needs identifying (Figure 7.7):
splitting a system into
smaller sub-systems,
Calculator which can in turn be
split into smaller sub
systems.
Process
numberl
symbol
number2
Figure 7.7: A finished structure diagram for the calculator
This program was fairly small, so it has been split into very precise instructions that
can then be programmed. The next example is a larger problem.
A computerised version of chess is being developed. Two players can enter their names
and then a new board will be displayed. The players take it in turns to select pieces to
move and the positions to move them to. The program will check that the moves are
valid and then move the pieces. It will remove any pieces that have been taken in each
move, and check if anyone has reached checkmate.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 2
The name of the program is at the top (Figure 7.8).
The program could be decomposed into inputs, processes and outputs, but this
is a large program so it can be split down by different functions instead. The first
part is that there are two players who need entering, this is given the name ‘New
players’. Then the game is set up (‘New game’). The players can then move their
pieces (‘Make move’). The program will check if someone has checkmate Figure 7.8: A structure diagram for
(‘Check won’) (Figure 7.9): a chess program
Chess
l
New Make
New game Check won
players move
These can then be split further. They are each given their own sub-diagram here so that
they are easier to view (Figures 7.10-13):
New game
Figure 7.10: The New players subprogram Figure 7.11: The New game subprogram
Check won
ACTIVITY 7.1
Can you split any of these subprograms down further? In 'Check won'
(Figure 7.13) what should happen if the result is checkmate? Should there be
an output? What if there is check but not checkmate? Should this be output?
Peer Assessment
Compare your subsystems with a friend. Did you have the same answers?
If so, are they both valid structure diagrams even though they are different?
Once you have decomposed your program into subprograms, you will need to design
an algorithm for each part. This could be the level 1 (the first row below the top box)
like in the calculator example. It could be for a lower level, like in the game of chess.
Each box should become an individual algorithm. When you write your program,
each of these individual algorithms might be a separate function or procedure (see
Chapter 8, Section 12). Together, these individual algorithms should come together to
create the whole system.
Questions
1 Describe the process of decomposition.
2 A program asks the user to enter two numbers. The program then adds the
numbers together and outputs the total. Draw a structure diagram for the program.
3 A satellite navigation system needs to ask the user to input their destination.
It then finds the route to the destination and outputs the instructions to the user.
Draw a structure diagram for the system.
4 A login system asks the user to enter their username and password. It checks these
are valid and either outputs that they are correct, or incorrect and prompts to
re-enter. Draw a structure diagram for the system.
A flowchart shows each step of a process, in the order that each step is performed.
Each shape has one statement within it, for example, input number, or add l to x.
The shapes are joined with arrows to show the direction of flow and the content
inside each box can be written as words, or as pseudocode statements. Table 7.1 shows
examples of how the flowchart symbols are used.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
(
1
Stop
/ output "error" /
(continued)
7 Algorithm design and problem solving
It is important that all arrows are complete, i.e. all boxes lead somewhere else so that
you cannot get stuck in the flowchart with nowhere to go.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 1
Figure 7.20 shows a flowchart for a calculator.
Example 2
Figure 7.21 shows a flowchart for a password validation program.
ACTIVITY 7.2
Flowcharts can be used for more than writing programs. Work in pairs to
produce a flowchart for making a cup of tea, or coffee, or another drink.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Questions
5 Write the name of each flowchart symbol in the shape.
b
Pseudocode refers to any code that is not written on a computer to run. There is no one pseudocode: code
set pseudocode, because if there was then this would be code with a specific language. like statements that
Instead it’s a term for any readable code-like statements that all programmers will are used to design an
understand. This means that it uses keywords, and constructs such as IF statements, algorithm but do not
WHILE loops, etc. These constructs occur in almost all languages, so any programmer follow any specific
would be expected to read them and translate them into the actual programming language.
language they are using.
Example pseudocode:
INPUT Numberl
IF Numberl < 10 THEN
OUTPUT "too small"
ELSE
OUTPUT "valid"
ENDIF
This uses the keywords INPUT, IF and OUTPUT. These can then be translated
into whatever language the programmer is using. Here the pseudocode program is
converted into Python, VB.NET and Java.
7 Algorithm design and problem solving
Python
number1 = input()
if number < 10:
print("too small")
else:
print("valid")
VB.NET
numberl = console.readline()
if number < 10 then
console.writeline("too small")
else
console.writeline("valid")
endif
Java
number = Integer.parselnt(scanner.nextLine());
if (number < 10){
System.out.printin("too small");
}else{
System.out.printin("valid");
}
There are many different valid pseudocode formats. Some will always use capitals for the
commands, e.g. INPUT, IF, FOR. Some will use <- instead of an = for assignment. If
you write your pseudocode in almost perfect ‘code’, i.e. you actually write Python code,
because it is not to be run and you can have all sorts of syntax errors it is still pseudocode.
What is important is that the program is split into steps that can be easily converted into a
real program. Table 7.2 shows some examples of valid and invalid pseudocode.
The syllabus includes information about the pseudocode conventions that will
appear within examinations. The pseudocode conventions in this book don't
always exactly follow the conventions you will see in your exams, but they are
still valid. Remember that your syntax doesn't have to be perfect - it is your
logic that is important.
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
REFLECTION
After completing
Proqramminq
Task 7.1:
How did you
approach the
programming task?
Did you skip the
getting started or did
you jump straight to
the practice?
Did that approach
work? Will you
consider the getting
started next time?
Did you tackle the
challenge yourself?
If not, would you
revisit this when you
are feeling more
confident in this
topic?
ACTIVITY 7.3
Questions
8 Describe the purpose of pseudocode.
9 Tick one box in each row to identify if the statements are appropriate pseudocode
statements, or not.
7 Algorithm design and problem solving
IF y < 6 THEN
add 3 to the value entered
store the value entered in the variable newValue
valuel = INPUT("Enter a number")
IF number is more than 10
WHILE numberl <> 0
Example 1
A program allows the user to enter their age as a whole number between 10 and 100
years.
Example 2
A user needs to enter a password at least 8 characters long.
ACTIVITY 7.4
Questions
12 Identify three different types of test data.
13 Why can you have the same test data as normal and extreme types of test data?
14 What is the difference between extreme and boundary test data?
15 A program asks the user to input a number between 1 and 10 (inclusive).
7 Algorithm design and problem solving
Identify test data for each of the test data types in the table:
A search algorithm checks a set of data to identify whether a specific value exists in the search algorithm: a
data, or not. One example of this is a linear search. series of steps that
searches for a specific
A sorting algorithm takes a set of data and rearranges it to be in a specific order,
value in a set of data.
e.g. in ascending alphabetical order. One example of this is a bubble sort.
sorting algorithm:
COMPUTER SCIENCE IN CONTEXT a series of steps
that will rearrange a
Sorting data and searching for data are activities that a very large proportion set of data into an
of programs will use at some point. For example, outputting a list of data may order, e.g. ascending
need sorting into order. A user may enter a username and the program needs numerical data.
to search for this in the set of valid usernames.
There are many different searching and sorting algorithms, each one has its
benefits and drawbacks depending on the problem. This could be the number
of data items it has to sort through, or whether the data is already in order to
search for a value. It is up to the programmer to identify the algorithm that is
most appropriate for their program to make sure it is as efficient as possible
(both in the time it takes to run, and the amount of memory it needs to
perform this task).
线性搜素
Linear search KEY WORD
In a program you might need to look for a specific value in a set of data. A linear linear search: a
search will check each item one at a time, starting with the first item and continuing search algorithm that
until it either finds the item, or it checks the last value. visits each item of
data in turn to check
ACTIVITY 7.5 whether it is the data
being looked for.
Get a set of playing cards. Select 10 random cards and
place them face down on the table in a row. Perform a
linear search to see if the Ace of Spades is in the set.
r
*
1 Turn over the first card.
2 Is it the Ace of Spades? 4b
3 If it is, then stop searching, you've found it.
♦
4 If it isn't, turn over the next card. Repeat from 2. V,
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 1
Search this set of data for the number 4.
5 3 9 4 2 1 8
Compare the first number (5) with the search value (4). They are not the same.
Compare the second number (3) with 4. They are not the same.
Compare the third number (9) with 4. They are not the same.
Compare the fourth number(4) with 4. They are the same. It has been found.
Example 2
Search this set of data for the character
Example 3
Searching an array (Chapter 8, Section 15 on arrays).
The array dataArray stores a set of data under one identifier. Each element in the
array has an index.
Index 0 1 2 3
Data 1 5 6 8
Search the array for the number 6
Is DataArray [0] =6? No, DataArray [0] = 1
Is DataArray [1] =6? No, DataArray [ 1 ] = 5
Is DataArray [2 ] =6? Yes, DataArray [ 2 ] - 6
6 was found in index 2.
This can now be written as an algorithm:
FOR Arrayindex = 0 to LENGTH(Array) -1 //loop through each element
//check if the current index is the data searched for
IF DataArray[Arrayindex] = Searchvalue THEN
//if it is, output the index where’ it is found
OUTPUT "Found at " & Arrayindex
ELSE
//if it not found, increment arrayindex to check the next value
Arrayindex <- Arrayindex + 1
END IF
NEXT Arrayindex
7 Algorithm design and problem solving
This algorithm is inefficient because if it finds the search value then it still continues
TIP
searching. This is useful if you want to know whether the search value appears more
than once. Different
You can make the algorithm more efficient by stopping as soon as the value is found, programming
for example: languages use
different characters to
Found <- FALSE indicate the start of
Arrayindex <- 0 a comment (there is
//run while the value is not found, and you have not checked no closing character).
//all elements For example, #, //,
WHILE Found = FALSE AND Arrayindex < LENGTH(Array) DO /* and '. You have
//check if the current index is the data searched for to use one of these
IF DataArray[ArrayIndex] = Searchvalue THEN characters when
//if it is output where it was found writing pseudocode,
OUTPUT "Found at " & Arrayindex but any one of these
//set found to be true to stop the while loop running is acceptable.
//again
Found <- TRUE
ELSE
//if it is not found, increment Arrayindex to the next value
Arrayindex <- Arrayindex + 1
END IF
ENDWHILE
Bubble sort
When writing a program you may need to sort a set of data into a specific order,
for example, ascending numerical order or descending alphabetical order. KEY WORD
ACTIVITY 7.6
Get a set of playing cards. Select 10 random cards and place them face down
on the table in a row. Perform a bubble sort to put the cards in ascending
numerical order.
1 Turn over the first two cards.
2 If the 1 st is larger than the 2nd, swap them. Otherwise, do nothing.
3 Turn the cards back over.
4 Turn over the 2nd and 3rd cards.
5 Repeat step 2.
6 Repeat turning over the cards and swapping until you have been through
all 10 cards once.
7 Did you make any swaps? If so, start again from step 1. If not, stop
because the cards should be in order.
A bubble sort can be written as a pseudocode algorithm. There are different versions
of the algorithm. Here are two different versions.
Version 1
Stopping only when it has run array length -1 times.
//loop array length - 1 number of times
FOR NumberPasses <- 0 to LENGTH(DataArray) - 1
//loop through each element in the array
FOR Index «- 0 to LENGTH (Da taAr ray) - 1
//check if the data is in the correct order
IF DataArray[Index] > DataArray[Index + 1] THEN
//if not swap the items
Temp <- DataArray [Index]
DataArray[Index] <- DataArray[Index + 1]
DataArray [Index + 1] <- Temp
ENDIF
NEXT Index
NEXT NumberPasses
Version 2
Stopping when there are no changes or when it has run array length - 1 times.
NumberPasses <- 0
//continue until one pass has no changes (changes = false)
//or it has looped array length - 1 times
WHILE Changes = FALSE or NumberPasses <= LENGTH(DataArray) - 1 DO
7 Algorithm design and problem solving
When you are performing a bubble sort, first identify the order required, e.g.
ascending or descending. Then identify the data item being sorted, e.g. is it a
number, a letter, a set of words, etc.
For example: sort the numbers 6 2 5 1 into ascending numerical order.
There are 4 numbers that need sorted into ascending numerical order. This means
you keep on sorting until either:
a you have passed through all numbers 3 times
or
b you have passed through all the numbers once without making any changes.
To help guide your working it’s often useful to draw a table for each of the items.
Draw a table with the four values:
6 2 5 1
Pass 1. Work through the data items, comparing each pair in turn. If the data is in
the wrong order, swap them.
Data Instructions
6 2 5 1
6 2 5 1 Compare the first two values.
2 6 5 1 They are in the wrong order so swap them.
2 6 5 1 Compare values 2 and 3.
2 5 6 1 They are in the wrong order so swap them.
2 5 6 1 Compare values 3 and 4.
2 5 1 6 They are in the wrong order so swap them.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
b you have passed through all the numbers once without making any changes
[False, there has been at least one change].
Pass 2. Work through the data items, comparing each pair in turn. If the data is in
the wrong order swap them.
Data Instructions
2 5 1 6
2 5 1 6 Compare the first two values.
2 5 1 6 They are in the correct order. Compare values 2 and 3.
2 1 5 6 They are in the wrong order. Swap them.
2 1 5 6 Compare values 3 and 4. They are in the correct order.
Should it stop?
Compare to the two criteria:
a you have passed through all numbers 3 times [False, only 2 passes have been made]
or
b you have passed through all the numbers once without making any changes
[False, there has been at least one change].
Pass 3. Work through the data items, comparing each pair in turn. If the data is in
the wrong order swap them.
Data Instructions
2 1 5 6
2 1 5 6 Compare the first two values.
1 2 5 6 They are in the wrong order. Swap them.
1 2 5 6 Compare values 2 and 3.
1 2 5 6 They are in the correct order. Compare values 3 and 4.
1 2 5 6 They are in the correct order.
Should it stop?
Compare to the two criteria:
a you have passed through all numbers 3 times [True, 3 passes have been made so
stop].
7 Algorithm design and problem solving
CONTINUED
Questions
1 How many swaps were made in this bubble sort?
2 Why did it stop after 3 passes?
3 How would you change this process to put the data into descending numerical
order?
Put the characters "z" "c" "f' "a” "h" into descending alphabetical order.
First identify the data and method. This is string data, and into descending
alphabetical order.
There are five characters, so keep on sorting until either:
a you have passed through all characters 4 times
or
b you have passed through all the numbers once without making any changes.
Draw a table with the given characters:
z c f a h
Pass 1. Work through each of the data items once. If the pair is in the incorrect
order, swap them.
z c f a h
z f c a h
z f c h a
Should it stop? It has not run 4 times. It has made changes. Repeat.
Pass 2.
z f c h a
z f h c a
Should it stop? It has not run 4 times, and it made a change. Repeat.
Pass 3.
z f h c a
z h f c a
Should it stop? It has not run 4 times. It has made 1 change. Repeat.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
Pass 4.
z f h c a
Should it stop? It has run 4 times - stop.
Questions
1 How many comparisons were made that did not result in swaps?
2 How would you change this algorithm to work with strings instead of multiple
characters, e.g. 'zoo' 'farm' 'cat' 'horse' 'animal'?
A program asks the user to enter a set of 20 numbers. The user can then
enter a number for the program to search for in the set of data. The program
will output if it is found, or not. The program should then put the data into
ascending order and output the newly arranged data.
Getting started
1 Practise the linear search process using a set of cards. Lay them out and
search them in turn to identify if a specific one is present.
2 Practise the bubble sort process using a set of cards. Lay them out and
put them into the correct order following the bubble sort instructions.
3 Recap the programming skills; input, output, selection and iteration.
Focus on how to loop 20 times to enter 20 numbers.
4 Read the linear search and bubble sort algorithms with a partner.
Follow each instruction in the algorithm.
Practice
1 Identify the inputs, processes and outputs for the problem.
2 Create a structure diagram for the problem.
3 Write a pseudocode algorithm to take in the set of 20 numbers from the
user.
4 Amend the algorithm to allow the user to input a number to search for, and
then the code to perform a linear search on the data and output the result.
5 Amend the program to perform a bubble sort on the data, and output the
arranged program.
Challenge
1 Move the linear search into its own subroutine (procedure or function) so
it can be called from anywhere in the main program.
2 Move the bubble sort into its own subroutine and call it from the program.
7 Algorithm design and problem solving
Questions
16 Perform a linear search for the number 6 in the following data:
10 5 6 8 1 2
17 Perform a linear search for the letter “f ” in the following data:
b u l p f a g h
1 8 Perform a bubble sort to put the following data into ascending numerical order:
1 5 6 2 9 0 1
19 Perform a bubble sort to put the following data into descending numerical order:
60 2 40 52 3 5
20 Explain the difference in efficiency between the two different bubble sort algorithms.
Example 1
Totalling the 10 values input by the user:
Total <- 0 //Initialise the total variable to 0
FOR X <- 0 TO 9
Total <- Total + INPUT("Enter a value") //Add the input to the total
NEXT X
OUTPUT Total
Example 2
Totalling the values in an array named dataArray:
Totalvalue «- 0 //Initialise the total variable to 0
FOR Count <- 0 TO LENGTH (DataArray) - 1
Totalvalue <- Totalvalue + DataArray[Count] //Add the input to the total
NEXT Count
OUTPUT Total
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Counting is working out how many of something there are. For example, counting counting: statements
how many fingers you have or counting how many items you bought when you in a program that
went shopping. record how many of
something there are.
To do this in a program you need to:
• Initialise a variable to start the count, e.g. Count I terns «- 0.
• Add 1 to the count variable each time, e.g. Count «- Count + 1.
Example 1
Count the number of items the user enters:
Count *- 0 //initialise the count variable
Number <- 0
WHILE Number <> -1 DO // loop until the user enters -2
Number <- INPUT("Enter a number. Enter -1 to stop")
Count <- Count + 1 //add 1 to count each time a number is input
ENDWHILE
Example 2
Count how many numbers in an array are below 10, and how many are more than 20:
CountBelowlO «- 0 //initialise both counters to 0
CountAbove20 <- 0
FOR X <- 0 to LENGTH(NumberArray) //loop through each array element
7 Algorithm design and problem solving
Example 1
Find the smallest number input by a user:
Minimum <- 9999 //initialise minimum to large value
Number <- 1
WHILE Number >= 1 DO //loop until the user enters 0
Number <- INPUT("Enter a number or 0 to stop")
IF Number < Minimum THEN // check if the number entered is smaller than
//the current minimum
Minimum <- Number //if true then make minimum because the number
ENDIF
ENDWHILE
Example 2
Find the smallest number in an array of data:
Minimum <- 999999
FOR X <- 0 TO LENGTH (NumberAr ray)
IF NumberArray[X] < minimum THEN
Minimum <- NumberAr r ay [X]
ENDIF
NEXT X
The maximum value is the largest value within a set. For example, the marks for a class maximum: the
are entered and the highest mark is the maximum. largest item in a set
of data.
To do this in a program you need to:
• Initialise a maximum variable to be a small value, beyond those that will be
entered, e.g. Maximum <- -9999.
• Compare each value to the maximum variable, e.g. IF Number > Maximum.
• If it is, it replaces the maximum value, e.g. Maximum <- Number.
This means the new value is the maximum, so the next time a value is compared,
it is checking it with the new maximum value.
Example 1
Find the largest number input by a user:
Maximum *- -9999 //initialise maximum to small value
Number <- 1
WHILE Number >= 1 DO //loop until the user enters 0
Number = INPUT("Enter a number or 0 to stop")
IF Number > Maximum THEN // check if the number entered is larger than
//the current maximum
Maximum <- Number //if true then make maximum because the number
ENDIF
ENDWHILE
7 Algorithm design and problem solving
Example 2
Find the largest number in an array of data:
Maximum <- -1 // initialise the maximum value to a small number
FOR X <- 0 TO LENGTH (NumberAr ray)
//check if the number entered is larger than the current maximum
IF NumberArray[X] > Maximum THEN
Maximum <- NumberArray[X] //if true store the value in maximum
END IF
NEXT X
The average here is referring to the mean. This is the total of all the values added average: the mean
together, then divided by how many numbers there are. of a set of values, the
total divided by the
For example, if the data is 1,3, 5, 8, 4, 2, 6, 9 ,
quantity.
the average = (l+3 + 5 + 8 + 4 + 4 + 6 + 9)/8 = 40/8 = 5
To do this in a program you need to use the count and total from earlier in this section.
The average is then calculated with the formulae Total / Count.
Example 1
Find the average of the numbers input by a user:
Count <- 0 //initialise the count to 0
Total <- 0 //initialise the total to 0
Number <- 1
WHILE Number >= 1 DO //loop until the user enters 0
Number <- INPUT("Enter a number or 0 to stop")
Total <- Total + Number //add the number entered to the total
Count <- Count + 1 //add 1 to the count
ENDWHILE
Example 2
Find the average of the numbers in an array of data:
Count <- 0 //initialise the count to 0
Total <- 0 //initialise the total to 0
FOR X <- 0 TO LENGTH (NumberArray)
Total <- Total + NumberArray[X] //add value to total
Count <- Count + 1 //add 1 to count
NEXT X
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Questions
21 Explain the difference between totalling and counting.
22 A program allows numbers to be entered between 20 and 200, and finds the
smallest and largest entered. Identify appropriate values to initialise the variables
Smallest and Largest.
23 Write an algorithm to input 40 numbers and output the total and average.
24 Write an algorithm to input 100 numbers and output the smallest and largest.
Validation is the checking of data that is input to make sure it is reasonable, and/or validation: the
within set bounds. For example, making sure that a number is entered for an age or checking of data
limiting the range of numbers that can be entered. to make sure it is
reasonable and
ACTIVITY 7.7 within set bounds.
Have you ever entered data to be told that it is invalid? What were you trying
to enter, and why was it incorrect? Visit some websites that need you to
enter some data (but stay safe and make sure it is not personal data).
What restrictions do they have? Are there some spaces that you need to
enter data in? Do some of them give you a set structure to fill in, for example,
a date as I I_____ ?
Are these all controlled with validation rules?
KEY WORD
Range check
A range check assesses whether data is within one or two bounds. For example, an age range check, a
must be between 0 and 100. A date must be before today’s date. type of validation
that makes sure
Range checks can be programmed using selection to produce an error, or within a loop
data is between
that keeps asking you enter a value until it is valid.
the minimum and
maximum.
Example 1
Using selection:
This algorithm will check whether a number is higher than 1 and less than 10.
Number <- INPUT("Enter a number between 1 and 10")
IF Number < 1 OR Number > 10 THEN
OUTPUT("Invalid")
ELSE
OUTPUT("Valid")
END IF
Example 2
Using a loop:
This algorithm will check if a number is higher than 1 and less than 10. It will
continually ask for a value to be input until the number is valid.
Number <- INPUT("Enter a number between 1 and 10")
WHILE Number < 1 OR Number > 10 DO
OUTPUT("Invalid please try again")
Number <- INPUT ()
ENDWHILE
KEY WORD
Length check
A length check will check the number of characters that are present. This could in a length check: a type
string, for example, the length of “hello world” is 11, the space is also a character. of validation that
It could be in a variable, for example, in this example, 8 will be output: checks the number of
characters is within a
TheData <- "123 ABC!"
set limit.
OUTPUT(LENGTH(TheData))
The length of a piece of data can be found using a variety of commands depending on
the language you are using. The following are all valid and there are many more:
theData.length()
LENGTH(theData)
LEN(theData)
theData.len
A length check can be programmed using selection or iteration.
Example 1
Using selection:
This algorithm will check if the data input has 10 or less characters to be invalid,
otherwise (10 or more) it is valid.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 2
Using iteration:
This algorithm will also check the length but will continually ask for this to be input
until it is 10 or more characters long.
Data <- Input ()
WHILE LENGTH(Data) < 10 DO
OUTPUT("Invalid, please try again")
Data <- INPUT ()
ENDWHILE
Example 1
Using selection:
This algorithm will check if the data entered is an integer value to be valid.
INPUT Data
//check if the data entered is an Integer
IF Data.GetDataType() <> Integer THEN //if it is not an integer
OUTPUT ("Invalid")
ENDIF
Example 2
Using iteration:
This algorithm will continually ask for the data to be input until it is a string value.
INPUT Data
//loop while the data entered is not a string
WHILE Data.IsString = FALSE DO
OUTPUT("Invalid please try again")
INPUT Data
ENDWHILE
7 Algorithm design and problem solving
Example 2
Using iteration:
This algorithm continually takes an input while there is no data entered.
INPUT Data
WHILE Data = "" DO //loop while there is nothing in data
OUTPUT("Invalid please try again")
INPUT Data
ENDWHILE
Example 2
Using a loop:
This algorithm checks whether an input is in the format two numbers, /, two numbers,
/, four numbers.
INPUT Date
//loop while the data is not in the correct format
WHILE (SUBSTRING(Date, 0, 2).IsNumeric = FALSE OR //2 numbers
SUBSTRING (Date, 2, 1) <> " /" OR // 1st slash
SUBSTRING(Date, 3, 2).IsNumeric = FALSE OR //2 numbers
SUBSTRING(Date, 5, 1) <> " /" OR //2nd slash
SUBSTRING(Date, 6, 4).IsNumeric = FALSE) DO // 4 numbers, year
OUTPUT("Invalid")
INPUT Date
ENDWHILE
OUTPUT("Valid")
A check digit is calculated from a set of numbers, and is input with the numbers. check digit: a type
When the data has been input, the calculation is performed on the data again and of error detection
the result is compared with the final number (the check digit). method that is
used for data entry.
Example A calculation is
This algorithm calculates the check digit using the method 5 digit number input. performed on the
9999, 4 digits used to calculate 5th check digit, and compares it to the input value. data entered to
create a value. Check
INPUT Code
digit values are
//extract 1st digit
compared to see it
Digitl «- Code DIV 1000 the data entered is
Code <- Code - (1000 * Digitl)
correct.
//extract 2nd digit
digit2 <- Code DIV 100
Code <- Code - (100 * Digitl)
//extract 3rd digit
Digit3 <- Code DIV 10
Code <- Code - (10 * Digitl)
//extract 4th digit
Digit4 <- DIV (Code, 1)
CheckDigit <- Code
//calculate check digit from data entered
//multiply by position and add together
Total <- (Digitl * 4) + (Digit2 * 3) + (Digit2 * 2) + Digit3
NewCheckDigit MOD(Total, 11) //find Mod 11 of total
NewCheckDigit <- 11 - NewCheckDigit //subtract result from newCheckDigit
//check if the calculated check digit is the same as the last digit in the //code
IF NewCheckDigit = CheckDigit THEN
OUTPUT("Correct data entry")
ELSE
OUTPUT("Incorrect data entry")
ENDIF
You can find out more about check digits in Chapter 2.
7 Algorithm design and problem solving
A user needs to enter a series of data that each require validation. The table
shows the data and the requirements:
Getting started
For each of the validation requirements, decide on which type of validation
you are going to use. Try and choose a different one for each value.
Recap the algorithms for each type, write an example beside each of the ones
you have chosen.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
Practice
1 Write an algorithm to take as input the five values.
2 Amend the program to include the validation for each item of data.
3 Amend your program to output, for each data item, whether their data is
valid or invalid.
Challenge
Extend the program to repeatedly ask for each item of data until they enter
one that is valid. Then the next piece of data should be input.
Could any of the items of data have more than one validation rule used?
Find at least one piece of data that can have two types of validation and
implement it in your program.
ACTIVITY 7.8
Work in pairs to identify how many times you have come across validation
or verification in a program or website. Compare your answers with another
pair. How common are validation and verification? Are there any methods not
identified here, for example, what is two-step verification?
Questions
25 What is validation?
26 Give three examples of validation checks.
27 What is the purpose of verification?
28 Identify which validation rule this algorithm uses:
INPUT Num
IF Num > 0 AND Num < 100 THEN
OUTPUT "Valid"
ELSE
OUTPUT "Invalid"
ENDIF
29 Identify which validation rule this algorithm uses:
REPEAT
INPUT Value
UNTIL Value <> NULL AND Value <> ""
30 Write a validation routine to input a word and check that it is more than 10 characters long.
31 Write a validation routine to input a number and check that it is an integer value.
7 Algorithm design and problem solving
A trace table is a structure to help you follow an algorithm, for example, to find an trace table: a
error, or to work out what the algorithm does. structure to complete
when walking
Each statement in an algorithm is run manually, and the values that are written to through an algorithm
variables are written in the table in the order the changes are made. manually, where the
Each column in the table is designated to one variable. There can also be a column values that change
for any outputs to be written in. User prompts are also entered in the trace table, these are written in each
can be entered in a separate column or as an output (because they will be output). row.
For example, x = input(“Enter a number”), the text “Enter a number” is a user prompt
and will need to be added to the trace table.
Specific inputs can be given to test different parts of the algorithm.
To create a trace table you need to identify all of the variables in an algorithm.
Each variable should have its own column in the trace table. There should also be
an output column if the program will output any data or strings.
For example, trace the following algorithm with the input values 1 and 3.
INPUT Numberl
INPUT Number2
IF Numberl > Number2 THEN
OUTPUT(Numberl)
ELSE
OUTPUT(Number2)
ENDIF
There are two variables and there is an output (each variable has a column,
and the output has a column).
You then complete this table by reading through the algorithm one line at a time.
It is important not to jump ahead and guess what the algorithm will do.
Read one line and perform that action.
Run line 1 of the code (input values 1,3):
INPUT Numberl
INPUT Number2
IF Numberl > Number2 THEN
OUTPUT(Numberl)
ELSE
OUTPUT(Number2)
ENDIF
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED A
numberl number2 OUTPUT
The first line inputs
1 4______________
the first value
given, 1.
1 Run the first 3 lines of code. These are the initialisations, lines 01,02 and 03.
01 Count <- 0
02 Inputvalue <- 1
03 Total <- 0
CONTINUED
CONTINUED
8 Line 08 returns to line 04 again. WHILE 1 >0 is TRUE. Run lines 05, 06 and 07.
05 INPUT Inputvalue Inputvalue <- 0
06 Total <- Total + Inputvalue Total <-10 + 1
07 Count <- Count + 1 Count <-4 + 1
Questions
1 What do you record in a trace table?
2 When do you change the value in a column?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
3 Repeat the process with a different set of data, for example, this time using
10, 5, 1.
4 Complete the trace table.
7 Algorithm design and problem solving
CONTINUED
Keep on repeating this process until you can identify the pattern.
In this case it is outputting the largest number input and then outputting the total of
the 3 numbers input.
Questions
1 Two sets of data were used to run this algorithm. If you had to choose a third
set what would you choose?
2 How do you know when to stop testing the algorithm with different data?
3 Describe the processes in this algorithm and state its purpose using a trace table.
Quantity <- 0
Total <- 0
Value <- 0
Small <- 999
WHILE Quantity < 5 DO
INPUT Value
IF Value >= 10 AND Value <= 100 THEN
Quantity <- Quantity + 1
Total <- Total + Value
IF Value < Small THEN
Small <- Value
ENDIF
ENDIF
ENDWHILE
OUTPUT("small = ", Small)
OUTPUT(Total / Quantity)
DESCRIBING AN ALGORITHM
When you are describing an algorithm you need to do more than repeat the line of
code using English statements. For example, in the following code, for line 02 don’t
just say, ‘it is a for loop from y is 0 to x.’ This is stating what each part of the code is,
but it does not describe the algorithm.
01 INPUT X
02 FOR Y <- 0 TO X
03 OUTPUT Y
04 NEXT Y
You can do a trace table to help you work out the purpose of the algorithm before
describing it if that helps you. This algorithm has three parts: line 01, line 02 and
line 03. These are summarised below:
• Takes a number as input, (line 01)
• Loops from 0 to the number that has been input, (line 02)
• Outputs the values from 0 to the number, (line 03)
From this you can develop a description of the algorithm, for example:
The algorithm takes a number from the user, and then outputs all of the numbers from
0 to the number input.
Questions
1 What methods can you use to work out the purpose of an algorithm?
2 Why should your description explain more than what each part of the code
does?
3 Describe the purpose of this algorithm:
01 X <- -1
02 Count «- 0
03 WHILE Count < 10 DO
04 INPUT Y
05 IF Y > X THEN
06 X = Y
07 ENDIF
08 Count *-Count + 1
09 ENDWHILE
10 OUTPUT(X)
7 Algorithm design and problem solving
Computer programmers will come across errors all the time. These could be
ones that they have made, or that they are testing or fixing for other people.
There are lots of ways that they can find the errors, but many of them will
use the two methods used here; using a trace table, and dry running by
reading the code. There are other options often available to them as well,
for example, features within the Integrated Development Environment (IDE)
that they use to write the program. These features allow the programmer to
see the values of variables and the outputs at each stage, without having to
trace them manually.
Using a trace table will allow you to follow each step in the algorithm and by
comparing this to the intended outcome you can find where it goes wrong,
and then work out how to correct it.
For example, this program should take 5 numbers as input and output the total
of all the numbers.
01 Total <- 1
02 Quantity <- 1
03 WHILE Quantity < 5 DO
04 INPUT Number
05 Total <- Number
06 Quantity <- Quantity + 1
07 ENDWHILE
08 OUTPUT(Total)
First dry run the algorithm. If not provided, you will need to identify some test
data to use.
This algorithm should take 5 numbers as input, so you could use 1, 2, 3, 4, 5.
Then work out what the result of the algorithm should be. It outputs the total,
so it should output: 1+2 + 3 + 4 + 5=15
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
Now draw a trace table for the algorithm (revisit the section on trace tables if
needed) and then run each step of the algorithm, writing the values in the table.
You may not always need to use a trace table, or you may not want to. There are
many different ways of finding the errors. In this example you will look for each of
the requirements in the algorithm to determine whether it has been met.
The following algorithm should take 3 numbers as input, and output the largest
value and the average value.
01 Total <- 0
02 Largest <- 999
03 FOR X <- 0 TO 2
04 INPUT Data
05 IF Data < 999 THEN
06 Large <- Data
07 ENDIF
08 Total <- Total + Data
09 NEXT X
10 OUTPUT Largest
11 Average <- Total / 3
12 OUTPUT Average
7 Algorithm design and problem solving
CONTINUED
Re-read the description: take 3 numbers as input, and output the largest value and
the average value.
This can be split into three sections:
1 Take 3 numbers as input.
2 Output the largest value.
3 Output the average value.
The two outputs need to be calculated before being output, so they can be added to
the requirements:
1 Take 3 numbers as input.
2 Calculate the largest value.
3 Output the largest value.
4 Calculate the average value.
5 Output the average value.
Now check the first requirement:
Does it take 3 numbers as input?
The for loop goes from 0 to 2, so it will run 0, 1,2 = 3 times. Inside the loop it inputs
a value each time. This is correct.
The second requirement:
Calculate the largest value.
To find the largest it needs to:
a Initialise a largest variable with a low number.
This is not met. Line 02 largest is set to 999 but this should be a very small value,
e-g.
Largest «- -1
b It should check if the data input is larger than the data in largest.
This is not met. Line 05 checks if data is less than 999. It should be larger.
IF Data > Largest THEN
c Line 06 replaces the value in Large with data, but the identifier is incorrect, the
variable is named largest.
Largest <- Data
The third requirement:
Output the largest value.
Line 10 outputs the largest value, this is correct.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
CONTINUED
2 a Complete the trace table for the following algorithm using the input data: 7.
INPUT Number
WHILE Number >= 0 DO
OUTPUT Number
Number «- Number - 1
ENDWHILE
Number OUTPUT
SUMMARY
192 )>
7 Algorithm design and problem solving
CONTINUED
Blue <- 10
White <- 5
Yellow <- 2
Continue <- "Y"
WHILE Continue = "Y" DO
INPUT Colour
INPUT Quantity
IF Colour = "Blue" AND Quantity <= Blue THEN
Blue «- Blue - Quantity
OUTPUT "Blue left = ", Blue
ELSEIF Colour = "White" AND Quantity <= White
White <- White - Quantity
OUTPUT "White left = ", White
ELSEIF Colour = "Yellow" AND Quantity <= Yellow
OUTPUT "Yellow left = ", Yellow
ELSE
OUTPUT "Try again"
ENDIF
OUTPUT "Continue?"
INPUT Continue
ENDWHILE
[5]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
COMMAND WORD
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
Programming
IN THIS CHAPTER YOU WILL:
GETTING STARTED
PROGRAMMING LANGUAGES
C++ and many, many more. They all have different s zrng As Long •Zeilenanzahl dex Tabeile
n srng As Byte ' *■’ det
'Spaltenanzahl ** Tabeile
‘r“u*
commands, requirements for brackets, some a nrng As String •Name der Tabeile mit Bereich deflniert
fundamentals that work in the same way in Array (nrng, "Elementl"), Version:-xlPivotTable
CreatePivocTable TableDestinatlon:-"", TableN
Defaultversion:-xlPivotTableVersionl4
most (there are always one or two that try to be ActiveSheet.PivotTableWizard TableDestinatlon:-Act
ActiveSheet.PivotTables("PivotTable2").PivotFields(-?
different) languages. Once you know what these xlHidden|
ActiveSheet.PivotTables("PlvotTable2").PivotFields! S«j
number1
colour
price
finished
4
5
6
7
Variables and constants have one difference. In a variable, you can change the data
while the program is running. For example, putting the number 3 0 into memory
location number 1, the memory would then look like this:
number1
colour
price
finished
4
5
6
7
A constant cannot have its value changed while the program is running. When you
declare a constant you put a value into it and this cannot be changed.
KEY WORD
Using variables
Putting data into a variable is done using an assignment statement. The left hand side assignment: a type
of the equals sign is the identifier. The right hand side of the equals sign is the value of programming
(see Figure 8.2). statement that stores
data in a variable or
constant.
number = 10
Figure 8.2: Components of an assignment
Number <- 10
Colour <- "red"
Price «- 22.2
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
VB.NET
Dim number As Integer
Dim colour As String
Dim price As Single
number = 10
colour = "red"
price = 22.2
Python
number = 10
colour = "red"
price = 22.2
Java
public static void main(String args[]){
Integer number = 10;
String colour = "red";
Double price = 22.2;
}
To get data out of a variable you just use its identifier (see Figure 8.3).
print (number)
Figure 8.3: Printing the contents of a variable
Number *-10
Colour *- "red"
OUTPUT(Number)
OUTPUT("The colour is ", Colour)
Price <- Number * 2
VB.NET
Dim number As Integer
Dim colour As String = "red"
Dim price As Single
Console.WriteLine(number)
Console.WriteLine("The colour is " & colour)
price = number * 2
8 Programming
Python
colour = "red"
number = input()
print("The colour is", colour)
price = number * 2
Java
public static void main(String args[]){
Integer number = 10;
String colour = "red";
System.out.printin("The colour is " + colour);
Integer price = number * 2;
}
Using constants
Before you use a constant in your program you need to give it a value. This is an
assignment statement the same as a variable. (No examples are given for Python as it
does not have in-built constants.)
CONSTANT Colour <- "yellow"
VB.NET
Const colour As String = "yellow
Java
public static void main(String args[]){
final String colour = "yellow";
}
Using the key word constant makes it clear that this value cannot then be changed.
You get data out of a constant the same way as a variable, by using its identifier.
OUTPUT(Colour)
VB.NET
Const colour As String = "yellow"
Console.Writeline(colour)
Java
public static void main(String args[]){
final String colour = "yellow";
System.out.printin(colour);
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ACTIVITY 8.1
Take each data type in turn and think of at least 10 different examples of
data that can be stored (apart from Boolean where there can be only two).
From these, identify whether any of these could be more than one data
type, discuss in pairs what options would be valid and which would be most
appropriate.
Peer Assessment
Compare your work with another pair. Identify if all of the data is appropriate
for the data type chosen. Discuss the choices, e.g. if one was more
appropriate than the other?
8 Programming
VB.NET
Dim colour As String = "red"
Const value As Integer = 10
Dim price As Single = 22.4
Dim flag As Boolean = True
Python
colour = "red"
value = 10
price = 22.4
flag = True
Java
public static void main(String args[]){
String colour = "red";
final Integer value = 10;
Double price = 22.4;
Boolean flag = true;
)
VB.NET
Dim number As Integer
number = Convert.Tolntl6("123")
Python
number = int("123")
Java
public static void main(String args[]){
Integer number = Integer.parselnt("123");
}
Example 2
Convert a number to a string:
Value «- string (22.4)
VB.NET
Dim value As String
value = Convert.ToString(22.4)
Python
value = str(22.4)
Java
public static void main(String args[]){
String value = Double.toString(22.4);
}
Questions
1 Tick one or more boxes in each row to identify whether each statement refers to
variables and/or constants.
Statement Variable Constant
You cannot change the value when the
program is running.
It has an identifier.
It is a memory location.
You can change its value when the
program is running.
It stores a piece of data.
8 Programming
VB.NET
Console.WriteLine("Hello World")
Python
print("Hello World!")
Java
public static void main(String args[]){
System.out.printin("Hello World");
)
Example 2
Output the number 20:
OUTPUT(20)
VB.NET
Console.WriteLine(20)
Python
print(20)
205 >
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
System.out.printin(20);
}
KEY WORD
If you want to output more than one piece of data then you can join them using a
concatenation symbol. Concatenation means join together, so it joins multiple pieces of concatenation:
data together. This could be a comma (,), an ampersand (&) or a plus (+) depending joining two or more
on your language. All are acceptable in pseudocode. strings together.
Example 1
Output the word Hello, then the contents of variable name:
OUTPUT("Hello ", Name)
VB.NET
Dim name As String = "Alex"
Console.WriteLine("Hello " & Name)
Python
name = "Alex"
print("Hello", name)
Java
public static void main(String args[]){
String name = "Alex";
System.out.printin("Hello " + name);
}
Example 2
Output the cost of an item stored in the variable cost:
OUTPUT("The cost is " , Cost)
VB.NET
Dim cost As Single = 22.54
Console.WriteLine("The cost is " & cost)
Python
cost = 22.54
print("The cost is", cost)
206 y
8 Programming
Java
public static void main(String args[]){
Double cost = 22.54;
System.out.printIn("The cost is " + cost);
}
Example 3
Output the number of balloons stored in the variable balloon:
OUTPUT("There are " , Balloon , " balloons")
VB.NET
Dim balloon As Integer = 100
Console.WriteLine("There are " & balloon & "balloons")
Python
balloon = 100
print("There are", balloon, "balloons")
Java
public static void main(String args[]){
Integer balloon = 100;
System.out.printIn("There are " + balloon + " balloons");
}
In these examples you will see there are spaces within the speech marks. This is because
OUTPUT ("Hello", Name) would join these together, e.g. Hello Jane. When writing
in pseudocode it is not important that these are included, but you might need to do it
when outputting in your chosen programming language.
Input
A program might need the user to enter (input) some data. To do this, the command input: the user
word INPUT is used. This cannot appear on its own, otherwise the data entered will entering data into
disappear into space. So you need to do something with it, for example, store it in the program, usually
a variable. from a keyboard.
Example 1
Input a number and store it in a variable:
INPUT Number
VB.NET
Dim number As Integer
number = Console.ReadLine
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
number = int(input())
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer number = Integer.parselnt(scanner.nextLine());
}
Example 2
Tell the user to enter a word and store it in a variable:
OUTPUT("Enter a word")
INPUT Word
VB.NET
Dim word As String
Console.WriteLine("Enter a word")
word = Console.ReadLine
Python
number = input("Enter a word")
Java
public static void main(String args[]){
System.out;printin("Enter a word")
Scanner scanner = new Scanner(System.in);
String word = scanner.nextLine();
A program asks the user to register for a new account. The user needs to enter
key information, e.g. name, date of birth, select a username, etc.
Getting started
1 Work in pairs to list the different items that the program will collect.
2 Identify the most appropriate data type for each of the items you have
identified.
8 Programming
CONTINUED
Practice
1 Select appropriate variables for the items you have identified that you are
going to store.
2 Write a program to ask the user to enter each of the items in turn. Read in
each value and store it in an appropriate variable.
3 Output a message confirming the details that the user has entered.
Challenge
1 The username needs to be at least 8 characters long. Find out how to
work out the length of a string input and output how many characters the
user has entered.
2 Find out how to use selection statements to check the length of the string
and if it is not long enough, ask the user to enter a different username.
KEY WORD
MOD has one special use in programming. It can be used to work out if a number is
odd or even. If you perform MOD 2 to a number and it returns 0 then it is even, if it KEY WORDS
returns 1 then it is odd.
MOD: remainder
Example: MOD(10, 2) = 0 therefore 10 is even. division. The
remainder after
MOD( 11, 2) = 1 therefore 11 is odd.
the division is
performed, e.g.
SKILLS FOCUS 8.1 MOD(5, 2) = 2.
MOD VS DIV DIV: integer division.
The remainder
It is important that you know the difference between MOD and DIV. They are from the division is
similar in their function, but are often confused with division (/). You need to be ignored, e.g. DIV (5,
able to use both of these, both to identify the result of the operation, and to be able 2) = 2.
to write programs using them. In this Skills Focus you will be calculating the result
from a MOD and DIV operation.
DIV gives the whole number after the division and ignores any remainder.
a 10/2 =v5 There is no remainder, so DIV(10, 2) = 5.
b 20/7 = 2.857 There is a remainder, so DIV(20, 7) = 2 (ignore the numbers after
the decimal point).
c 100/21 =4.762 There is a remainder, so DIV(100, 21) = 4 (ignore the numbers
after the decimal point).
MOD gives the remainder after division. This is not the decimal point, but how
many values are left.
a 10/2 = 5 There is no remainder, so MOD(10, 2) = 0.
b 20/7 = 2.857 There is a remainder. Take the DIV result (2) and multiply it by
the divisor number. 7*2=14. The remainder is how many more numbers are
between 14 and the 20 (20-6). The answer is 6.
c 100/21 =4.762 There is a remainder. Take the DIV result (4) and multiply it by
the divisor 21 * 4 = 84. The remainder is 100 - 84 which is 16.
d 30/9 = 3.3333 There is a remainder. 9 * 3 = 27. 30-27 = 3.
Questions
1 Calculate the result for each of these equations:
a DIV(9, 2) b DIV(17,3)
2 Calculate the result for each of these equations:
a MOD(9,2) b MOD(17,3)
The operators for DIV and MOD will differ depending on the programming language
you are using.
Example 1
Taking two numbers as input and adding them together:
OUTPUT("Enter the first number")
INPUT Numl
OUTPUT("Enter the second number")
INPUT Num2
Total <- Numl + Num2
VB.NET
Dim numl As Integer
Dim num2 As Integer
Dim total As Integer
Console.WriteLine("Enter the first number")
numl = Console.ReadLine
Console.WriteLine("Enter the second number")
num2 = Console.ReadLine
total = numl + num2
Python
numl = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
total = numl + num2
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter the first number");
Integer numl = Integer.parselnt(scanner.nextLine());
System.out.printin("Enter the second number");
Integer num2 = Integer.parselnt(scanner.nextLine());
Integer total = numl + num2;
}
Example 2
Subtracting 10 from 20:
Number 1 <- 10
Number2 <-20
Result <- Number2 - Numberl
VB.NET
Dim numberl As Integer = 10
Dim number2 As Integer = 20
Dim result As Integer
result = number2 - numberl
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
number1 = 10
number2 = 20
result = number2 - numberl
Java
public static void main(String args[]){
Integer numberl = 10;
Integer number2 = 20;
Integer result = number2 - numberl;
}
Example 3
Multiplying two values together:
Numberl <- 5
OUTPUT("Enter a number")
INPUT Number2
Result <- Numberl * Number2
VB.NET
Dim numberl As Integer = 5
Dim number2 As Integer
Console.WriteLine("Enter a number")
number2 = Console.ReadLine
Dim result As Integer
result = number2 * numberl
Python
numberl = 5
number2 = int(input("Enter a number"))
result = numberl * number2
Java
public static void main(String args[]){
Integer numberl = 5;
System.out.printIn("Enter a number");
Scanner scanner = new Scanner(System.in);
Integer number2 = Integer.parselnt(scanner.nextLine());
Integer result = numberl * number2;
}
8 Programming
Example 4
Dividing 100 by 5:
Number 1 <- 100
Number2 <- 5
Result <- Number 1 / Number2
VB.NET
Dim numberl As Integer = 100
Dim number2 As Integer = 5
Dim result As Single
result = number2 / numberl
Python
numberl = 100
number2 = 5
result = number2 / numberl
Java
public static void main(String args[]){
Double numberl = 100.0;
Double number2 = 5.0;
Double result = number2 / numberl;
}
Example 5
Finding the whole number after dividing 33 by 7:
Result <- DIV(33Z 7)
VB.NET
Dim result As Single
result = 33 \ 7
Python
result = int(33 / 7)
Java
public static void main(String args[]){
Integer result = 33 / 7;
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 6
Finding the remainder after dividing 33 by 7:
Result <- MOD (33, 7)
VB.NET
Dim result As Single
result = 33 Mod 7
Python
result = 33 % 7
Java
public static void main(String args[]){
Integer result = 33 % 7;
} KEY WORD
Calculations can use parentheses (brackets) to change the order the calculations are parentheses:
performed in. The calculations within the brackets are done first. brackets in a
mathematical
Example 7 statement. They
determine which
Total <- 1 + (2*3)
calculations are
Total <- (1 + 2) * 3 performed first.
The first line will result in 7 (3 * 2 = 6 + 1 = 7).
The second line will result in 9 (1+ 2 = 3 * 3 = 9).
Sequence is the first of three constructs within programs. A sequence is a series of sequence: a
statements that are executed (run) once, in the order they are written. programming
construct. Instructions
Example 1 are run once and in
the order they are
OUTPUT("Enter a colour") written.
INPUT Colour
OUTPUT("Enter your name")
INPUT Name
OUTPUT(Name , " your favourite colour is " , Colour)
VB.NET
Dim colour As String
Console.WriteLine("Enter a colour")
colour = Console.ReadLine()
Dim name As String
Console.WriteLine("Enter your name")
8 Programming
name = Console.ReadLine()
Console.WriteLine(name & " your favourite colour is " & colour)
Python
colour = input("Enter a colour")
name = input("Enter your name")
print(name, "your favourite colour is", colour)
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a colour");
String colour = scanner.nextLine();
System.out.printIn("Enter your name");
String name = scanner.nextLineO ;
System.out.printin(name + " your favourite colour is " + colour);
}
This is a sequence. It has 3 lines are executed once, and in the order they are written
(line 1, then 2 then 3).
Example 2
x <- 1
Y <- 2
Z <- 3
Total «- X + Y + Z
OUTPUT("Enter the first value")
INPUT Value1
VB.NET
Dim X As Integer = 1
Dim Y As Integer = 2
Dim Z As Integer = 3
Dim total As Integer
Dim valuel As String
Console.WriteLine("Enter the first value")
valuel = Console.ReadLine
Python
x = 1
y = 2
z = 3
total = x + y + z
valuel = int(input("Enter the first value"))
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
Integer X = 1;
Integer Y = 2; KEY WORDS
Integer Z = 3;
selection: a
Integer total = X + Y + Z;
programming
String valuel;
construct. A
System.out.printIn("Enter the first value");
condition is checked
Scanner scanner = new Scanner(System.in);
and this determines
valuel = scanner.nextLine();
which code is run, or
}
not run.
IF statement: a type
Questions of selection construct
where the result of
4 Give the result from the following calculations:
the condition is either
a 10 + 20 e 20 DIV 2 true or false.
b 20/2 f 39 DIV 6
CASE statement:
c 100 * 4 g 20 MOD 2 a type of selection
d 50 - 15 h 40 MOD 6 construct where there
is a list of different
5 Write a program to take a number as input, multiply it by 2 and output the result.
values to compare a
6 Write a program to store the numbers 10 and 12 in constants, add them together single value against.
and then output the result.
7 Write a program to ask a user to enter their age and name, then output a message logical operator: a
that uses both values, e.g. Hello Suzie you are 15 year old. symbol that performs
a comparison
resulting in True or
False. Can be equals,
8.6 Selection not equal to, less
than, less than or
Selection is the second of the three constructs. In selection a condition is checked
equal to, greater
and this determines which, if any, code is run. There are two forms of selection,
than, greater than or
IF statements and CASE statements.
equal to.
Conditions need logical operators. These allow for comparisons to be made. Table 8.3
describes these different operators. Each statement using a logical operator results in
TRUE or FALSE.
COMPARISON OPERATORS
CONTINUED
Questions
1 Put each statement into words:
a IF(1 < 2)
Look at the left of the symbol. Is it small or large? Write the first number,
followed by the symbol name, then the second number.
b IF(6 > 3)
c IF(999 >= 998)
d IF(34 <= 77)
2 Work out if each statement is True or False.
a IF(66 < 40)
b IF(100 > 101)
c IF(90 <= 45)
d IF(30 >= 30)
IF statements
The command IF is followed by a condition that is created using the logical operators.
There are three stages of IF statements; IF, ELSE and ELSEIF.
IF has one comparison and the code inside the IF will only run if that condition is
True. If it is not true, the code in the IF statement will not run.
It follows the structure:
IF comparison THEN
Statements that run if the comparison is true
END IF
Example 1
This program will check the value in the variable numl is equal to 10. If it is, it will
output the word True.
Numl <-10
IF Numl =10 THEN
OUTPUT("True")
END IF
VB.NET
Dim numl As Integer = 10
If numl = 10 Then
Console.WriteLine("True")
End If
Python
numl = 10
if numl == 10:
print("True")
8 Programming
Java
public static void main(String args[]){
Integer numl = 10;
if(numl == 10){
System.out.printin("True");
}
}
Example 2
This program will check if the value input is greater than the one stored in the variable.
OUTPUT("Enter a number")
INPUT Valueinput
StoredValue <- 100
IF Valueinput > StoredValue THEN
OUTPUT("It is more than 100")
END IF
VB.NET
Dim valueinput As Integer
Console.WriteLine("Enter a number")
valueinput = Console.ReadLine
Dim StoredValue As Integer = 100
If valueinput > StoredValue Then
Console.WriteLine("It is more than 100")
End If
Python
valueinput = int(input("Enter a number"))
StoredValue = 100
if valueinput > StoredValue:
print("It is more than 100")
Java
public static void main(String args[]){
Integer StoredValue = 100;
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a number");
Integer valueinput = Integer.parselnt(scanner.
nextLine());
if(valueinput > StoredValue){
System.out.printin("It is more than 100");
}
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ELSE
This is added within an IF statement. If the IF statement’s condition is false then the
ELSE will run. You can only ever have one ELSE in an IF statement.
ELSE follows the structure:
IF comparison THEN
Statements that run if the comparison is true
ELSE
Statements that run if the comparison is false
ENDIF
Example 1
In this example if the two values are the same it outputs " That' s correct". If they
are not the same then the ELSE runs, it will output " Incorrect".
Num <- 10
OUTPUT("Enter a number")
INPUT Guess
IF Num = Guess THEN
OUTPUT("That's correct")
ELSE
OUTPUT("Incorrect")
ENDIF
VB.NET
Dim num As Integer = 10
Dim guess As Integer
Console.WriteLine("Enter a number")
guess = Console.ReadLine
If num = guess Then
Console.WriteLine("That's correct")
Else
Console.WriteLine("Incorrect")
End If
Python
num = 10
guess = int(input("Enter a number"))
if num == guess:
print("That's correct")
else:
print("Incorrect")
Java
public static void main(String args[]){
Integer num = 10;
Integer guess;
Scanner scanner = new Scanner(System.in);
220 >
8 Programming
System.out.printin("Enter a number");
guess = Integer.parselnt(scanner.nextLine());
if(num == guess){
System.out.printIn("That's correct");
}else{
System.out.printin("Incorrect");
}
}
Example 2
In this example, it will output the smallest number, or one of the numbers if they are
both the same.
Valuel <- 10
Value2 <- 20
IF Valuel < Value2 THEN
OUTPUT(Valuel)
ELSE
OUTPUT(Value2)
ENDIF
VB.NET
Dim valuel As Integer = 10
Dim value2 As Integer = 20
If valuel < value2 Then
Console.WriteLine(valuel)
Else
Console.WriteLine(value2)
End If
Python
valuel = 10
value2 = 20
if valuel < value2:
print(valuel)
else:
print(value2)
Java
public static void main(String args[]){
Integer valuel = 10;
Integer value2 = 20;
if(valuel < value2){
System.out.printIn(valuel);
}else{
System.out.printin(value2);
}
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ELSEIF
This allows for a second condition to be used within the same IF statement.
If the first condition is False, then a second condition can be checked.
ELSEIF follows the structure:
IF comparisonl THEN
Statements that run if the comparison is true
ELSEIF comparison2 THEN
Statements that run if comparisonl is false, and comparisons is true
ENDIF
Example 1
This will output which number is greater, or nothing will output if they are the same.
Numl <-10
Num2 <-2 0
IF Numl < Num2 THEN
OUTPUT(Num2)
ELSEIF Num2 < Numl THEN
OUTPUT(Numl)
ENDIF
VB.NET
Dim numl As Integer = 10
Dim num2 As Integer = 20
If numl < num2 Then
Console.WriteLine(num2)
Elself num2 < numl Then
Console.WriteLine(numl)
End If
Python
numl = 10
num2 = 20
i f numl < num2:
print(num2)
elif num2 < numl:
print(numl)
Java
public static void main(String args[]){
Integer numl = 10;
Integer num2 = 20;
i f(numl < num2) {
System.out.printIn(num2);
}else if(num2 < numl){
System.out.printIn(num2);
}
8 Programming
You can use multiple ELSEIF statements, and combine them with a single ELSE
statement at the end.
This will follow the structure:
IF comparisonl THEN
Statements that run if the comparison is true
ELSEIF comparison2 THEN
Statements that run if comparisonl is false, and comparisons is true
....as many ELSEIFs as you need
ELSE
Statements that run if none of the comparisons are true
ENDIF
Example 2
This uses ELSEIF and an ELSE to output the largest number.
IF Numl > Num2 THEN
OUTPUT(Numl)
ELSEIF Num2 > Numl THEN
OUTPUT(Num2)
ELSE
OUTPUT("They are the same")
ENDIF
VB.NET
Dim numl As Integer = 10
Dim num2 As Integer = 20
If numl > num2 Then
Console.WriteLine(numl)
Elself num2 > numl Then
Console.WriteLine(num2)
Else
Console.WriteLine("They are the same")
End If
Python
numl = 10
num2 = 20
i f numl > num2:
print(numl)
elif num2 > numl:
print(num2)
else:
print("They are the same")
Java
public static void main(String args[]){
Integer numl = 10;
Integer num2 = 20;
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 3
This uses multiple ELSEIFs.
IF Age < 14 THEN
OUTPUT("You are not old enough")
ELSEIF Age <16 THEN
OUTPUT("You need an adult present")
ELSEIF
VB.NET
Dim age As Integer
Console.WriteLine("Enter your age")
age = Console.ReadLine
If age < 14 Then
Console.WriteLine("You are not old enough")
Elself age < 16 Then
Console.WriteLine("You need an adult present")
End If
Python
age = int(input("Enter your age"))
if age < 14:
print("You are not old enough")
elif age < 16:
print("You need an adult present")
SELECT CASE
A SELECT CASE statement allows the program to take one variable or value, and then
have lots of different options depending what it is equal to.
CASE follows the structure:
CASE OF variable
valuel:
Statements that run if CASE valuel is true
value 2:
Statements that run if CASE valuel is false, and value2
OTHERWISE
Statements that run if none of the comparisons are true
ENDCASE
8 Programming
A case can have as many CASE statements as needed, but can only ever have a
maximum of one default (this runs if none of the comparisons are true).
Example 1
Using a SELECT CASE to output a grade for an in-lesson test. (No example is given
for Python as it does not have a CASE construct and no example is given for Java as it
does not support switch statements with comparisons, e.g. < or >.)
Score <- INPUT ("Enter score")
CASE OF score:
>=80 : OUTPUT ( "A"
> = 70 : OUTPUT( .. B" )
>=60 : OUTPUT( "C" )
>=50 : OUTPUT( D - )
OTHERWISE OUTPUT(
ENDCASE
VB.NET
Dim score As Integer
Console.WriteLine("Enter score")
score = Console.ReadLine
Select Case score
Case >= 80
Console.WriteLine("A")
Case >= 70
Console.WriteLine("B")
Case >= 60
Console.WriteLine("C")
Case >= 50
Console.WriteLine("D")
Case Else
Console.WriteLine("U")
End Select
Example 2
Output a message depending on which number is entered. (No example is given for
Python as it does not have a CASE construct.)
OUTPUT("Enter a number, 1 to 5")
INPUT Choice
CASE OF Choice:
1: OUTPUT("Menu option 1")
2 : OUTPUT("Menu option 2")
3 : OUTPUT("Menu option 3")
4: OUTPUT("Menu option 4")
5: OUTPUT("Menu option
OTHERWISE OUTPUT("Invalid choice")
ENDCASE
225 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
VB.NET
Dim choice As Integer
Console.WriteLine("Enter a number, 1 to 5")
choice = Console.ReadLine
Select Case choice
Case 1
Console.WriteLine("Menu option 1")
Case 2
Console.WriteLine("Menu option 2")
Case 3
Console.WriteLine("Menu option 3")
Case 4
Console.WriteLine("Menu option 4")
Case 5
Console.WriteLine("Menu option 5")
Case Else
Console.WriteLine("Invalid choice")
End Select
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a number, 1 to 5");
Integer choice^ Integer.parselnt(scanner.nextLine());
switch(choice){
case 1:
System.out.printin("Menu option 1
break;
case 2:
System.out.printin("Menu option 2
break;
case 3:
System.out.printin("Menu option 3");
break;
case 4:
System.out.printin("Menu option 4");
break;
case 5:
System.out.printin("Menu option 5");
default:
System.out.printin("Invalid choice");
ACTIVITY 8.2
226 )>
8 Programming
CONTINUED
Peer Assessment
Explain your choices in Activity 8.2 to a partner. Did they come to the same
conclusions as you did? Is there always a correct answer or are the different
points of view all valid?
227 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Make a list of the use of AND, OR and NOT in real-life situations. For
example, if one of two light switches is pressed then a light turns on. If the
door is locked and you have the key then you can unlock the door.
Peer Assessment
Share your list in groups of 3. Discuss each of the statements and whether
they have been correctly identified as AND, OR or NOT. Select one of each
Boolean operator and share it with the rest of the class.
Example 1
This will output the first message if both test marks are greater than or equal to 90.
If only one mark is greater than or equal to 90 then the second message will output.
OUTPUT("Enter the mark for test 1")
INPUT Markl
OUTPUT("Enter the mark for test 2")
INPUT Mark2
IF Markl >=90 AND Mark2 >=90 THEN
OUTPUT("Well done you got top marks on both tests")
ELSEIF Markl >= 90 OR Mark2 >=90 THEN
OUTPUT("Well done you got top marks on one of the tests")
ELSE
0UTPUT("You didn't quite get top marks on the tests, try again next time")
ENDIF
VB.NET
Dim markl As Integer
Console.WriteLine("Enter the mark for test 1")
markl = Console.ReadLine
Dim mark2 As Integer
Console.WriteLine("Enter the mark for test 2")
mark2 = Console.ReadLine
If markl >= 90 And mark2 >= 90 Then
Console.WriteLine("Well done you got top marks on both tests")
Elself markl >= 90 Or mark2 >= 90 Then
Console.WriteLine("Well done you got top marks on one test")
Else
Console.WriteLine("You didn't quite get top marks ont he tests, try again
next time")
End If
Python
markl = input("Enter the mark for test 1")
mark2 = input("Enter the mark for test 2")
if markl >= 90 and mark2 >= 90:
print("Well done you got top marks on both tests")
elif markl >= 90 or mark2 >= 90:
print("Well done you got top marks on one of the tests")
228
8 Programming
else:
print("You didn't quite get top marks on the tests, try again next time")
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter the mark for test 1");
Integer markl = Integer.parselnt(scanner.nextLineO);
System.out.printin("Enter the mark for test 2");
Integer mark2 = Integer.parselnt(scanner.nextLine());
if(markl >= 90 && mark2 >= 90){
System.out.printin("Well done you got top marks on both tests");
}else if(markl >=90 || mark2 >= 90){
System.out.printin("Well done you got top marks on one of the tests");
}else{
System.out.printin("You didn't quite get top marks on the tests, try
again next time");
}
}
Example 2
Output the highest number out of three that are input:
OUTPUT("Enter 3 numbers")
INPUT Numberl
INPUT Number2
INPUT Number3
IF Numberl > Number2 AND Numberl > Number3 THEN
OUTPUT(Numberl)
ELSEIF Number2 > Number3 THEN
OUTPUT(Number2)
ELSE
OUTPUT(Number3)
ENDIF
VB.NET
Dim numberl As Integer
Console.WriteLine("enter a number")
numberl = Console.ReadLine()
Dim number2 As Integer
Console.WriteLine("enter a number")
number2 = Console.ReadLine
Dim number3 As Integer
Console.WriteLine("enter a number")
number3 = Console.ReadLine
If numberl > number2 And numberl > number3 Then
Console.WriteLine(numberl)
Elself number2 > number3 Then
Console.WriteLine(number2)
Else
Console.WriteLine(number3)
End If
229 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
number1 = input("Enter a number")
number2 = input("Enter a number")
number3 = input("Enter a number")
if number1 > number2 and number1 > number3:
print(number1)
elif number2 > number3:
print(number2)
else:
print(number3)
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a number");
Integer number1 = Integer.parselnt(scanner.nextLine());
System.out.printin("Enter a number");
Integer number2 = Integer.parselnt(scanner.nextLine());
System.out.printin("Enter a number");
Integer number3 = Integer.parselnt(scanner.nextLine());
if(number1 > number2 && number1 > number3){
System.out.printin(numberl);
}else if(number2 > number3){
System.out.printIn(number2);
}else{
System.out.printIn(number3);
}
}
Practice
1 Discuss in pairs which type of selection statement would be most
appropriate for checking the symbol input.
2 Edit your program to use your chosen selection statement to check the
symbol the user has entered. Depending on the symbol, perform the
required calculation and output the result.
8 Programming
CONTINUED
Challenge
1 Discuss in pairs how the inputs could be repeatedly asked for until a valid
entry is given. For example, keep entering a symbol until one of the valid
ones is entered.
2 Implement your idea for repeatedly asking for the symbol to be input until
a valid one is entered.
3 Include additional mathematical operations, for example, power of, KEY WORDS
modulus division.
iteration: a
programming
construct. Code is
Questions run multiple times -
8 Describe what is meant by selection. either a finite number
9 Identify the two different examples of selection. of times (count-
controlled), until
10 Write a program that takes two numbers as input and outputs the largest.
a condition is true
11 Write a program that outputs a question (e.g. a maths question), takes an answer (post-condition), or
from a user and outputs if they are correct or not. while a condition is
12 Ask the user to input a colour. The program should then output a different true (pre-condition),
message if the user enters the word "yellow", "green" or "blue".
If neither of these are entered, the program should output a different message. loop: another name
Use a CASE statement. for iteration.
count-controlled
loop: a type of
8.7 Iteration iteration. Code is run
a finite number of
An iteration or loop is a programming construct where statements are run either a finite times. Usually a for
number of times, until a condition is true or while a condition is true. loop.
There are three types of loop: count-controlled, pre-condition and post-condition. pre-condition loop:
a type of iteration.
Code is run while the
Count-controlled condition is true. The
This type of loop uses a counter to run a set number of times. The most common condition is checked
count-controlled loop is the for loop. This has the structure: before running any
code in the loop,
FOR variable <- start value TO endvalue therefore the code
Code that runs repeatedly might never run.
NEXT variable
post-condition loop:
The loop will run from the start value to the end value, increasing by l each time. If the
a type of iteration.
start value is 1 and the end value is 10, it will run 10 times (1,2, 3, 4, 5, 6, 7, 8, 9 and 10).
Code is run until a
condition is true. The
Example 1 condition is checked
Output the numbers 1 to 10: after the code in the
loop is run, therefore
FOR X <- 1 TO 10 the code always runs
OUTPUT(X)
once.
NEXT X
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
VB.NET
For x = 1 To 10
Console.WriteLine(x)
Next
Python
for x in range(1, 11):
print(x)
Java
public static void main(String args[]){
for(Integer x = 1; x <= 10; x++){
System.out.printin(x);
}
}
Example 2
Output the 12 times table from 1 to 12:
FOR Count <- 1 TO 12
OUTPUT(Count * 12)
NEXT Count
VB.NET
For count = 1 To 12
Console.WriteLine(count * 12)
Next
Python
for count in range (1, 13):
print(count * 12)
Java
public static void main(String args[]){
for(Integer count = 1; count < 13; count++){
System.out.printIn(count * 12);
}
}
8 Programming
Example 3
Add together the first 100 numbers:
Total <- 0
FOR Number <- 1 TO 100
Total <- Total + Number
NEXT Number
VB.NET
Dim total As Integer = 0
For number = 1 To 100
total = total + number
Next
Python
total = 0
for number in range(1, 101):
total = total + number
Java
public static void main(String args[]){
Integer total = 0;
for(Integer number = 1; number <= 10; number++){
total = total + number;
}
}
You can change the amount that you increase the variable by each time you loop. This is by using STEP. STEP 1 will
increase the counter by 1 each time. STEP -1 will decrease the counter by 1 each time. STEP 0.5 will increase the
counter by 0.5 each time.
Example 1
Output the numbers 10 to 1:
FOR Number 10 TO 1 STEP -1
OUTPUT(Number)
NEXT Number
VB.NET
For number = 10 To 1 Step -1
Console.WriteLine(number)
Next
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
for number in range (10, 0, -1):
print(str(number))
Java
public static void main(String args[]){
for(Integer number = 10; number >= 1; number--){
System.out.printIn(number);
}
}
Example 2
Output the numbers from 11 to 20, increasing by 0.5 each time. (No example is given for Python as it does not support
stepping in decimals.)
FOR Value <- 11 TO 20 STEP 0.5
OUTPUT(Value)
NEXT Value
VB.NET
For value = 11 To 20 Step 0.5
Console.WriteLine(value)
Next
Java
public static void main(String args[]){
for(Double value = 11.0; value <= 20.0; value += 0.5){
System.out.printin(value);
}
}
Pre-condition
A pre-condition loop tests the condition before starting the loop. This means that if the condition is false, the code
inside the loop will not run. It loops while the condition is true. It stops looping when the condition is false.
A WHILE loop is a pre-condition loop. It has the structure:
WHILE condition DO
Code that will run when the condition is true
ENDWHILE
234 )>
8 Programming
Example 1
Looping while the user enters “Yes”.
Inputvalue <- "Yes"
WHILE Inputvalue = "Yes" DO
Inputvalue <- INPUT("Do you want to continue?")
ENDWHILE
VB.NET
Dim inputvalue As String = "Yes"
While inputvalue = "Yes"
Console.WriteLine("Do you want to continue?")
inputvalue = Console.ReadLine
End While
Python
inputvalue = "Yes"
while inputvalue == "Yes":
inputvalue = input("Do you want to continue?")
Java
public static void main(String args[]){
String inputvalue = "Yes";
Scanner scanner = new Scanner(System.in);
while(inputvalue.equals("Yes")){
System.out.printin("Do you want to continue?");
inputvalue = scanner.nextLine();
}
}
Example 2
Outputting the numbers I to 10:
Number <- 1
WHILE Number < 11 DO
OUTPUT(Number)
Number «- Number + 1
ENDWHILE
VB.NET
Dim number As Integer = 1
While number < 11
Console.WriteLine(number)
number = number + 1
End While
235 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
number = 1
while number < 11:
print(str(number))
number = number + 1
Java
public static void main(String args[]){
Integer number = 1;
while(number < 11){
System.out.printIn(number);
number++;
}
}
Example 3
Asking the user to enter a number until they guess the stored number correctly:
Number <- 5
Guessed <- FALSE
WHILE Guessed = FALSE DO
OUTPUT("Guess the number")
INPUT Guess
IF Guess = Number THEN
Guessed <- TRUE
ENDIF
ENDWHILE
VB.NET
Dim number As Integer = 5
Dim guessed As Boolean = False
While guessed = False
Console.WriteLine("Guess the number")
number = Console.ReadLine
If guessed = number Then
guessed = True
End If
End While
Python
number = 5
guessed = False
while guessed == False:
guess = int(input("Guess the number"))
if guess == number:
guessed = True
8 Programming
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer number = 5;
Boolean guessed = false;
while(guessed == false){
System.out.printin("Guess the number");
Integer guess = Integer.parselnt(scanner.nextLine());
if(guess == number){
guessed = true;
}
}
)
Post-condition loop
A post-condition loop runs the code inside the loop once, and then checks the
condition at the end of the loop. This means that the code will always run once.
A REPEAT UNTIL loop is a post-condition loop. It has the structure:
REPEAT
Code that runs inside the loop
UNTIL Condition
In this case it continues until the Condition becomes True. It loops while the condition
is False.
Example 1
Looping until the user enters Yes. (No example is given for Python as it does not have
an in-built post-condition loop.)
REPEAT
OUTPUT("Do you want to stop?")
INPUT Answer
UNTIL Answer = "Yes"
VB.NET
Dim answer As String
Do
Console.WriteLine("Do you want to stop?")
answer = Console.ReadLine
Loop Until answer = "Yes"
Java
Java has a do while loop, so it loops while the condition is true, not until it is true,
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String answer = "Yes";
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 2
Outputting the numbers 1 to 10. (No example is given for Python as it does not have an
in-built post-condition loop.)
Number <- 1
REPEAT
OUTPUT(Number)
Number <- Number + 1
UNTIL Number >10
VB.NET
Dim number As Integer = 1
Do
Console.WriteLine(number)
number = number + 1
Loop Until number > 10
Java
public static void main(String args[]){
Integer number = 1;
do {
System.out.printIn(number);
number++;
}while(number <= 10);
}
Example 3
Asking the user to enter a number until they guess the correct number. (No example is
given for Python as it does not have an in-built post-condition loop.)
NumberToGuess <- 15
REPEAT
OUTPUT("Guess the number")
INPUT Guess
UNTIL Guess = NumberToGuess
VB.NET
Dim numberToGuess As Integer = 15
Dim guess As Integer
8 Programming
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer numberToGuess = 15;
Integer guess;
do{
System.out.printin("Guess the number");
guess = Integer.parselnt(scanner.nextLine());
}while(numberToGuess != guess);
}
239 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Step 1: Declare the variable used as the counter. In this example the variable is
x, the value is 1.
Step 2: Take the last value and put it in the while loop condition. In this
example loop until it is 10, so the condition is while x < 11.
Step 3: Increment the counter in the loop. The counter is x so x needs to have 1
added to it.
X = 1 (Step 1)
WHILE X < 11 DO (Step 2)
OUTPUT(X)
X <- X + 1 (Step 3)
ENDWHILE
Questions
1 Convert the following FOR loop to a WHILE loop.
FOR Count <- 0 TO 100
OUTPUT(Count + Count)
NEXT
240 >
8 Programming
Questions
13 Describe the difference between a pre-condition and post-condition loop.
14 A program needs a loop that will run 50 times. Which type of loop would be most
appropriate?
15 Write a program to output the numbers 100 to 200.
16 Write a program to output the 5 times table (from 5 times l, to 5 times 12).
17 Write a program to ask the user to enter a number continually, until they enter the
number 10, using a post-condition loop.
18 Write a program to output the word “Hello” until the user enters the word “stop”,
using a pre-condition loop.
19 Convert the following count-controlled loop to a pre-condition loop.
FOR Counter <- 1 to 10
OUTPUT(Counter * Counter)
NEXT Counter
Totalling is adding together a set of values. To write a program to total you need to: totalling a type of
program, it adds up
• Initialise the total to 0.
multiple values to
• Add the values together (either individually or within a loop). find the total.
Example 1
Asking the user to enter 10 numbers and totalling them:
Total <- 0
FOR Counter <- 0 TO 10
OUTPUT("Enter a number")
Total <- Total + INPUT
NEXT Counter
OUTPUTC'The total is " & Total)
VB.NET
Dim total As Integer = 0
For counter = 0 To 10
Console.WriteLine("Enter a number")
total = total + Console.ReadLine
Next
Console.WriteLine("The total is " & total)
Python
total = 0
for counter in range(0, 11):
total = total + int(input("Enter a number"))
print("The total is", total)
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer total = 0;
for(Integer counter = 0; counter < 11; counter++){
System.out.printin("Enter a number");
total = total + Integer.parselnt(scanner.nextLine());
}
System.out.printin("The total is " + total);
}
Example 2
Total the data in an array of 100 elements:
Total <- 0
FOR Count 0 TO 99
Total <- Total + ArrayData[Count]
NEXT Count
OUTPUT(Total)
VB.NET
Dim total As Integer = 0
Dim arrayData(99) As Integer
'insert code to populate array
For count = 0 To 99
total = total + arrayData(count)
Next
Console.WriteLine(total)
Python
total = 0
arrayData^ []
#insert code to populate array
for count in range(0, 100):
total = total + arrayData[count]
print(str(total) )
Java
public static void main(String args[]){
Integer total = 0;
Integer[] arrayData = new Integer[100];
//insert code to populate array
for(Integer count = 0; count < 100; count++){
total = total + arrayData[count];
}
System.out.printin(total);
}
8 Programming
Counting is working out how many of something there are. For example how many counting: a type of
numbers were entered that were over 10. To write a program to count you need to: program, it adds one
for every item to find
• Initialise a counter variable to 0.
out how many there
• Increment (add one to) the counter each time an item is entered, or found. are.
Example 1
Count how many numbers the user enters until they say to stop:
Count <- 0
Continue <- "Yes"
WHILE Continue = "Yes" DO
OUTPUT("Do you want to continue?")
INPUT Continue
Count <- Count + 1
ENDWHILE
OUTPUT("You continued " & Count - 1 & " times")
VB.NET
Dim count As Integer = 0
Dim continueLoop As String = "Yes"
While continueLoop = "Yes"
Console.WriteLine("Do you want to continue?")
continueLoop = Console.ReadLine
count = count + 1
End While
Console.WriteLine("You continued " & count-1 & " times")
Python
count = 0
continuelnput = "Yes"
while continuelnput == "Yes":
continuelnput = input("Do you want to continue?")
count = count + 1
print("You continued", str(count-1), "times")
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter the first number");
Integer count = 0;
String continuelnput = "Yes";
while(continuelnput.equals("Yes")){
System.out.printin("Do you want to continue?");
continuelnput = scanner.nextLine();
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
count = count + 1;
}
count = count - 1;
System.out.printin("You continued " + count + " times");
}
Example 2
Count how many numbers in an array of 100 elements are more than 50:
Count <- 0
FOR X <- 0 TO 99
IF ArrayData[X] > 50 THEN
Count <- Count + 1
ENDIF
NEXT X
VB.NET
Dim arrayData(99) As Integer
'insert code to populate array
Python
count = 0
arrayData=[]
#insert code to populate array
for x in range(0, 100):
if arrayData[x] > 50:
count = count + 1
Java
public static void main(String args[]){
Integer[] arrayData = new Integer[100];
//insert code to populate array
Integer count = 0;
for(Integer x = 0; x < 100; x++){
if (arrayData[x] > 50){
count = count + 1;
}
}
244 )>
8 Programming
Questions
20 What are the two required elements for a totalling program.
21 What are the two required elements for a counting program.
22 Write a program to ask the user to input 100 numbers, total the values and output
the total.
23 Write a program to ask the user to input numbers. Count how many numbers are
less than 100, and how many are more than or equal to 100. Stop when the user
enters the number 0.
Length
This command will return the number of characters in a string. It has the structure:
LENGTH(string).
Example 1
LENGTH ("hi ") would return 2.
VB.NET
Dim stringLength As Integer
stringLength = Len("hi")
Python
stringLength = len("Hi")
Java
public static void main(String args[]){
Integer stringLength = ("hi").length();
}
Example 2
LENGTH (" 0123 ") would return 4.
VB.NET
Dim stringLength As Integer
stringLength = Len("0123")
245 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
stringLength = len("0123")
Java
public static void main(String args[]){
Integer stringLength = ("0123").length();
}
Substring
This command will return some of the characters in the string. It has the structure:
SUBSTRING(string, start character, number of characters).
Depending on your language, the first character could be in position 0 or position 1.
Example 1
Using substring:
SUBSTRING ("Hello", 0, 1) This will start at character 0 and take 1 character.
It will return "H".
VB.NET
(Uses 1 for the first character.)
Dim substring As String
substring = Mid("Hello", 1, 1)
Python
(Uses 0 for the first character.)
substring = "Hello"[0:1]
print(substring)
Java
public static void main(String args[]){
String substring = ("Hello").substring(0,1);
System.out.printin(substring);
}
Example 2
Using substring:
SUBSTRING (" Goodbye", 4 , 3 ). This will start at character 4 and take
3 characters. It will return "bye".
246 >
8 Programming
VB.NET
Dim substring As String
substring = Mid("Goodbye", 5, 3)
Python
substring = "Goodbye"[4:7]
Java
public static void main(String args[]){
String substring = ("Goodbye").substring(5z 3);
}
Example 3
Output the length of a string that the user inputs:
Inputstring <- INPUT("Enter a string")
StringLength <- LENGTH(Inputstring)
OUTPUT(Inputstring & " is " & StringLength & " characters long")
VB.NET
Dim inputstring As String
Console.WriteLine("Enter a string")
inputstring = Console.ReadLine
Dim stringlength As Integer
stringlength = Len(inputstring)
Console.WriteLine(inputstring & " is " & stringlength & " characters long")
Python
inputstring = input("Enter a string")
StringLength = len(inputstring)
print(inputstring, " is ", str(StringLength), " characters long")
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a string");
String inputstring = scanner.nextLine();
Integer StringLength = inputstring.length();
System.out.printin(inputstring + " is " + StringLength + " characters long");
}
247 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 4
Output the first 4 characters in a string:
StringData <- "Goodbye"
NewMessage <- SUBSTRING(StringData, 0, 4)
OUTPUT(NewMessage)
VB.NET
Dim StringData As String = "Goodbye"
Dim newMessage As String
newMessage = Mid(StringData, 1, 4)
Console.WriteLine(newMessage)
Python
StringData = "Goodbye"
newMessage = StringData[0:4]
print(newMessage)
Java
public static void main(String args[]){
String StringData = "Goodbye";
String newMessage = StringData.substring(0,4);
System.out.printIn(newMessage);
}
Example 5
Output each letter of a string one character at a time. Depending on your language,
the stopping condition might be the length, or the length -1 depending on
whether the first character is 0 or 1.
OUTPUT("Enter a message")
INPUT Stringinput
FOR Count <- 0 to LENGTH (Stringinput) - 1
Character <- SUBSTRING(Stringinput, Count, 1)
OUTPUT(Character)
NEXT Count
VB.NET
Dim stringinput As String
Console.WriteLine("Enter a message")
stringinput = Console.ReadLine
Dim character As String
For count = 1 To Len(stringinput)
character = Mid(stringinput, count, 1)
Console.WriteLine(character)
Next
248 y
8 Programming
Python
stringinput = input("Enter a message")
for count in range(0, len(stringinput)):
character = stringinput[count:count+l]
print(character)
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a message");
String stringinput = scanner.nextLine();
String character;
for(Integer count = 0; count < stringinput.length(); count++){
character = stringinput.substring(count, count+l);
System.out.printIn(character);
}
}
Example 6
Output the last 3 characters in a string:
OUTPUT("Enter a message")
INPUT Stringinput
NewString «- SUBSTRING(Stringinput, LENGTH(Stringinput) - 3, 3)
OUT PUT(NewString)
VB.NET
Dim stringinput As String
Console.WriteLine("Enter a message")
stringinput = Console.ReadLine
Dim newString As String
newString - Mid(stringinput, Len(stringinput) - 2Z 3)
Console.WriteLine(newString)
Python
stringinput = input("Enter a message")
newString = stringinput[len(stringinput)-3:]
print(newString)
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printIn("Enter a message");
String stringinput = scanner.nextLine();
String newString = stringinput.substring(stringinput.length()-3, stringinput,
length());
System.out.printin(newString);
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 1
Using UPPER with a string:
UPPER("Hello") will return "HELLO"
VB.NET
Word = "Hello".toUpper()
Python
Word = "Hello".upper()
Java
Word =- "Hello".toUpperCase();
Example 2
Using LOWER with a string stored in a variable:
Word <- "HELLO"
Word «- LOWER (Word)
VB.NET
word = "HELLO"
word = word.toLower()
Python
word = "HELLO"
word = word.lower()
Java
word = "HELLO";
word = word.toLowerCase();
8 Programming
When you need to create a password for a website or computer there are
usually rules you have to follow; e.g. more than 8 characters, at least one
lowercase letter, at least one uppercase letter, one special character, etc. The
length function you have just learnt can be used to work out if the password
is long enough. You can also use the substring function by checking each
character one at a time to work out if it is a special character (e.g. / ! ?, etc.).
You don't need to know about cases for the specification, but you can research
how to find out about a character in upper case, or lowercase as well. Put
them all together and you can write a program to check if a password is valid.
A nested statement is one or more selection and/or iteration statements inside another nested statement: a
selection/iteration statement. This could be an IF statement inside an IF statement or a construct (selection
loop inside an IF statement or an IF statement in a loop or a loop within a loop. You or iteration) that
might have already used these without realising they were called nested statements. is inside another
construct.
The position of the start and end of these constructs are important. If, for example, a
loop starts inside an IF statement, the loop must also finish inside the same IF statement.
Example 1
Count how many numbers entered are more than 10, and how many are equal to 10:
MoreThanlO <- 0
EqualTolO <- 0
FOR X <- 0 TO 99
OUTPUT("Enter a number")
INPUT Number
IF Number >10 THEN
MoreThanlO <- MoreThanlO + 1
ELSEIF Number =10 THEN
EqualTolO <- EqualTolO + 1
ENDIF
NEXT X
This code has an IF statement nested inside a count-controlled loop.
VB.NET
Dim moreThanlO As Integer = 0
Dim equalTolO As Integer = 0
Dim number As Integer
For x = 0 To 99
Console.WriteLine("Enter a number")
number = Console.ReadLine
If number > 10 Then
moreThanlO = moreThanlO + 1
Elself number = 10 Then
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
equalTolO = equalTolO + 1
End If
Next
Python
moreThanlO = 0
equalTolO = 0
for x in range(0, 100):
number = int(input("Enter a number"))
if number > 10:
moreThanlO = moreThanlO + 1
elif number = 10:
equalTolO = equalTolO + 1
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
Integer moreThanlO = 0;
Integer equalTolO = 0;
for(Integer x = 0; x < 100; x++){
System.out.printin("Enter a number");
Integer number = Integer.parselnt(scanner.nextLine());
if(number > 10){
moreThanlO +=1;
}else if(number == 10){
equalTolO +=1;
}
Example 2
Loop counting how many values in an array are more than or equal to 100, and then
stop counting:
Number <- 0
Count <- 0
WHILE Number < 10 DO
DatalnArray <- ArrayData[Count]
Count <- Count + 1
IF DatalnArray >= 100 THEN
Number <- Number + 1
ENDIF
ENDWHILE
This has an IF statement inside a pre-condition loop.
8 Programming
VB.NET
Dim number As Integer = 0
Dim count As Integer = 0
Dim dataArray(999) As Integer
'insert code to populate array
Python
arrayData = []
#insert code to populate array
number = 0
count = 0
while number < 10:
datalnArray = arrayData[count]
count = count + 1
if datalnArray >= 100:
number = number + 1
Java
public static void main(String args[]){
Integer[] dataArray = new Integer[1000];
//insert code to populate array
Integer number = 0;
Integer count = 0;
Integer datalnArray = 0;
while(number < 10){
datalnArray = dataArray[count];
count +=1;
if(datalnArray >= 100){
number +=1;
}
}
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 3
Output only the vowels in a message input if user selects option 1:
OUTPUT("Enter 1 or 2")
INPUT Choice
IF Choice = 1 THEN
OUTPUT("Enter a word")
INPUT Word
FOR Count <- 0 to LENGTH (Word)-1
Character <- SUBSTRING(Word, Count, 1)
IF Character = "a" OR Character = "e" OR Character = "I"
OR Character = "o" OR Character = "u" THEN
OUTPUT(Character)
ENDIF
NEXT Count
ENDIF
This has a FOR loop inside an IF, and another IF inside the FOR loop.
VB.NET
Dim choice As Integer
Console.WriteLine("Enter 1 or 2")
choice = Console.ReadLine
Dim word As String
Dim character As String
If choice = 1 Then
Console.WriteLine("Enter a word")
word = Console.ReadLine
For count = 0 To Len(word)
character = mid(word, count, 1)
If character = "a" Or character = "e" Or character = "i" Or character =
"o" Or character = "u" Then
Console.WriteLine(character)
End If
Next
End If
Python
choice = int(input("Enter 1 or 2"))
if choice == 1:
word = input("Enter a word")
for count in range(0, len(word)):
character = word[count:count+1]
if character == "a" or character == "e" or character == "i" or character
== "o" or character == "u":
print(character)
8 Programming
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter 1 or 2");
String word;
String character;
Integer choice = Integer.parselnt(scanner.nextLine());
if(choice == 1){
System.out.printin("Enter a word");
word = scanner.nextLine();
for(Integer count = 0; count < word.length(); count++){
character = word.substring(count, count + 1);
if(character.equals("a") || character.equals("e") || character,
equals("i") || character.equals("o") || character.equals("u")){
System.out.printIn(character) ;
}
}
}
}
Questions
24 Give one example of a nested statement.
25 What will the pseudocode statement LENGTH ("Hello World! ") return?
26 What will the pseudocode statement SUBSTRING (" HELLO WORLD! ", 6, 5)
return?
27 Write a program to take a string input from the user, count out how many
numbers are in the string and output the count.
28 Write a program to output a string value backwards. KEY WORDS
subroutine: a self-
contained piece of
8.12 Subroutines code that has an
A subroutine is a self-contained piece of code that has an identifier (name), and it can identifier and can be
called from elsewhere
be called from anywhere in the main program.
in a program.
When you decompose a problem into sub-systems, each of the sub-systems can be
written as an individual subroutine. You can then call that subroutine when you need procedure: a
to use it. subroutine that does
not return a value
Subroutines are useful because they reduce code. You write the subroutine once, and to the program that
then you can call it as many times as you need to, instead of having to re-write it every called it.
time. Each time you re-write it there is a chance of an error, so this reduces the chances
of this error. function: a subroutine
that does return a
There are two types of subroutine: procedures and functions. A function returns a value
value to the program
to the program that called it. A procedure does not return a value.
that called it.
Procedures and functions can both take one or more values as parameters. These are
parameter: a value
values that are sent to the subroutine. Parameters will be introduced after the basics of
procedures and functions. that is sent to a
subroutine.
255 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Procedures
A procedure runs the code inside it, and does not return a value. The structure of a
procedure is:
PROCEDURE identifier^
code to run inside the function
ENDPROCEDURE
The identifier is then used in the main program.
Example 1
A procedure to output the numbers I to 10:
PROCEDURE OutputlTolO()
FOR Count <- 1 to 10
OUTPUT(Count)
NEXT Count
ENDPROCEDURE
The main program can then call the procedure with the code:
OutputlTolO()
VB.NET
Sub Main()
OutputlTolO()
End Sub
Sub OutputlTolO()
For count = 1 To 10
Console.WriteLine(count)
Next
End Sub
Python
def OutputlTolO():
for count in range(1, 11):
print(str(count))
OutputlTolO()
Java
public static void OutputlTolO(){
for(Integer count = 0; count < 11; count++){
System.out.printIn(count);
}
}
public static void main(String args[]){
OutputlTolO();
}
8 Programming
Example 2
A procedure to take two numbers from the user and multiply then together:
PROCEDURE Multiply()
OUTPUT("Enter a number")
INPUT Numl
OUTPUT("Enter a second number")
INPUT Num2
Total <- Numl * Num2
ENDPROCEDURE
The procedure can be called in the main program with the code:
multiply()
VB.NET
Sub Main()
multiply()
End Sub
Sub multiply()
Dim numl As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Dim num2 As Integer
Console.WriteLine("Enter a second number")
num2 = Console.ReadLine
Dim total As Integer
total = numl * num2
End Sub
Python
def multiply():
numl = int(input("Enter a number"))
num2 = int(input("Enter a second number"))
total = numl * num2
multiply()
Java
public static void multiply(){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a number");
Integer numl = Integer.parselnt(scanner.nextLine());
System.out.printin("Enter a number");
Integer num2 = Integer.parselnt(scanner.nextLine());
Integer total = numl * num2;
}
public static void main(String args[]){
multiply();
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Function
A function returns a value to the program that called it. This can be by either using
the RETURN command, or saving a value to the function’s identifier. Once a value is
returned, the function stops running, so it cannot have any code after otherwise this
will not run.
It has the structure:
FUNCTION identifier^
Code to run in the function
RETURN value
ENDFUNCTION
When the function is called it returns a value, so something needs to happen with this
value. It could be output, e.g.
OUTPUT(function identifier)
or it could be saved in a variable, e.g.
variable identifier= function identifier
Example 1
Write a function to ask the user to enter two values, add them together and return
the value:
FUNCTION Multiply()
OUTPUT("Enter a number")
INPUT Numl
OUTPUT("Enter another number")
INPUT Num2
RETURN Numl * Num2
ENDFUNCTION
To output the return value the main program can use:
OUTPUT(Multiply())
VB.NET
Sub Main()
Console.WriteLine(multiply())
End Sub
Function multiply()
Dim numl As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Dim num2 As Integer
Console.WriteLine("Enter a second number")
num2 = Console.ReadLine
Return numl * num2
End Function
258 >
8 Programming
Python
def multiply():
numl = int(input("Enter a number"))
num2 = int(input("Enter another number"))
return numl * num2
print(str(multiply()))
Java
public static Integer multiply(){
Scanner scanner = new Scanner(System.in);
vSystem.out.printIn("Enter a number");
Integer numl = Integer.parselnt(scanner.nextLine());
System.out.printIn("Enter a second number");
Integer num2 = Integer.parselnt(scanner.nextLine());
return(numl * num2);
}
public static void main(String args[]){
System.out.printin(multiply());
}
Example 2
Write a function to total all the values in an array with 50 elements and then
return the total:
FUNCTION Totalvalues()
Total <- 0
FOR X 0 TO 49
Total <- Total + Array [X]
NEXT X
RETURN Total
ENDFUNCTION
To store the return value in a variable in the main program:
Total = Totalvalues()
VB.NET
Sub Main()
Dim total As Integer
total = totalvalues()
End Sub
Function totalvalues()
Dim arrayData(49) As Integer
'insert code to populate array
Dim total As Integer = 0
For x = 0 To 49
total = total + arrayData(x)
Next
Return total
End Function
259 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
def totalvalues():
arrayData = []
#insert code to populate array
total = 0
for x in range(0, 50):
total = total + arrayData[x]
return total
total = totalvalues()
Java
public static Integer totalvalues(){
Integer[] arrayData = new Integer[50];
//insert code to populate array
Integer total = 0;
for(Integer x = 0; x < 50; x++){
total = total + arrayData[x];
}
return total;
}
public static void main(String args[]){
Integer total = totalvalues();
}
The scope of a variable is the areas within a program that it can be accessed. scope: the sections in
There are two scopes: global and local. the code where the
variable, or constant,
If you declare a variable (or constant, or array) as global then it means it can be
can be accessed.
accessed by any part of the program. That includes the main program and any
subroutines. In most languages this means declaring it at the top of the program. global scope: the
variable or constant
Example 1 can be accessed
from any part of the
Declaring a global variable, then outputting its value twice. Once in the main program,
program.
and once in a procedure call call.
GLOBAL Data local scope: the
PROCEDURE OutputData() variable or constant
OUTPUT(Data) can only be accessed
ENDPROCEDURE in the subroutine it is
//main program declared within.
Data «- 1
OUTPUT(Data)
OutputData()
260 y
8 Programming
VB.NET
Module Program
Dim data As Integer
Sub outputData()
Console.WriteLine(data)
End Sub
Sub Main(args As String())
data = 1
Console.WriteLine(data)
outputData()
End Sub
End Module
Python
data = 1
def outputData():
print(str(data))
print(str(data))
outputData()
Java
class outputtingf
static Integer data = 1;
public static void outputData(){
System.out.printIn(data);
}
public static void main(String args[]){
System.out.printin(data);
outputData();
}
}
If you declare a variable (or constant, or array) as local, then it can only be accessed
in the part of the code where it is declared. If you declare it first in a subroutine,
then it can only be accessed within that subroutine. If you declare it in the main
program, it can only be accessed in the main program.
Example 2
Creating a local variable to the main program and outputting it twice. Once in the main
program, and once from a subroutine where it is sent as a parameter.
PROCEDURE OutputData(DataParameter)
OUTPUT(DataParameter)
ENDPROCEDURE
Data <- 1
OUTPUT(DataParameter)
OutputData(Data)
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
VB.NET
Module Program
Sub outputData(dataParameter)
Console.WriteLine(dataParameter)
End Sub
Sub Main(args As String())
Dim data As Integer
data = 1
Console.WriteLine(data)
outputData(data)
End Sub
End Module
Python
def outputData(dataParameter):
print(str(dataParameter))
#main
data = 1
print(str(data))
outputData(data)
Java
class outputting{
public static void outputData(Integer dataParameter){
System.out.printin(dataParameter);
}
public static void main(String args[]){
Integer data = 1;
System.out.printIn(data);
outputData(data);
}
}
Best practice restricts the use of global variables, because their memory is taken for the
whole of the program and nothing else can use that memory space. If you declare them
locally then when that part of the program finishes the memory location is freed. Local
variables are more tricky to program because you need to send them as parameters
between functions and make sure you return them back if they have changed.
Parameters
A parameter is a value that is sent from the main program to the subroutine (procedure
or function). Parameters are declared inside the brackets after the subroutines name, e.g.
PROCEDURE identifier (parameter!., parameter2 ...)
ENDPROCEDURE
262 >
8 Programming
Example 1
A function takes two numbers, divides them and returns the result:
FUNCTION Division(First, Second)
RETURN First / Second
ENDFUNCTION
The main program sends 10 and 2, then outputs the return value.
OUTPUT(Division(10, 2))
VB.NET
Sub Main()
Console.WriteLine(division(10, 2))
End Sub
Function division(first, second)
Return first / second
End Function
Python
def division(first, second):
return first / second
print(str(division(10,2)))
Java
public static Double division(Double first, Double second)
{
return (first / second);
)
public static void main(String args[]){
System.out.printin(division(10.0,2.0));
}
263 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 2
A procedure takes 2 values and outputs all the numbers between the first number to
the second:
PROCEDURE OutputNumbers(Numl, Num2)
FOR Count <- Numl TO Num2
OUTPUT Count
NEXT Count
ENDPROCEDURE
The main program taking two values from the user.
OUTPUT("Enter the smallest number")
INPUT FirstNumber
OUTPUT("Enter the largest number")
INPUT SecondNumber
OutputNumbers(FirstNumber, SecondNumber)
VB.NET
Sub Main()
Console.WriteLine("Enter the smallest number")
Dim firstNumber As Integer = Console.ReadLine
Console.WriteLine("Enter the largest number")
Dim SecondNumber As Integer = Console.ReadLine
OutputNumbers(firstNumber, SecondNumber)
End Sub
Sub OutputNumbers(numl, num2)
For count = numl To num2
Console.WriteLine(count)
Next
End Sub
Python
def OutputNumbers(numl, num2):
for count in range(numl, num2+l):
print(str(count))
Java
public static void OutputNumbers(Integer numl, Integer num2){
for(Integer count = numl; count <= num2; count++){
System.out.printin(count);
8 Programming
Questions
29 What is the difference between a function and a procedure?
30 Consider the following function:
FUNCTION Calculate(Numl, Num2)
Numl <- Numl * 2
Num2 <- Num2 + Numl
RETURN(Numl + Num2)
ENDFUNCTION
What will the following statement output?
OUTPUT(Calculate(1,2))
31 Write a program statement to call the following function with the parameter 100
and output the return value.
FUNCTION FindValue(Number)
Number <- Number + INPUT
RETURN Number
ENDFUNCTION
32 Write a procedure to take three numbers as parameters and output the largest.
33 Write a function that takes two strings as parameters. It takes the first 3 characters
of each string and combines them, returning the resulting string.
Two other library routines that you need to know are ROUND and RANDOM. library routine:
a pre-written
subroutine that can
ROUND be called from within
a program.
This will take a real number (decimal) and limit how many numbers there are after the
decimal point.
265 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
For example ROUND (10.123, 1) will take the number 10.123 and only leave 1
number after the decimal point, returning 10.1.
ROUND(4.8293, 2) will return 4.82.
As with functions, the values it returns need to be used. This could be done by
outputting the return value, or saving it in a variable, e.g.
RoundedValue ROUND (77.2 93 , 1)
VB.NET
Dim roundedValue As Single
roundedValue = Math.Round(77.293, 1)
Python
roundedValue = round(77.293,1)
Java
public static void main(String args[]){
double value = Math.round(77.23 * 10.0) / 10.0;
}
RANDOM
This will generate a random number between two values that it takes as parameters.
For example, RANDOM (10, 2 0) will return a number between 10 and 20.
ACTIVITY 8.4
VB.NET
Dim randomNumber As Integer
Dim rand As Random = New Random
randomNumber = rand.Next(1, 101)
8 Programming
Python
import random
randomNumber = random.randint(1, 100)
Java
public static void main(String args[]){
Random rand = new Random();
Integer randomNumber = rand.nextlnt(1000) + 1;
}
A comment is a description of a line of code, or section of code. To write a comment comment: text
you use a special character or characters, for example, II. This tells the program not to within a program to
execute the text after this symbol. describe its function,
it is not executed
You do not need to comment every line of code, for example, the statement Count
when the program
does not need commenting, it is clear that it is storing 0 in the variable count.
is run.
Example 1
The function of the FOR loop is written as a comment:
FOR Count <- 0 TO 9 //Output the first 10 elements in the array
OUTPUT(Array[Count])
NEXT Count
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
VB.NET
For count = 0 To 9 'output the first 10 elements in the array
Console.WriteLine(arrayData(count))
Next
Python
for count in range(0, 10): output the first 10 elements in the array
print(arrayData[count])
Java
public static void main(String args[]){
Integer[] arrayData = new Integer[10];
//insert code to populate the array
Example 2
OUTPUT("Enter a number")
INPUT Numl
OUTPUT("Enter a number")
INPUT Num2
//find and output the largest number
IF Numl > Num2 THEN
OUTPUT(Numl)
ELSE
OUTPUT(Num2)
ENDIF
VB.NET
Dim numl As Integer
Dim num2 As Integer
Console.WriteLine("Enter a number")
numl = Console.ReadLine
Console.WriteLine("Enter a number")
num2 = Console.ReadLine
Python
numl = int(input("Enter a number"))
num2 = int(input("Enter a number"))
# find and output the largest number
i f numl > num2:
print(str(numl))
else:
print(str(num2))
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.printin("Enter a number");
Integer numl = Integer.parselnt(scanner.nextLine());
System.out.printIn("Enter a number");
Integer num2 = Integer.parselnt(scanner.nextLine());
i f(numl > num2){
System.out.printIn(numl);
}else{
System.out.printin(num2)
}
}
Subroutines
Subroutines help to split the code down into sections, especially when one subroutine
may need to be called multiple times. This means that if you need to make any
changes then you only need to make them once. For more on subroutines, look back
at section 8.12.
ACTIVITY 8.5
Open a computer program that you have written. Check its maintainability.
Edit the program to improve the maintainability. Present your before and after
program and explain how you improved its maintainability.
Questions
34 Explain how subroutines help make a program maintainable.
35 Describe two other ways of making a program maintainable.
36 Write a program statement to generate a random number between 1 and 5.
37 Identify the result from the statement ROUND (3.142 , 1).
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
This array has 5 spaces. Each space has an index. In this array the first data item is in
position 0, the data value is 10. In the second array space (index 1), the number 5 is
stored.
Arrays can be 0-indexed or 1-indexed. This depends on the programming language that
you use. Some arrays start with 0 as the first space. Some arrays start with 1 as the first
space.
Arrays use brackets after the identifier to indicate the index you want to access.
For example, Array [ 0 ] is accessing the first element in the array named Array.
MyData [ 3 ] is accessing the fourth element in the array named MyData.
Example 1
Store the colour "red" in the first position of the array named Colour:
Colour [0] <- "red"
VB.NET
Dim colour(0) As String
colour(0) = "red"
Python
colour = ["" ,""]
colour[0] = "red"
8 Programming
Java
public static void main(String args[]){
String[] colour = new String[1];
colour[0] = "red";
}
Example 2
Store the colour "yellow" in the second position of the array named Colour:
Colour [1] <- "yellow"
VB.NET
Dim colour(1) As String
colour(1) = "yellow"
Python
colour = [" " , " " ]
colour[1] = "yellow"
Java
public static void main(String args[]){
String[] colour = new String[2];
colour[1] = "yellow";
}
Example 3
Store the number 2 0 in the sixth position of the array named Numbers:
Numbers [5] <-20
VB.NET
Dim numbers(9) As String
numbers(5) = 20
Python
numbers = [0,0,0,0,0,0,0,0,0,01
numbers[5] = 20
Java
public static void main(String args[]){
Integer[] numbers = new Integer[10];
numbers[5] - 20;
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 1
Output the first value in the array Colours:
OUTPUT(Colours[0])
VB.NET
Console.WriteLine(Colours(0))
Python
colours = ['red']
print(colours[0])
Java
public static void main(String args[]){
String[] colours = new String[10];
System.out.printin(colours[0]);
}
Example 2
Store the second value in the array Colours in a variable:
TheColour <- Colours [1]
VB.NET
theColour = colours(1)
Python
colours = ['redyellow']
theColour = colours[1]
Java
public static void main(String args[]){
String[] colours = new String[10];
colours[0] = "red";
colours[1] = "yellow";
String theColour = colours[1];
272 y
8 Programming
Example 3
Add 10 to the third value in the array Numbers:
Value <- 10 + Numbers [2]
VB.NET
value 10 + numbers(2)
Python
numbers = [0,1,2,3,41
value = 10 + numbers[2]
Java
public static void main(String args[]){
Integer[] numbers = new Integer[5];
numbers[0] = 0;
numbers[1] = 1 ;
numbers[2] = 2;
numbers[3] = 3;
numbers[4] = 4;
Integer value = 10 + numbers[2];
}
Example
Ask the user which array element to output from the array colours:
OUTPUT("Enter the array element you want to output")
INPUT ToOutput
OUTPUT(Colours[ToOutput])
VB.NET
Dim colours(9) As String
colours(0) = "red"
colours(1) = "yellow"
colours(2) = "black"
colours(3) = "green"
Console.WriteLine("Enter the array element you want to output")
Console.WriteLine(colours(Console.ReadLine))
Python
colours = ['red','yellow','black','green']
print(colours[int(input("Enter the array element you want to output"))])
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
String[] colours = new String[10];
colours[0] = "red";
colours[1] = "yellow";
colours[2] = "black";
colours[3] = "green";
System.out.printin("Enter the array element you want to output");
Scanner scanner = new Scanner(System.in);
Integer choice = Integer.parselnt(scanner.nextLine());
System.out.printIn(colours[choice]);
}
Example 1
Output all 10 elements in the array Colours:
FOR Count <- 0 TO 9
OUTPUT(Colours[Count])
NEXT Count
VB.NET
Dim colours(9) As String
colours(0) = "red"
colours(1) = "yellow"
colours(2) = "black"
colours(3) = "green"
colours(4) = "blue"
colours(5) = "white"
colours(6) = "orange"
colours(7) = "purple"
colours(8) = "grey"
colours(9) = "maroon"
For count = 0 To 9
Console.WriteLine(colours(count))
Next
8 Programming
Python
colours = ['red', 'yellow', 'black', 'green', 'blue', 'white', 'orange', 'purple',
'grey', 'maroon']
for count in range(0, 10):
print(colours[count])
Java
public static void main(String args[]){
String[] colours = new String[10];
colours[0] = "red";
colours[1] = "yellow";
colours[2] = "black";
colours[3] = "green";
colours[4] = "blue";
colours[5] = "white";
colours[6] = "orange";
colours[7] = "purple";
colours[8] = "grey";
colours[9] = "maroon";
for(Integer count = 0; count < 10; count++){
System.out.printin(colours[count]);
}
}
Example 2
Ask the user to input 20 numbers and store each in the array Numbers:
FOR counter <- 0 TO 19
OUTPUT("Enter a number")
INPUT Numbers[Counter]
NEXT counter
VB.NET
Dim numbers(20) As Integer
For count = 0 To 19
Console.WriteLine("Enter a number")
numbers(count) = Console.ReadLine()
Next
Python
numbers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for count in range(0, 20):
numbers[count] = int(input("Enter a number"))
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
Integer[] numbers = new Integer[20];
Scanner scanner = new Scanner(System.in);
for(Integer count = 0; count < 20; count++){
System.out.printIn("Enter a number");
numbers[count] = Integer.parselnt(scanner.nextLine());
}
Example 3
Searching the values in the array values that has 50 values, for the data input by the user:
ValueToFind <- INPUT("Enter the value to find")
FOR Count <- 0 TO 49
IF Values[Counter] = ValueToFind THEN
OUTPUT("Found it")
ENDIF
NEXT Count
VB.NET
Dim values(49) As Integer
'insert code to populate array
Console.WriteLine("Enter the value to find")
Dim ValueToFind As Integer = Console.ReadLine
For count = 0 To 49
Console.WriteLine("Enter a number")
If values(count) = ValueToFind Then
Console.WriteLine("Found it")
End If
Next
Python
values^[]
# insert code to populate array
ValueToFind = int(input("Enter the value to find"))
for count in range(0z 50):
if values[counter] = ValueToFind:
print("Found it")
Java
public static void main(String args[]){
Integer[] values^ new Integer[50];
//insert code to populate array
276 y
8 Programming
A 2-dimensional arrax is best viewed as a table with rows and columns. 2-dimensional array:
an array that has two
Index 0 1 2 3 4 indices.
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
In a 2-dimensional array there are two indices. For example, from the table:
Position[0, 0] is 10.
Position[0,
Position[4,
Example 1
Store "red" in the first position in the array Colours:
Colour [0, 0] <- "red"
VB.NET
colours(0,0) = "red"
Python
numbers = [[''] * 5 for i in range(10)]
numbers[0][0] = "red"
Java
public static void main(String args[]){
String[][] colours = new String[10][10];
colours[0][0] = "red";
}
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 2
Store 10 in the array Data, in element 4 across and 3 down:
Data [4, 3] <-10
VB.NET
data(4,3) = 10
Python
numbers = [[0] * 5 for i in range(5)]
numbers[4][3] = 10
Java
public static void main(String args[]){
Integer[][] data = new Integer[10][10];
data[4][3] = 10;
}
Example 1
Output the data in the array ArrayData, element 5 across and 1 down:
OUTPUT(ArrayData[4, 1])
VB.NET
Console.WriteLine(arrayData(4,1))
Python
arrayData = [[0] * 5 for i in range(5)]
print(str(arrayData[4][1]))
Java
public static void main(String args[]){
Integer[][] arrayData = new Integer[5][5];
//insert data to populate array
System.out.printIn(arrayData[4][1]);
}
8 Programming
Example 2
Access the data in the array colours, in the first element across and the third down:
ColourAccessed <- Colours [0, 2]
VB.NET
colourAccessed = colours(0,2)
Python
colours = [[''] * 5 for i in range(5)]
colourAccessed = colours[0][2]
Java
public static void main(String args[]){
String[][] colours = new String[10][5];
String colourAccessed = colours[0][2];
}
Example 1
Output the data in element 4,3:
First <- 4
Second <- 3
OUTPUT(ArrayData[First, Second])
VB.NET
Dim arrayData(9, 9) As String
'insert code to populate array
Dim first As Integer = 4
Dim second As Integer = 3
Console.WriteLine(arrayData(first, second))
Python
arrayData = [[''] * 5 for i in range(5)]
first = 4
second = 3
print(arrayData[first][second])
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
String[][] arrayData = new String[10][10];
//insert code to populate array
Integer first = 4;
Integer second = 3;
System.out.printin(arrayData[first][second]);
}
Example 2
Ask the user which element to store in data:
OUTPUT("Enter dimension 1")
INPUT Indexl
OUTPUT("Enter dimension 2")
INPUT Index2
Data <- Array [ Indexl, Index2 ]
VB.NET
Dim arrayData(9, 9) As String
'insert code to populate array
Dim first As Integer
Console.WriteLine("Enter dimension 1")
first = Console.ReadLine
Dim second As Integer
Console.WriteLine("Enter dimension 2")
second = Console.ReadLine
Dim data As Integer
data = arrayData(indexl, index2)
Python
arrayData = [[''] * 10 for i in range(10)]
#insert code to populate array
Java
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String[][] arrayData = new String[10][10];
//insert code to populate array
Integer indexl = Integer.parselnt(scanner.nextLine());
Integer index2 = Integer.parselnt(scanner.nextLine());
String data = arrayData[indexl][index2];
}
8 Programming
Index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
The first loop will check row 2. The column will change from 0, 1, 2, 3, 4. The row will
stay the same at 1.
Index 0 1 2 3 4
0 10 5 90 26 87
1 3 15 74 62 5
2 7 10 85 4 24
Example 1
DataArray has 10 elements by 3 elements. Output all of the elements in the array:
FOR Row <- 0 TO 2
FOR Column <- 0 TO 9
OUTPUT(DataArray[Column, Row])
NEXT Row
NEXT Count
VB.NET
Dim dataArray(2, 9) As Integer
'insert code to populate array
For row = 0 To 2
For column = 0 To 9
Console.WriteLine(dataArray(row, column))
Next
Next
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
arrayData = [[''] * 2 for i in range(10)]
#insert code to populate array
Java
public static void main(String args[]){
Integer[][] dataArray = new Integer[3][10];
//insert code to populate array
for(Integer row = 0; row < 3; row++){
for(Integer column = 0; column < 10; column++){
System.out.printIn(dataArray[row][column]);
}
}
}
Example 2
Search a 2-dimensional array, with 50 elements by 100 elements, for the value input by
the user:
OUTPUT("Enter a number to search for")
INPUT Searchvalue
FOR Row <- 0 TO 49
FOR Column <- 0 TO 99
IF DataArray[Row, Column] = Searchvalue THEN
OUTPUT("Found it at " & Column & " " & Row)
ENDIF
NEXT Column
NEXT Row
VB.NET
Dim dataArray(50, 100) As Integer
'insert code to populate array
Dim searchvalue as Integer
Console.WriteLine("Enter a number to search for")
searchvalue = Console.ReadLine()
for (row = 0 to 50)
for(column = 0 to 100)
if(dataArray(row, column) =searchValue) then
Console.WriteLine("Found it at " & column & " " & row)
endif
next
next
282 )>
8 Programming
Python
arrayData = [[0] * 50 for i in range(100)]
#insert code to populate array
searchvalue = int(input("Enter a number to search for"))
for row in range(0, 50) :
for column in range(0, 100):
if arrayData[column][row] = searchvalue:
print("Found it at", str(column), " ", str(row))
Java
public static void main(String args[]){
Integer[][] dataArray = new Integer[50][100];
Scanner scanner = new Scanner(System.in);
Integer searchvalue = Integer.parselnt(scanner.nextLine());
for(Integer row = 0; row < 50; row++){
for(Integer column = 0; column < 100; column++){
if(dataArray[row][column] == searchvalue){
System.out.printIn("Found it at " + column + " " + row);
}
}
}
Example 3
Find and output the total of all elements in the each of the first dimensions, in an array
of 10 elements by 15 elements:
FOR Row <- 0 TO 9
Total <- 0
FOR Column <- 0 TO 14
Total <- Total + TheArray[Row, Column]
NEXT Column
OUTPUT("Index " & Row & " has the total " & Total)
NEXT Row
VB.NET
Dim theArray(9, 14) As Integer
'insert code to populate array
Dim total As Integer = 0
For row = 0 To 9
total = 0
For column = 0 To 14
total = total + theArray(row, column)
Next
Console.WriteLine("Index " & row & " has the total " & total)
Next
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Python
theArray = [[0] * 10 for i in range(15)]
#insert code to populate array
total = 0
for row in range(0, 10):
for column in range(0, 15):
total = total + theArray[row][column]
print("Index",row,"has the total", total)
Java
public static void main(String args[]){
Integer[][] theArray = new Integer[10][15];
//insert code to populate array
Integer total = 0;
for(Integer row = 0; row < 10; row++){
for(Integer column = 0; column < 15; column++){
total = total + theArray[row][column];
}
System.out.printIn("Index " + row + " has the total " + total);
}
}
8 Programming
CONTINUED
Getting started
1 Decompose the problem into its inputs, processes and outputs.
2 Work in pairs to discuss how you will alternate between the players.
3 Work in pairs to discuss how you will check if a player has won.
Practice
1 Write the program to ask each player to make one move. Check that
they have not selected the same box, if they have, ask them to select
another box.
2 Write an algorithm to check if a player has won and either output who has
won, or continue playing.
Challenge
1 Write a function for your algorithm to check if a player has won or not.
This should check all possible ways of winning and return either: X
(crosses has won), O (noughts has won) or C (continue play as no-one has
won). Your main program will need to decide whether to end, or continue
based on the value returned.
2 Edit your program to allow the user to play multiple games. The player
should alternate allowing noughts to go first, and then crosses to go first.
3 Edit your program to allow the user to select how many games they
should play. Keep track of how many games each player has won and
output who won overall.
Questions
38 Explain the difference between a variable and an array.
39 Explain why the following code will result in an error.
MyData [ 0 ] <- 1
MyData[1] <- 4
MyData [2] <- "7"
MyData [3] <- "9"
40 Write a program to read 10 numbers from the user into a 1-dimensional array
named MyNumbers.
41 Write a program to add together all 100 elements in a 1-dimensional array named
MyNumbers.
42 A 2-dimensional array, MyData, has 20 elements by 5 elements. Write a function
that takes a parameter search value. The function should search MyData and
return either TRUE if the parameters is in MyData, or FALSE if the parameters is
not in MyData.
285 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example 1
Reading and outputting a word stored in the text file data. txt:
OPEN "data.txt"
OUTPUT(READ("data.txt"))
CLOSE "data.txt"
VB.NET
Dim theFile As New System.IO.StreamReader("data.txt")
Console.WriteLine(theFile.ReadLine())
theFile.Close()
286 y
8 Programming
Python
theFile = open("data.txt", ' r')
print(theFile.read())
theFile.close()
Java
public static void main(String args[]){
try{
FileReader f = new FileReader("data.txt");
BufferedReader reader = new BufferedReader(f);
System.out.printin(reader.readLine());
reader.close();
}catch(Exception e){
System.err.printin("No file");
}
}
Example 2
Read and output the number stored in the file myNumber . txt by storing the filename
in a variable:
Filename <- "myNumber.txt"
OPEN Filename
TheFileData <- READ(Filename)
CLOSE(Filename)
OUTPUT(TheFileData)
VB.NET
Dim filename As String = "myNumber.txt"
Dim theFileData As String
Dim theFile As New System.10.StreamReader(filename)
theFileData = theFile.ReadLine()
theFile.Close()
Console.WriteLine(theFileData)
Python
filename = "myNumber.txt"
theFile = open(filename, 'r')
theFileData = theFile.read()
theFile.close()
print(theFileData)
287 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Java
public static void main(String args[]){
String filename = "myNumber.txt";
String theFileData;
try{
FileReader f = new FileReader(filename);
BufferedReader reader = new BufferedReader(f);
theFileData = reader.readLine();
reader.close();
}catch(Exception e){
System.err.printin("No file");
}
}
Writing to a file
The specification states that you will only need to write a single item of data or a line
of text. This means you will be overwriting any data that is already in the file, you do
not need to worry about appending (to add onto the end) to data that already exists,
or writing multiple values to the same file.
To write a value to a file you need to:
• Open the file using its filename (the filename will be a string value).
• Write the data to the file.
• Close the file.
You can use the pseudocode commands:
OPEN filename
WRITE data
CLOSE filename
Example 1
Write the word "red" to thefilecolour.txt:
OPEN "colour.txt"
WRITE "red"
CLOSE "colour.txt"
VB.NET
Dim fileWrite As New System.10.Streamwriter("colour.txt")
fileWrite.WriteLine("red")
fileWrite.Close()
Python
fileData = open("colour.txt",'w')
fileData.writelines("red")
fileData.close()
8 Programming
Java
public static void main(String args[]){
try{
FileWriter f = new FileWriter("colour.txt");
BufferedWriter out = new BufferedWriter(f);
out.write("red");
out.close();
}catch(Exception e){
System.err.printin("No file");
}
}
Example 2
Write the number 100 to the file myData. txt storing the filename in a variable:
Filename <- "myData.txt"
OPEN Filename
WRITE 100
CLOSE Filename
VB.NET
Dim filename As String = "myData.txt"
Dim fileWrite As New System.IO.Streamwriter(filename)
fileWrite.WriteLine(100)
fileWrite.Close()
Python
filename = "myData.txt"
fileData = open(filenamew')
fileData.writelines(100)
fileData.close()
Java
public static void main(String args[]){
try{
String filename = "myData.txt";
FileWriter f = new FileWriter(filename);
BufferedWriter out = new BufferedWriter(f);
out.write(100);
out.close();
}catch(Exception e){
System.err.printin("No file");
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
A maths quiz game needs to keep a record of the highest number of points
players has gained. The maths quiz is made of randomly generated questions;
the mathematical operation and the numbers are all randomly generated. The
user keeps on being given new questions until they get one wrong. The points
equate to the number of questions they got correct.
Getting started
1 In pairs discuss how the program can randomly generate the numbers
within reasonable bounds, e.g. between 1 and 20.
TIP
2 In pairs discuss how the program can randomly generate the symbol
limited to + - / * A. There are five options
so a number could
3 In pairs discuss how the highest score can be stored in a file. Discuss represent each
when the file will be read from, and when it will be written to. symbol.
Practice
1 Write the program to randomly generate one maths question (random
numbers and symbol). Output the question and ask the user for the
answer. Check if it is correct and output an appropriate response.
2 Amend your program to repeatedly ask the user questions until they get
one incorrect. Keep track of how many questions they get correct.
3 Amend your program so when the user gets a question incorrect, the
current high score is loaded from a text file. Replace the high score if the
user has more points.
Challenge
1 Text files can be read one line at a time. Find out how to store more than
one high score (e.g. a top-ten) in a file, and rearrange the high-score table
when a user gains a score worthy of including.
REFLECTION
Consider the program you made for Programming Task 8.5. How did you
decide which stage(s) to complete and when to stop? How did you find
example code that you needed? Was this an efficient method of finding the
required statements?
How did you test your program during development? Did you test the
program after each line of code, or did you write a section? Did this method
work for the program? Would you do it the same way in the future?
How did you test your program once it was complete? Did you set out a
structured test plan with different types of data? Did you ask other people to
help you test it? Was your chosen method appropriate for the program, or did
you have to change it during the testing process?
8 Programming
Questions
43 Why do some programs need to store data in files?
44 What are the three stages that need to be followed to write data to a file?
45 Write a program to read in a value from the file dataStore. txt and output it.
46 Write a program to ask the user to input a filename, then store the word "house"
in the file.
SUMMARY
A variable is a space in memory, with an identifier, that can store a data item that can change while
the program is running.
A constant is a space in memory, with an identifier, that can store a data item that cannot change
while the program is running.
Integer data type stores whole numbers. Real data type stores decimal numbers. Char data type stores
a single character. String data type stores a series of characters. Boolean data type stores True or False.
Input allows the user to enter data into a system.
Output allows the program to display data to the user.
There are three constructs in programming; sequence, selection and iteration.
There are two types of selection; IF and CASE.
IF statements can include ELSEIF and ELSE.
There are three types of iteration; count-controlled loops (a set number of iterations), pre-condition loops
(condition is tested before starting the loop) and post-condition loops (condition is tested after completing
the code in the loop).
Totalling requires initialising the total to 0, then adding the values to it.
Counting requires initialising the count to 0, then adding 1 to it.
Nested statements are when selection/iteration are within a selection/iteration construct.
Subroutines are self-contained code, with an identifier that can be called from elsewhere in the program.
Subroutines reduce repeated code.
Subroutines can be procedures (that do not return a value) or functions (that return a value).
A parameter is a value sent to a subroutine.
Library routines contain pre-written and pre-tested subroutines that can be used in a program.
A maintainable program includes meaningful identifiers, addition of comments and subroutines.
An array allows a set of data, of the same data type, to be stored under one identified.
Each element in an array has an index. This might start at 0 or 1 depending on your language.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
COMMAND WORD
state: express in
clear terms.
COMMAND WORDS
identify: name /
select I recognise.
give: produce an
answer from a given
source or recall I
memory.
292 y
8 Programming
CONTINUED
5 Tick one box in each row to identify whether each if statement would
result in True, False or is an invalid condition.
293 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated 'Needs more work’ or 'Getting there’.
294 y
> Chapter 9
FROM
FROM WHERE
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
GETTING STARTED
Your school will have a database of information about you. Find out some of
the information the school stores, this could be by talking to your teacher, or
other members of staff at the school.
Make sure you consider privacy of data. You can find out the type of
information collected, e.g. date of birth, but you cannot collect actual data
about specific people or items.
Work in pairs to identify why each item of data is stored by the school. Take it
in turns to share your reasons with the rest of the class.
9 Databases
CONTINUED
Data can also be stolen. This is an additional threat if the data is stored online, e.g. on a web server. This is
because external people can access the web server and access the data on it. This could include personal
information such as your bank details. This is why it is important that the web servers have security such as
firewalls to attempt to stop this unauthorised access. You can learn more about online security in Chapter 5
Discussion questions
1 Consider a social media website. What information will they store about their users?
What could happen if someone gains unauthorised access to this data?
2 How important is it that a company keeps their data secure? What are the potential
consequences of someone gaining unauthorised access to personal data?
A database is a collection of data that is set up in a structured way. This is usually database: an
on a computer, but you could have a paper-based database as long as it is suitably example of
structured. application software
to store and
A database holds data about objects, for example, a person, an item in a shop, an order
manipulate data.
someone has made, etc. Each of these objects is stored in a table.
Each table is then made up of fields, a field is an individual piece of data being stored table: a set of data
about an object. For a person you could have a field for first name, a field for email about one type of
address, for phone number, etc. object, e.g. students.
A collection of these fields about one object is called a record. For example, all the field: an individual
information about the person Aarna Singh will be one record. piece of data, e.g.
date of birth.
Most databases have many tables and these are all joined together so that the data is
linked. This is outside the scope of the specification. You only need to look at single record all of the
table databases. records in a table
about one object,
Here’s an example database about books in a library. The table is called books.
e.g. all the personal
details about one
Book name Author Publisher Genre Fiction student.
Picking daisies J. Frank Cambridge Gardening False
horticulture
Night stars K. Mars Si-fi books Science fiction True
Dreaming of P. Yu Si-fi books Science fiction True
the sun
Cooking for fun W. Crisp Cookery penguin Cookery False
This database has five fields; Book name, Author, Publisher, Genre and Fiction.
This database as four records: One for Picking daisies, one for Night starts, one for
Dreaming of the sun and one for Cooking for Fun.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
ACTIVITY 9.1
Consider your school. In pairs identify the fields that your school will store
about you. Write a list of the fields. Compare your pair's answers with another
pair. Were there any differences? Did you add any more to your list?
Each field has a specific data type. This identifies what that field can hold. These are data type: the
similar to the data types you learnt about in programming (Chapter 8). characteristics of
a piece of data.
Table 9.1 shows the common database data types:
Common data types
Data type Description Examples are string, integer,
real and Boolean.
Text Any combination of letters, symbols and/or "Hello"
numbers.
Alphanumeric "2JK8D"
The numbers are treated as text and not
numeric, i.e. you can't add them together. "2198"
298 >
9 Databases
Example:
A shop that sells wool needs to store the items it has in stock. Each item has;
a name, e.g. “Sparkle wool”, a colour, e.g. “red”, a weight, e.g. 2, a price,
e.g. $3.99 and a quantity in stock, e.g. 23.
To define a single-table database for the shop, you need to:
Questions
1 Complete the table by giving an example of each type of data.
302 >
9 Databases
Single field:
The command
SELECT BookName 4 SELECT is followed
FROM Books <----- by the field name.
This query will return:
The command FROM
Picking daisies is followed by the
Night stars name of the table.
Dreaming of the sun
Cooking tor fun
The case, spellings
IMPORTANT: The field names and table name must be exact. If the field name in the and order are all
table is ‘Genre’ then putting ‘genre’ in the query is incorrect. It is case sensitive. important in the
answer. Putting
Multiple fields:
commas after each
SELECT BookName, Genre 4----------------------------------------------------------- one is incorrect.
FROM Books Putting them one after
Notice how there are no commas or any other symbol between each field. another on a line is
incorrect. Each record
This will return is on a new line.
The order the fields appear in the query are important. The data will be returned
in the order they appear in the query.
Example:
SELECT BookName, Author
FROM Books
will return book name then author:
303 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
whereas:
SELECT Author, BookName
FROM Books
will return author then book name:
Questions
These questions use the following database table, PRODUCTS, about products for sale
in a shop.
304 y
9 Databases
9 Complete the SQL scripts to display the Name, Cost and Quantity in stock for all
items.
........................... , ........... . Quantity in stock
.............. PRODUCTS
This has only one condition. The condition needs a logical operator. These are the logical operator: a
same operators that you use in programming (Table 9.2). symbol that performs
a comparison
Operator Description Example WHERE resulting in True or
= Equal to. WHERE Fiction = True False. Can be equals,
not equal to, less
< Less than. WHERE Cost<3.99
than, less than or
<= Less than or equal to. WHERE Cost<=10 equal to, greater
> Greater than. WHERE Quantity >0 than, greater than or
>= Greater than and equal to. WHERE Quantity >=100 equal to.
<> Not equal to. WHERE Cost<>4.0
Table 9.2: Logical operators
Not equal to
SELECT Order ID, Posted
FROM Orders
WHERE Posted <> Yes
This query returns:
1A No
1D No
Less than
SELECT Order ID
FROM Orders
WHERE NumberIterns < 10
This query returns:
1B
1C
Less than or equal to
SELECT Numberltems, TotalCost
FROM Orders
WHERE TotalCost <= 6.00
This query returns:
2 3.99
1 6.00
Greater than
SELECT FirstName, LastName
FROM Orders
WHERE NumberIterns > 20
This query returns:
Jenny Silver
Greater than or equal to
SELECT Posted, FirstName
WHERE TotalCost >= 3.99
This query returns:
Qirat No
Simon Yes
Mei Yes
Jenny No
9 Databases
Questions
These questions use the following database table, MARKS, about students and their
marks in tests.
Student ID Subject Test name Percentage Grade
123 Science Physics 1 10 Fail
596 Computer Science Programming 2 53.3 Pass
123 Maths Trigonometry 6 10 Pass
023 Maths Trigonometry 6 50 Pass
802 Science Physics 1 25 Fail
806 Computer Science Programming 2 46.6 Pass
023 Maths Trigonometry 7 81 Merit
596 Science Physics 1 50 Pass
KEY WORD
1B 2 Yes
OR
SELECT FirstName, TotalCost, Posted
FROM Orders
WHERE TotalCost < 5 OR Posted = No
This query returns:
Qi rat 21.99 No
Simon 3.99 Yes
Jenny 59.65 No
9 Databases
Simon Tong
Mei Liu
If you log into a website then the code behind the scenes runs a query to
find out what your username and password are, and then compares what
you entered to these details. This is likely to use an SQL SELECT ... FROM ...
WHERE statement.
Questions
These questions use the following database table, WEATHER,
that store weather readings.
309 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
1 8 Complete the SQL script to display the time when the date is 12/12/2019 and the
humidity is more than 50.
SELECT
FROM
WHERE = 12/12/2019 Humidity > 50
19 Complete the SQL script to wind speed and temperature, when the wind speed is
either below 15 or above 20.
Wind speed,
FROM WEATHER
WHERE Wind speed 15 Wind speed 20
9 Databases
CONTINUED
Challenge
This task goes beyond the range of the specification.
Find out how to write SQL queries in the database software you have used.
Write the queries for practice and run them in your database.
9.5 Order by
This command allows you to state which order the result will be displayed in. There are
two options, ascending (ASC) and descending (DESC). The default is ascending.
The order by statement comes after the SELECT . . . FROM or SELECT . . . FROM . . . WHERE.
The following queries will use the following table, Orders:
Example 1:
SELECT OrderlD, Numberitems
FROM Orders
ORDER BY NumberIterns ASC
This query will return:
1C 1
1B 2
1A 20
1D 29
Example 2:
SELECT OrderlD, TotalCost, Posted
FROM Orders
WHERE Posted = Yes
ORDER BY TotalCost DESC
This query will return:
1C 6.00 Yes
1B 3.99 Yes
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Questions
These questions use the following database table, WEATHER,
that store weather readings.
SUM command will add up the field that is written after it. Il is written in the select
9.6 SUM
statement in the format:
SELECT SUM(field)
FROM table
9 Databases
Example 1:
SELECT SUM(NumberIterns)
FROM Orders
This query will return:
52
It is calculated from adding together all of the number of items (20 + 2+ 1 +29).
Example 2:
SELECT SUM(TotalCost)
FROM Orders
WHERE Posted = No
This query will return:
81.64
It is calculated from adding together all the total costs where posted is No (21.99 + 59.65).
9.7 COUNT
This will count how many records meet the criteria, or how many fields are in the table.
Count is in the format:
SELECT COUNT(field)
FROM table
The following queries will use the following table, Orders:
Example 1:
SELECT COUNT(OrderID)
FROM table
The query will return:
4
Example 2:
SELECT COUNT(Numberitems)
FROM table
WHERE Posted = Yes
The query will return:
2
Example 3:
SELECT COUNT(OrderID)
FROM Orders
WHERE NumberIterns > 10
The query will return:
2
SUM and COUNT are both mathematical operations that perform different functions.
SUM
This performs addition of a group of values.
Example 1, a set of data.
1+3+8+9+3=24
Example 2, a table of data.
10___
2___
9___
30
4
5
The SUM is 10 + 2 + 9 + 30 + 4 + 5 = 60
Example 3, an SQL query.
This query will use the following table, SALES.
9 Databases
CONTINUED
SELECT SUM(Total)
FROM SALES
The command word SUM tells you it needs you to add values together. The field in
the brackets, Total, tells you to add together the Total column.
20.00 + 16.25 + 8.99 + 3.00 + 11.50 = 59.74
When you are answering questions such as what does this script return when SUM is
being used, the only answer is the number. In Example 3, the answer to the question
would just be: 59.74
Example 4, table with criteria using the table SALES.
SELECT SUM(Total)
FROM SALES
WHERE Customer ID = "2"
This time there is a criteria. Only records with Customer ID being 2 are needed.
CONTINUED
10
2
9
30
4
5
There are 6 values
Example 3, an SQL query.
This query will use the following table, SALES.
CONTINUED
Questions
These will use the following table, PRODUCTS:
ACTIVITY 9.2
There are other mathematical functions that SQL can perform. Find at least
one other example of a mathematical function and how to write an SQL script
using it.
Take one of the example databases and write a script using your function.
Peer Assessment
Swap your new function and your script with a partner. Research the new
function your partner has used and check whether their script is accurate. If
not, discuss the error and how to solve it.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
REFLECTION
Questions
These questions use the following database table, ORDERS, that stores details about
orders ID a shop.FirstName
Orderfrom LastName Numberitems TotalCost
15 Keanu Kawai 5 20.59
16 Keanu Kawai 10 101.12
17 Eka Loke 3 30.50
18 Keanu Kawai 2 14.00
19 Ariana Wang 4 21.10
20 James Smith 6 44.60
21 James Smith 20 156.90
22 Ajay Gupta 1 10.00
SUMMARY
1 Define the terms record and field. Give an example of each. [2] define: give precise
2 Describe the following data types and give an example for each. meaning.
• Boolean describe: state the
• Real points of a topic /
• Date I time give characteristics
and main features.
• Text [4]
3 A cinema stores data about the films it is showing. It stores the screen
number (for example, l), the film (for example, The Dark), the date and
time of the showing, the number of seats sold (e.g. 150).
Define the single-table database for the cinema by identifying the fields,
data types, and primary key for the table. [7]
9 Databases
CONTINUED
322 y
9 Databases
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
represent a problem statement as a logic expression, logic circuit and a truth table
10 Boolean logic
GETTING STARTED
FUELLING A COMPUTER
As humans, we need food and water to fuel our body each day. Computers KEY WORDS
need their own fuel to operate and this is electricity. However, the electricity
that we supply a computer with has one set voltage. The electricity flow voltage: the pressure
through the different parts of the computer at this set voltage. This would be that forces the
okay if we only needed the computer to represent data as a single value, e.g. charged electrons to
1. Computers represent data in binary form, so this has two different values, flow in an electrical
0 and 1. Therefore, how do we make the electricity have two different states, circuit.
rather that the single state in which is enters the computer? Easy! It's done
logic gate: a very
through the use of logic gates.
small component in a
Most logic gates in a computer have two input values. These can be two Os, computer system that
two 1s or a 1 and a 0. Each logic gate has a single output, either a 1 or controls the flow of
a 0. The 1 is when the electricity is at a high voltage and the 0 is when the electricity.
electricity is changed to a low voltage. This means the electricity can flow into
a logic gate and will leave the logic gate in either a high or low state. The
computer now has two states and these are used to represent the necessary
binary values. One way of thinking about the role of a logic gate is to think of
it as a switch. It allows the voltage to be switched to a high or low state.
It seems quite absurd that the data stored by our computer is just a mixture
of high or low voltage electricity, but there is a feeling of wonder that such
complex processes in a computer are built upon this simple concept.
325 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
KEY WORD
truth table: a
Figure 10.2: A NOT logic gate
method to show
all the different
A truth table can be used to represent the logic of a logic gate. It shows all the outcomes of an
combinations that can be used as input values and what the output value will be for electrical circuit or
those input values. When doing this it is easier to give the input and output a character system, dependent
as a label, for example, the input can be labelled A and the output can be labelled X. on the inputs it
This is a completed truth table for a NOT logic gate: receives.
326 y
10 Boolean logic
A X
1 0
0 1 KEY WORD
A logic expression can be used to represent the logic of a logic gate. It shows the logic logic expression:
as a mathematical equation. The logic expression for a NOT gate is: a mathematical
representation that
X = NOTA
is used to represent
When you are doing further research and practice with Boolean logic, you may find an electrical circuit or
that there are other symbols and notations that can be used in logic expressions. system.
An alternative notation for a NOT gate is:
X=A
The line over the top of the character A represents it is NOT A. An interesting point
of knowledge to impress your friends with is that the line is called vinculum.
vinculum:联系、纽带。
Questions
1 Draw a NOT logic gate.
2 Complete the truth table for the NOT logic gate. A is the input and X is
the output:
A X
1
0
Output
This time input 1 is labelled A, input 2 is labelled B and the output is labelled X.
This is a completed truth table for an AND gate:
A B X
0 0 0
0 1 0
1 0 0
1 1 1
Questions
4 Draw an AND logic gate.
5 Complete the truth table for the AND logic gate:
A B X
0 0
0 1
1 0
1 1
ACTIVITY 10.1
Look at the truth table that you have completed for question 5. From the
results of the logic operations, do you think that an AND gate performs an
addition, subtraction, multiplication or division mathematical operation? Why?
Peer Assessment
Discuss your thoughts from the activity with a partner and see if you agree on
the mathematical operation that the AND gate performs. If you don't agree,
discuss each of your reasons for your choice and work out who is correct.
Did you both arrive at this answer in the same way? Discuss how you worked
out your answer.
10 Boolean logic
Input 1
Output
Input 2
Figure 10.4: An OR logic gate
A B X
0 0 0
0 1 1
1 0 1
1 1 1
Questions
7 Draw an OR logic gate.
8 Complete the truth table for the OR logic gate:
A B X
0 0
0 1
1 0
1 1
ACTIVITY 10.2
Look at the truth table that you have completed for question 8. From the
results of the logic operations, do you think that an OR gate performs an
addition, subtraction, multiplication or division mathematical operation? Why?
Peer Assessment
Discuss your thoughts from the activity with a partner and see if you agree on
the mathematical operation that the OR gate performs. If you don't agree,
discuss each of your reasons for your choice and work out who is correct.
Did you both arrive at this answer in the same way? Discuss how you worked
out your answer.
Output
A B X
0 0 1
0 1 1
1 0 1
1 1 0
The NAND logic gate is just a simplification of an AND gate followed by a NOT gate
(Figure 10.6):
4D
Figure 10.6: A NAND gate is a simplification of an AND gate and a NOT gate
330 y
10 Boolean logic
If you look at the truth table for the NAND gate, you should notice that the
outputs are the opposite of what they are in the AND truth table. This is because
the NOT gate takes the output of the AND table as its input, then reverses it to the
opposite value.
The logic expression for a NAND logic gate is:
X = A NAND B
An alternative notation for a NAND gate is:
X = A7B
The dot symbol (.) between the A and the B and then the line over both inputs and
the dot, represents the NAND in this expression.
You may remember that you studied how data is stored using solid-state
storage in the hardware chapter. In Chapter 3, you learnt that NAND
gate technology is one of the technologies used to create solid-state storage.
Questions
10 Draw a NAND logic gate.
11 Complete the truth table for the NAND logic gate:
A B X
0 0
0 1
1 0
1 1
input2 ZT^Output
A B X
0 0 1
0 1 0
1 0 0
1 1 0
The NOR logic gate is just a simplification of an OR gate followed by a NOT gate
(Figure 10.8):
If you look at the truth table for the NOR gate, you should notice that the outputs
are the opposite of what they are in the OR truth table. This is because the NOT gate
takes the output of the OR table as its input, then reverses it to the opposite value.
The logic expression for a NOR logic gate is:
X = A NOR B
An alternative notation for a NOR gate is:
X = A+B
The plus symbol (+) between the A and the B and then the line over both inputs and
the +, represents the NOR in this expression.
Questions
13 Draw a NOR logic gate.
14 Complete the truth table for the NOR logic gate:
A B X
0 0
0 1
1 0
1 1
Questions
16 Draw an XOR logic gate.
17 Complete the truth table for the XOR logic gate:
A B X
0 0
0 1
1 0
1 1
A logic circuit is a combination of several logic gates that are linked. Figure 10.10 shows
a simple logic circuit:
There are three different inputs to this logic circuit: A, B and C. There is one output
from this logic circuit that is labelled Y. There are three different logic gates in this logic
circuit: NOT, OR and AND.
You need to be able to complete a truth table for a logic circuit, so let’s learn how to do that.
First you need a truth table to complete. As this logic circuit has three inputs, so there
can be eight different combinations to consider:
A B c Y
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
If you look at the values in the truth table, what do you notice about the order of
each combination? If you think about each row as a 3-bit binary value, you should
notice that they increment from 0 to 7 in denary. For example, 000 = 0, 001 = 1,
010 = 2, 011=3, etc.
In the logic circuit, as the output from the OR gate and the NOT gate become the inputs
for the AND gate, it helps to give these a label so that it is easier to track values for
them. In this example, Figure 10.11, the labels D and E are used.
CONTINUED
You can add these labels into the truth table to work out what these interim values are:
A B c D E Y
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
You can now begin to fill in the values in the truth table. You need to complete the
output for the OR gate in the column labelled D. You have learnt that the logic of an
OR gate is that if either or both inputs are l, the output is l. You are just looking at
the values in columns A and B for this, as these are the inputs to the OR gate. You can
ignore what is in column C for now. This is the truth table with column D completed:
A B c D E Y
0 0 0 0
0 0 1 0
0 1 0 1
0 1 1 1
1 0 0 1
1 0 1 1
1 1 0 1
1 1 1 1
You need to complete the output for the NOT gate in the column labelled E.
You have learnt that the logic of a NOT gate is that it reverses the input value to be
the opposite value. You are just looking at the values in column C for this, as this is
the input to the NOT gate. You can ignore what is in the other columns for now.
This is the truth table with column E completed:
A B c D E Y
0 0 0 0 1
0 0 1 0 0
0 1 0 1 1
0 1 1 1 0
1 0 0 1 1
1 0 1 1 0
1 1 0 1 1
1 1 1 1 0
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
You can now complete the final output column that is the output for the logic circuit,
this is column Y. You have learnt that the logic of an AND gate is that the only time
the output is 1 is when both inputs are 1. You are just looking at columns D and E
for this, as they are the inputs to the AND gate. This is the truth table with the final
output column completed:
A B c D E Y
0 0 0 0 1 0
0 0 1 0 0 0
0 1 0 1 1 1
0 1 1 1 0 0
1 0 0 1 1 1
1 0 1 1 0 0
1 1 0 1 1 1
1 1 1 1 0 0
You now know how to complete a truth table for a logic circuit, excellent!
Questions
1 Complete the truth table for the given logic circuit in Figure 10.12:
Figure 10.12: Complete the truth table for this logic circuit
A B c Workspace Q
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
10 Boolean logic
CONTINUED
2 Complete the truth table for the given logic circuit in Figure 10.13:
Figure 10.13: Complete the truth table for this logic circuit
p Q R Workspace Z
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
The first part to the logic circuit is the OR gate. The logic expression for this part is
A OR B. The second part of this logic circuit is NOT and the third part of this logic
circuit in the AND gate.
So, the three parts to this logic circuit are:
AOR B
NOTC
AND
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
You can now start to join these different parts together to create the complete logic
expression. You should always start with the label for the final output followed by an
equals symbol (=):
Y=
One of the simplest ways to complete the expression is to then add the final gate in the
logic circuit as everything else is built around this:
Y = AND
Then add the part that creates the first input to this gate. You should put this into
brackets to show that it is a different part of the logic expression:
Y = (AOR B) AND
Then add the part that creates the second input to this gate to create the complete logic
expression:
Y = (A OR B) AND (NOT C)
Let’s look at a larger logic circuit (Figure 10.15) as a second example:
First, break down the logic circuit into its different parts:
PNANDQ
NOTQ
XOR
AND R
Then join together these different parts to create the logic expression.
Remember, a simple way to do this is to start with the final logic gate and work from
right to left.
Z = ANDR
Z = (XOR) AND R
Z =((P NAND Q) XOR) AND R
Z =((P NAND Q) XOR (NOT Q)) AND R
You now know how to write a logic expression for a logic circuit, that’s awesome!
338 y
10 Boolean logic
Questions
19 Write the logic expression for the given logic circuit:
know any single logic gates that would produce this truth table. It doesn’t match any
of the truth tables that you have learnt previously in this chapter for each of the logic
gates, therefore you now know it must be a combination of at least two logic gates.
When you are creating a logic expression and a logic circuit from a truth table, you only
need to know how to do this using three of the logic gates that you have learnt: the
NOT gate, the AND gate and the OR gate.
Once you have looked at the truth table to see if it represents a single logic gate that
you know, if you find it doesn’t, you can move onto the next step which is finding out
which gates will create that truth table.
339 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
A B X
0 0 0
ELZ 1 T|
1 0 0
1 1 0
It has one output value that is a 1, so this is what you need to concentrate on. You
need to use an AND gate to create this output. At present an input value of A =0 and
B = 1 will not result in an output of 1 using an AND gate. You should remember that
for the output to be 1 for an AND gate, both inputs need to be 1. Therefore, you need
to reverse input A, which is 0, to make it 1. You should remember that to reverse the
input value to create the opposite value as an output, you should use a NOT gate. That
makes the logic expression for this truth table:
X = (NOT A AND B)
You can then draw a logic circuit for this (Figure 10.18):
B--------------------------- 1
Figure 10.18: The logic circuit for logic expression X = (NOT A AND B)
A B X
0 0 0
|0 1 3
1 0 0
11 1 3
This time the truth table has two output values that are l, so you need to focus on both
of those. You have the same situation again with the first output of 1, so you already
know that this part is NOT A AND B.
A B X
0 0 0
0 1 1 NOT AAND B
1 0 0
HZ 1 3
You now need to look at the second output value of 1. You need to think whether an
input of 1 for A and an input of 1 for B will create an output of 1 if an AND gate is
used. You should recognise that it will. This means that this part is A AND B.
10 Boolean logic
A B X
0 0 0
0 1 1 NOT A AND B
1 0 0
1 1 1 A AND B
Now that you have worked out what the part of the logic expression is for each output
value of l, you need to join these together using an OR gate. That makes the logic
expression for this truth table:
X =(NOT A AND B) OR (A AND B)
You can then draw a logic circuit for this (Figure 10.19):
Figure 10.19: The logic circuit for logic expression X = (NOT A AND B) OR (A AND B)
Let’s now look at a truth table that has three input values A, B and C:
A B c X
0 0 0 0
0 0 1 1
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
This makes the process more complex and there are several methods that you can
use to work out the logic expression. Each method may generate a slightly different
logic expression, but they all should produce the same truth table. It is the structure
of them that will change slightly, but the logic of them will ultimately produce the
same result.
The first method you can use is a method called sum of products. In this method
you need to create a sum of products expression for each row in the table that has an
output value of 1. In a sum of products statement, you need to look at each input
value. If it is 1, then in the expression it will be, for example, A. If it is 0, then in the
expression it will be, for example, NOT A. Each input is then summed, this is done
using the AND gate.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
A B c X
0 0 0 0
10 0 1 T|
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 1
In this row:
• A is 0 so that’s NOT A.
• B is 0 so that’s NOT B.
• C is 1 so that’s C.
These are then joined using AND gates making:
NOT A AND NOT B AND C
You need to follow this process for each row in the truth table that has an output of 1.
You should see this result when you do:
A B c X
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 1
1 1 1 1
Again, you look at the rows that have an output of l. If you look at the first row with
an output of 1, the input values are A =0, B =0, C =1. You need to look to see if any
of these values are constant. This means, are there any values that are the same between
the inputs. You should notice that the input values for A and B are the same, 0 and 0.
You now need to look whether inputs of 0 and 0 for A and B always result in an output
of 1 in each row in the table. If they do, this means that the expression for this row is:
NOTA AND NOT B
If they don’t always result in an output of 1, then you use the sum of products
expression for the row instead. If you look at row 1 in the table, you should notice that
A and B both have an input of 0, but that the output is 0 and not 1. Therefore, you
need to use the sum of products expression for row 2 instead, which is:
NOT A AND NOT B AND C
This is because we need to apply the rule you learnt earlier about reversing the inputs
to make sure that the values will give an output of 1 for an AND gate.
If you look at the next row that has an output of 1, you should see that the inputs are
A = 0, B = 1, C = 1. This time it is B and C that have the constant value as they are
both the same. You now need to look at whether all rows in the table where B and C
have the value 1, the result is an output of 1. You should be able to notice that the only
other place in the table where the inputs are both 1 is row 8, the final row. This does
result in an output of 1 as well, so this means that the expression for this row is:
A ANDC
If you look at the final two rows in the table, they both that have an output of 1.
If you have two outputs of 1 together like this, you can treat them as a pair. You
apply the same method to see if there are any values that are constant. In row 7 the
values are A = 1, B = 1 and C =0, and in row 8 the values are A - 1, B = 1 and C = 1.
You should notice that the A and B inputs are constant in both of these rows. You now
look to see if there are any other instances of A and B both having an input of one in
the table to see if this results in an output of 1 also. There are no other instances, so
this means the expression for these two rows is:
A AND B
These three expressions are then joined together again with an OR gate, giving a final
expression of:
X = (NOT A AND NOT B AND C) OR (A AND C) OR (A AND B)
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
If you work out the statement using the sum of products method, you will get:
X = (NOT A AND NOT B AND C) OR (NOT A AND B AND C) OR
(A AND B AND NOT C) OR (A AND B AND C)
The two statements represent the same truth table, but you can see that the second
method creates a shorter statement, which can be helpful if there are lots of outputs of
1 to be considered.
Question
21 Look at the given truth table:
A B X
0 0 1
0 1 1
1 0 0
1 1 0
Figure 10.21: The logic circuit for the expression Z = (R AND S) OR (something)
344 )>
10 Boolean logic
Figure 10.22: The logic circuit for the expression Z = (R AND S) OR (R AND T)
You now have a logic circuit that represents the logic expression!
You can now use what you have previously learnt to represent that as a truth table:
R s T z
0 0 0 0
0 0 1 0
0 1 0 0
0 1 1 0
1 0 0 0
1 0 1 1
1 1 0 1
1 1 1 1
345 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Figure 10.24: The logic circuit for the expression X = ((A AND B) OR NOT C) XOR (something)
You now need to look at the final bracketed section as this will create the second
input for the XOR gate. This is B NOR C, so you can now complete the logic circuit
(Figure 10.25):
Figure 10.25: The logic circuit for the expression X = ((A AND B) OR NOT C) XOR (B NOR C)
Questions
22 Complete the truth table for the logic statement:
X = ((A AND B) OR NOT C) XOR (B NOR C)
A B c X
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
23 Draw a logic circuit to represent the logic expression:
Z =(A OR B) NAND ((C AND B) OR NOT A))
10 Boolean logic
The system will sound an alarm (X) when certain conditions are detected. The alarm
will sound when:
the pressure >= 75% and the temperature >= 50 °C
or
the temperature < 50 °C and the pH > 7
You can begin to break down this problem and write a logic expression for it. You
can take the alarm conditions line by line and break them down to create each part of
the expression.
Let’s look at the first line of the alarm condition:
The pressure >= 75% and the temperature >= 50 °C
You should notice this involves the inputs P and T. You need to work out what the
binary value for the input is for each of these conditions. You can do this by looking at
the table you are given. You should work out that P = 1 and T =0.
This line of the problem statement states that if both of those conditions happen,
the alarm will sound. This means that the expression would use an AND gate and
that both inputs must be 1 going into that AND gate in order to create an output of
1 to sound the alarm. As T =0, this value will need to be reversed and you should
remember that you can use a NOT gate to do this. This means that the expression for
this part of the problem statement is:
PAND NOTT
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
The second line of the alarm condition is simply an OR. You should learn from this
that the two sets of conditions will be separated using and OR gate. This means that
expression now becomes:
(P AND NOTT) OR
The third line of the alarm conditions is:
The temperature < 50 °C and the pH > 7
You should notice this involves the inputs T and A. You again need to look at the
table to work out the binary value for the input for each condition. You should work
out that T = 1 and A =0. It states that both of the conditions needs to be met for the
alarm to sound, so the expression for this part of the problem is:
TAND NOTA
You can now add this to the other part and create the full logic expression for the
problem statement, which is:
X =(P AND NOT T) OR (T AND NOT A)
Using what you have previously learnt, you can create the logic circuit and the truth
table from this to represent the problem statement (Figure 10.26):
P--------------
Figure 10.26: The logic circuit for the soap factory problem statement
A T p X
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 1
1 1 0 0
1 1 1 0
10 Boolean logic
As you can see from studying problem statements, many systems use more
than one sensor to monitor processes such as manufacturing. The data from
each of these sensors provides an input into a logic circuit to determine what
the output will be. Some manufacturing business use as many as ten different
sensors in a logic circuit to monitor their manufacturing processes. That would
be one huge logic circuit!
A B X
0 0 0
0 1 0
1 0 0
1 1 1
[1]
A B X
0 0 1
0 1 0
1 0 0
1 1 0
[1]
[Total: 2]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
A B X
0 0 1
0 1 0
1 0 1
1 1 1
s T p z
0 0 0 0
0 0 1 1
0 1 0 1
0 1 1 0
1 0 0 1
1 0 1 1
1 1 0 0
1 1 1 0
350 )>
10 Boolean logic
CONTINUED
b Complete the truth table to represent the given logic circuit:
L M N Workspace Y
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
[4]
[Total: 7]
6 A greenhouse has a system that monitors the growing conditions for
fruits and vegetables. The system has three conditions to monitor the
moisture level of the soil (M) the temperature (T) and the humidity (H).
The conditions for the system are:
The system will sound an alarm (X) when certain conditions are detected.
The alarm will sound when:
The moisture level <= 80% and the humidity < 65%
or
The temperature > 35 °C and the humidity is >= 65%
a Write a logic expression to represent the problem statement for the
alarm system for the greenhouse. [3]
b Draw a logic circuit to represent the problem statement for the
alarm system for the greenhouse. [5]
c Complete the truth table to represent the problem statement for the
alarm system for the greenhouse.
M T H Workspace X
0 0 0
0 0 1
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
CONTINUED
M T H Workspace X
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
[4]
[Total: 12]
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work’ or ‘Getting there’.
I can...
See Needs Getting Confident
topic more work there to move on
draw logic gates using the standard symbols. 10.1-10.7
describe the logic of each different logic gate. 10.1-10.7
complete a truth table for each logic gate. 10.1-10.7
identify the single logic gate the represents a given
10.1-10.7
truth table.
complete a truth table to represent a logic circuit. 10.1-10.7
write a logic expression to represent a logic circuit. 10.8
write a logic expression to represent a truth table. 10.9
draw a logic circuit to represent a truth table. 10.9
draw a logic circuit to represent a logic expression. 10.10
complete a truth table to represent a logic expression. 10.10
write a logic expression to represent a problem
10.11
statement.
draw a logic circuit to represent a problem statement. 10.11
complete a truth table to represent a problem
10.11
statement.
352 >
> Chapter 11
Programming
scenarios
n*
GETTING STARTED
PLANNING A PROGRAM
ACTIVITY 11.1
Write down some of the inputs, processes and outputs for your favourite
computer game.
Peer Assessment
Compare your game with a partner's. Can you think of any more inputs,
processes or outputs for their game?
Example - calculator:
A program needs writing to act as a calculator. The program needs to:
• Take one integer value from the user.
• Take an operator as input; + for addition, - for subtraction, / for
division, * for multiplication or A for power of.
• Take a second integer value from the user.
• Output the result.
Write a program using pseudocode or program code to solve the problem.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Once you have read it twice, start to identify the key features; the inputs, processes and
outputs. You could do this using a table, e.g.
Then you need to work out how to get from the input to the output. This could be a
description, program statements, or anything that helps you to write down what happens.
If you get stuck here, try doing what the program needs. In the case of the calculator,
write down the first integer value (e.g. 3), write down the operator (e.g. +), write
down the second integer value (1). Then what do you do with this values? Because the
operator is + you will do 3 + 1. That is your process.
Inputs
It is always best to include an output before the input, to tell the user what to enter.
This can be done in two statements, e.g.
OUTPUT "Enter a number"
INPUT number
or as one statement, e.g.
number <- INPUT "Enter a number"
Whichever way you choose, make sure you are inputting a value into a variable.
In the examples above the variable is number. If you use this statement:
INPUT "Enter a number"
then the number will be input and it won’t be stored anywhere, so you can’t use it.
Example - calculator:
Write code for the inputs.
Number 1 <- INPUT "Enter a number"
Operator «- INPUT "Enter an operator"
Number2 <- INPUT "Enter a number"
Validation
Now you have your inputs, consider if there are limits on what should be entered.
Look at each input in turn and write down what is, and isn’t allowed.
357 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Example - calculator:
• First integer value - must be a whole number.
• Operator must be + - / * or A.
• Second integer operator must be a whole number.
There are different ways that you could validate the inputs, e.g.
• Use an if statement and only allow the rest of the program to run if the
inputs it valid.
• Use a loop to continue asking for the input until it is valid.
Example - calculator:
REPEAT
Number 1 *- INPUT "Enter a number"
UNTIL Numberl.islnteger()
REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = " + " OR Operator = OR Operator = "★" OR Operator = "/"
OR Operator = " A "
REPEAT
Number2 <- INPUT "Enter a number"
UNTIL Number2.islnteger()
NB the statement . islnteger is not language specific, but as a pseudocode statement
it shows that you are looking to check if the value is an integer and only allow the input
if it is. You might have one for the language you choose, but it is better to use this than
a statement such as: until the number is an integer.
Processes
Revisit your design table and take the processes one at a time and work out whether
they need sequence, selection and/or iteration.
Example calculator:
Process Construct
1 If + is entered add the values. selection
2 If - is entered subtract the values. selection
3 If * is entered multiply the values. selection
4 If / is entered divide the values. selection
5 If A is entered work out the power of. selection
358 y
11 Programming scenarios practice
__ ii _ ti
ELSEIF Operator
THEN
Result <- Numberl - Number2
ELSEIF Operator — *Hii
THEN
Result <- Numberl ★ Number2
__ ii / ii
ELSEIF Operator
THEN
Result *- Numberl / Number2
ELSE
Result «- Numberl Number2
END IF
Outputs
Once you have written your processes, work out where your outputs should be. Make
sure you output using an appropriate message, for example, what the value is showing.
Example - calculator:
First integer value. If + is entered add the values. Result from the calculation.
ELSEIF Operator =
THEN
Result <- Numberl
ELSEIF Operator _ it * ii
Number2 -
THEN
Result <- Numberl ★ Number2
ELSEIF Operator __ /n ii
THEN
Result <- Numberl / Number2
ELSE
Result <- Numberl z\ Number2
ENDIF
OUTPUT "The result is: II / Result
Adding comments
You should always add comments to your code to explain what you have done.
Comments are statements in your program that will not be run. A comment will
always start with a specific symbol to state that this is where the comment starts, for
example, */, # or //.
Comments are used to explain sections of code, not every single statement.
Example calculator:
// input 2 numbers and operator
REPEAT
Number 1 <- INPUT "Enter a number"
UNTIL Numberl.Islnteger()
REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = " + " OR Operator = OR Operator = OR Operator = "/"
OR Operator = "A"
REPEAT
Numberl <- INPUT "Enter a number"
UNTIL Numberl.Islnteger()
//check operator and perform calculation
IF Operator = "+"
THEN
Result <- Numberl + Number2
ELSEIF Operator _ _ n ii
THEN
Result <- Numberl - Number2
ELSEIF Operator — n * H
THEN
Result <- Numberl ★ Number2
ELSEIF Operator __ / ii ii
THEN
Result <- Numberl / Number2
ELSE
Result <- Numberl Number2
11 Programming scenarios practice
ENDIF
//output the result
OUTPUT "The result is: ", Result
Final checks
Once you have finished your algorithm perform the following checks:
1 Have you stored all of your inputs in variables?
2 Have you validated inputs where possible?
3 Have you performed all of the processes?
4 Have you outputted the required values?
5 Have you included appropriate messages in your outputs?
6 Have you added comments?
7 Do all your variables have appropriate identifiers?
8 Return to the scenario and tick every statement that your program performs.
If you don’t tick a statement then you need to add that to your program.
ACTIVITY 11.3
Read the calculator pseudocode solution above and complete the final checks
on the algorithm. Tick each on in turn to make sure it has been covered in the
solution.
TACKLING A PROBLEM
When you are given a problem to write a computer program for, you need to know
how to approach it to create a solution. In this Skills Focus you will be walked
through the production of a solution by analysing the problem, identifying the
components and writing a solution that covers all of the requirements. You can then
apply the same methodology to other problems to write a computer program to
solve the problem.
A computer game asks the user to enter a 5-letter word and then stores each letter in
a different index in the array, for example:
‘house’ is input:
Index 0 1 2 3 4
Letter h o u s e
A second user then has 10 guesses to try and work out what the word is. They have
to enter one letter at a time, and the program either outputs the position that letter
is in (e.g. ‘h’ is in 0), or that the letter is not in the word.
After guessing a letter the user gets a free guess at the word. If they get it correct
they win and the program ends. If the player has entered 10 letters and not guessed
correctly then they lose.
Write a program using pseudocode or program code for the computer game.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Validation
The word that is input needs to be 5 characters long so that can be validated. The
character entered can be validated as to whether it is a character; there is no specific
way to do this but you could use a function such as IsCharacter (). Validating
the word is not as straightforward because most things could be accepted.
REPEAT
WordToGuess <- INPUT "Enter a 5 character word"
UNTIL LENGTH(WordToGuess) = 5
REPEAT
UserLetter «- INPUT "Enter a letter to guess"
UNTIL UserLetter.IsCharacter() = TRUE
Processes
Take these one at a time.
First: Store each letter in a different index in an array. To split the string you can use
either a function in your language, or a pseudocode function such as substring.
//INPUT word to guess
REPEAT
WordToGuess <- INPUT "Enter a 5 character word
362 >
11 Programming scenarios practice
CONTINUED
UNTIL LENGTH(WordToGuess) = 5
//store characters in array
LetterArray <- SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 1),
SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess, 3, 1)]
CONTINUED A
//check for position of user's guess
FOR Count <- 0 TO 5
IF UserLetter = LetterArray[Count]
THEN
OUTPUT "Position ", Count
ENDIF
NEXT Count
//check user's guess
UserWord «- INPUT "Enter a word to guess"
IF UserWord = WordToGuess
THEN
OUTPUT "You win"
ENDIF
Fourth: Count number of times the user has guessed and repeat and stop when
10 letters or word is correct.
These two are being combined because they are dependent on each other.
Split the processes down to:
• Repeatedly allow the user to guess the letters and word (repetition means using
a loop).
• Keep a count of how many guesses they have (counting requires a variable,
and incrementing this value).
• Stop when they get it correct or have had 10 guesses (the conditions for
stopping the loop).
LetterArray *- [SUBSTRING(WordToGuess, 0, 1),
SUBSTRING(WordToGuess, 1, 1),
SUBSTRING(WordToGuess, 2 , 1),
SUBSTRING(WordToGuess, 3 , 1)]
Count = 0
IF UserWord = WordToGuess
THEN
OUTPUT "You win"
Count <- 11
ENDIF
Count «- Count + 1
ENDWHILE
Fifth: Perform the final checks:
1 Have you stored all of your inputs in variables?
2 Have you validated inputs where possible?
3 Have you performed all of the processes?
4 Have you outputted the required values?
5 Have you included appropriate messages in your outputs?
6 Have you added comments?
7 Return to the scenario and tick every statement that your program performs.
If you don’t tick a statement then you need to add that to your program.
Questions
1 Which elements of a program do you first need to identify?
2 What is a process in a program?
3 What do you need to include in your final checks?
Example calculator:
A program needs writing to act as a calculator. The program needs to:
• Take one integer value from the user.
• Take an operator as input; + for addition, - for subtraction, / for
division, * for multiplication or A for power of.
• Take a second integer value from the user.
• Output the result.
Write a program using pseudocode or program code to solve the problem.
365 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Adding extras
It is best practice to add the following to your algorithms:
• Messages to tell people what to input.
• Validation of inputs.
• Messages to say what is being output.
• Comments to explain the code.
1 Messages to tell people what to input:
Number1 *- INPUT "Enter the first number"
Operator «- INPUT "Enter an operator2
Number2 «- INPUT "Enter the second number"
11 Programming scenarios practice
IF Operator = "+"
THEN
OUTPUT Number1 + Number2
ELSEIF Operator = "-"
THEN
OUTPUT Numberl - Number2
ELSEIF Operator = "*"
THEN
OUTPUT Numberl * Number2
ELSEIF Operator = "/"
THEN
OUTPUT Numberl / Number2
ELSE
OUTPUT Numberl A Number2
ENDIF
2 Validate inputs:
REPEAT
Numberl <- INPUT "Enter the first number"
UNTIL Numberl.Islnteger = TRUE
REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = "+" OR Operator = OR Operator = "*" OR Operator = "/"
OR Operator = "A"
REPEAT
Number2 <- INPUT "Enter the second number"
UNTIL Number2.Islnteger = TRUE
REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = "+" OR Operator = OR Operator = OR Operator = "/"
OR Operator = "A"
REPEAT
Number2 <- INPUT "Enter the second number"
UNTIL Number2.IsInteger = TRUE
IF Operator = "+"
THEN
OUTPUT "The addition = "
OUTPUT Numberl + Number2
ELSEIF Operator =
THEN
OUTPUT "The subtraction = "
OUTPUT Numberl - Number2
ELSEIF Operator = " *"
THEN
OUTPUT "The multiplication = "
OUTPUT Numberl * Number2
ELSEIF Operator = "/"
THEN
OUTPUT "The division = "
OUTPUT Numberl / Number2
ELSE
OUTPUT "The power of = "
OUTPUT Numberl A Number2
ENDIF
REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = " + " OR Operator = OR Operator = "*" OR Operator = "/"
OR Operator = "z'"
REPEAT
Number2 <- INPUT "Enter the second number"
UNTIL Number2.Islnteger = TRUE
IF Operator = "+"
THEN
OUTPUT "The addition = "
OUTPUT Number1 + Number2
ELSEIF Operator = "-"
THEN
OUTPUT "The subtraction = "
OUTPUT Number1 - Number2
ELSEIF Operator = "*"
THEN
OUTPUT "The multiplication =
OUTPUT Numberl * Number2
ELSEIF Operator = "/"
THEN
OUTPUT "The division = "
OUTPUT Numberl / Number2
ELSE
OUTPUT "The power of = "
OUTPUT Numberl A Number2
ENDIF
TACKLING A PROBLEM
In this problem an array is needed to store data within the problem. This Skills Focus
will take you through the production of a solution to a problem that makes use of an
array. You can then use this same methodology when solving your own problems.
A 2D array stores the cost of items and the quantity sold of 100 items. For example,
part of the array could store the data in the table.
Cost 10.00 15.99 20.22 13.78 8.99 6.20 4.30 10.00 12.00
Quantity 5 6 8 10 2 15 3 16 10
CONTINUED
Important note: this program uses an array. To check, count, or calculate using each
item in an array you will need to use a loop. A count-controlled loop, e.g. for loop, is
most appropriate.
Take each step and turn it into pseudocode.
Step 1 - output and input of choice.
OUTPUT "Enter 1 for total number of items sold, 2 for total cost of all items
sold, 3 for number of items less than $10, 4 for number of items $10 or more".
INPUT Choice
Step 2 - totalling number of items sold.
IF Choice = 1
THEN
Total <- 0
FOR Count <- 0 TO 100
Total <- Total + Array [Count, 1]
NEXT Count
OUTPUT "Total number of items sold is " , Total
ENDIF
370 y
11 Programming scenarios practice
CONTINUED
CONTINUED
IF Choice = 1
THEN
Total <- 0
FOR Count <- 0 TO 100
Total <- Total + Array [Count, 1]
NEXT Count
OUTPUT "Total number of items sold is " , Total
ELSEIF Choice = 2
THEN
Total <- 0
FOR Count <- 0 TO 100
Total <- Total + (Array[Count, 0] * Array[Count, 1])
NEXT Count
OUTPUT "Total cost of items sold is ", Total
ELSEIF Choice = 3
THEN
Number I terns <- 0
FOR Count <- 0 TO 100
IF Array[Count, 1] <10
THEN
Number I terns <- Number I terns + 1
ENDIF
NEXT Count
OUTPUT "Number of items that sold less than 10 ", Numberitems
ELSEIF Choice = 4
THEN
Number I terns <- 0
FOR Count <- 0 to 100
IF Array[Count, 1] >=10
THEN
Number I terns <- Number I terns + 1
ENDIF
NEXT Count
OUTPUT "Number of items that sold 10 or more ", Numberitems
ENDIF
Final checks
• Messages to tell people what to input. (/)
• Validation of inputs - needs to be done.
• Messages to say what is being output. (/)
• Comments to explain the code.
11 Programming scenarios practice
CONTINUED
A
//Take user choice from menu
REPEAT
OUTPUT "Enter 1 for total number of items sold, 2 for total cost of all
items sold, 3 for number of items less than $10, 4 for number of items
$10 or more."
INPUT Choice
UNTIL Choice = 1 or Choice = 2 or Choice = 3 or Choice = 4
IF Choice = 1
THEN //if choice is 1 total number of items sold
Total <- 0
FOR Count <- 0 TO 100
Total <- Total + Array [Count, 1]
NEXT Count
OUTPUT "Total number of items sold is " , Total
ELSEIF Choice = 2
THEN //if choice is 2 total cost of all items sold
Total <- 0
FOR Count <- 0 TO 100
Total <- Total + (Array[Count, 0] * Array[Count, 1])
NEXT Count
OUTPUT "Total cost of items sold is ", Total
ELSEIF Choice = 3
THEN //if choice is 3 count items less than 10
Number I terns <- 0
FOR Count <- 0 TO 100
IF Array[Count, 1] <10
THEN
Number I terns <- Number I terns + 1
ENDIF
NEXT Count
OUTPUT "Number of items that sold less than 10 ", Numberitems
ELSEIF Choice = 4
THEN //if choice is 4 total items 10 or more
Number I terns <- 0
FOR Count 0 TO 100
IF Array[Count, 1] >=10
THEN
Number I terns <- Number I terns + 1
ENDIF
NEXT Count
OUTPUT "Number of items that sold 10 or more ", Numberitems
ENDIF
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
11 Programming scenarios practice
CONTINUED
Getting started
1 Identify the data that needs to be input into the system.
2 Identify the outputs that will come from the system.
3 Identify any variables or constants that you may need to use.
Practice
1 Write the program using pseudocode or program code.
2 Check that your program meets all the requirements.
3 Make sure you have added comments to explain your code.
Challenge
Programs can use random number generators. Find out how to use a random
number generator and use this to declare the number at the start of the game,
instead of hard coding a value into the program. Amend your program to use
the random number generator.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
The variable Numberusers stores the how many usernames are currently
stored in the array Logins .
A valid username is one that does not already exist in the array Logins .
A valid username has at least 8 characters, and at least one letter and at least
one number.
Getting started
1 Identify the inputs into the system.
2 Identify the outputs from the system.
3 Identify the requirements for the username and password.
Practice
Write a program using program code or pseudocode to allow a user to enter
a username and password and store this in the array Logins.
11 Programming scenarios practice
CONTINUED
Challenge
The usernames and passwords can be stored in a text file instead of the array.
Each item can be on a different line, e.g.
usernamel
password 1
username2
password 2
Find out how to read and write multiple lines from a text file. At the start of
the program read in all the usernames and passwords to an array. At the end
of the program write all the usernames and passwords back into the file.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SUMMARY
EXAM-STYLE QUESTIONS
1 A program takes a number from the user. It then counts from l to the number
that the user has entered (inclusive). If the number being input is divisible by
5 it outputs a message. If the number being input is divisible by 7 it outputs
a message.
Write a program using pseudocode or program code to solve the problem. [15]
2 A program stores the name (e.g. Dahlia), maximum height in cm (e.g. 100)
and if they can live in shade (e.g. TRUE) of plants in one or more arrays.
The program asks the user to enter their requirement for a plant including:
• The minimum height required.
• If it needs to live in shade or not.
The program should then output all of the plants that meet the requirements.
Write a program using pseudocode or program code to solve the problem.
You can assume the array(s) have already been initialised with 50 plants. [15]
11 Programming scenarios practice
CONTINUED
3 A computer game for two players uses a set of cards. Each card has an
animal; horse, elephant, cat or lion.
Each player starts the game with 15 cards stored in an array; Playerl ,
Player2 .
The first card for each player is compared. The player who wins the round
follows these rules:
• Lion always beats horse.
• Elephant always beats lion .
• Horse always beats cat.
• Cat always beats elephant.
The program compares each card in turn until it has compared all 16 sets of cards.
The player who wins each comparison gets 1 point. If there is a winner at
the end of the game, the program should store the winner’s score in a text file,
and output the player’s name.
Write a program using pseudocode or program code to solve the problem.
You can assume the cards have already been divided between the two players. [15]
4 A program asks the user to enter the cost of 100 items. Each cost should
be stored in an array, Costs . The program should calculate and output:
• The total cost of the items.
• The average cost of the item.
• The cost of the most expensive item.
• The cost of the least expensive item.
Write a program using pseudocode or program code to solve the program. [15]
5 A program stores words in a l D array, Words , with 1000 elements.
The program needs to ask the user to select one of the three actions for
the program to perform.
1 Identify and output how many words have 5 or more letters.
2 Identify and output the longest word in the array.
3 Identify and output the shortest word in the array.
The program needs to use a function for each of the three actions that are
called from the main program.
Write a program using pseudocode or program code to solve the problem.
You can assume the array is already initialised with 1000 words. [15]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
SELF-EVALUATION CHECKLIST
After studying this chapter, think about how confident you are with the different topics.
This will help you to see any gaps in your knowledge and help you to learn more effectively.
You might find it helpful to rate how confident you are for each of these statements when you are revising.
You should revisit any topics that you rated ‘Needs more work' or ‘Getting there’.
stud
Photos within the case studies by Jonathan Banks for Microsoft
There are two case studies included in this book. They are designed to help you understand how some
aspects of computer science are used in the real world. You should find them fun and interesting to
read and study. They also have some questions and activities to help you further develop your thinking
and understanding.
The first case study focusses on the use of testing and how this impacts the development of a product.
The type of testing that you will mainly carry out is software testing. However, hardware must also be
thoroughly tested and the case study provides some interesting information about how this is used by
Microsoft. It will help you gain a greater understanding of the impact and importance of testing when
creating a product for a user.
The second case study focuses on the development of responsible Al and the privacy and security of
data when developing systems. You will learn about Al and how to consider its potential positive and
negative impacts on society. The case study will provide some exciting information about how Microsoft
create responsible Al and the importance of doing so. It will help you gain a greater understanding of the
implications and use of Al in your life and what that can mean for your future.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
Code Jumper allow students to create programs by joining Figure 2: Two students creating a program together.
small hardware pods with cables to form a sequence of
commands, creating an algorithm. Each pod has a different
command enabling such as play, pause and the ability to The design and creation of Code Jumper took a lot of
create selection and iteration. Therefore, each pod is like a time and innovation for Microsoft. The team at Microsoft
statement in the proqram. worked with many children and designers to
create the most recent product. The journey to
that product has often required a great deal of
problem solving, one of the fundamental skills
that you are learning as a computer scientist.
One of the first ideas the design team had was to create created the prototype and tested this with the user. Based
a system similar to a block building computer program, on the result of these tests, they repeatedly reworked
a bit like a physical version of a program called Scratch, and improved the technology to meet the user's needs.
that you may have used when you were younger. Students Without this level of test, they would not have been able
would create programs by taking the blocks and joining to understand whether the pods and how they were
them together. They would click together through the use joined together would work effectively for the students.
of magnets. Microsoft spent time designing and creating The outcome of the testing informed how they needed to
the prototype for this system and trialled it with some change and develop the product to improve it. If they had
students. The students did not use the product in the just made the product, tested it to see if all the parts work
way they had anticipated. They found that the students correctly, then released it, they would still have the original
became frustrated when trying to connect the block. They idea of the magnetic blocks that students didn't use in the
also found that they couldn't pick up their algorithms they way they had been intended. This shows that testing is so
had created with their blocks and pass them to a friend, much more important than just seeing if a program and
as the magnetic connections would fall apart. This would product operate correctly, it shows whether the computer
also happen if the student knocked their algorithm off the system or hardware will meet the needs of the user. It is so
table. They would have the frustration of having to start easy to just consider what we want from a program when we
it all again. Microsoft initially recognised the importance are creating it. However, it is likely that thousands, possibly
of the feel and interaction of the hardware for the visually millions, of people could potentially use that computer
impaired students, but their initial prototype just didn't program. Extensive testing can make sure that many different
have the level and ease of interaction they were looking types of users have tested the product in many ways, to
for. It was back to the drawing board! make sure it meets the needs of different types of users.
ACTIVITY
Microsoft applied the fundamentals of creating a piece of • I will have evidence of testing my work,
technology to the creating of Code Jumper. They analysed such as ...
the needs and requirements of the user, designed and
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
RESPONSIBLE Al
If you haven't learnt already, you will learn what is meant Microsoft currently have a research project called Project
by Al and its main characteristics. As Al becomes part of Tokyo. This is an Al system that helps a blind or visually
almost every activity that we do, it can have a considerable impaired person to identify people that they know around
impact on our lives and choices. Microsoft have to them. Researchers created a prototype of the system on
consider the impact that all of its technologies have on an adapted HoloLens device (see Figure 1). The device
people and society when they create Al systems. They call that the Al system operates on is a headband worn by the
the focus of creating technology in this way 'Responsible user. This headband contains cameras, depth sensors and
Al', making sure that both the operation and the ethics of speakers.
the system have been thoroughly considered. Microsoft
collaborates with researchers and academics around the Have you ever walked into a room and you just see lots of
globe to develop and advance responsible Al practices faces of people that you do not know? You may feel quite
and technologies. shy, you may feel a little nervous, but then you spot a face
of a person that you know and you may then feel much
Microsoft have six principles they apply when creating any more confident about walking into the room. Those who
Al system, these are: are without full vision have to try much harder to listen for
a voice that they may recognise in the crowd, or they may
• Fairness - Al systems should treat people fairly.
just have to wait until someone approaches them. Walking
• Inclusiveness - Al systems should empower everyone into a room can be a daunting task for a visually impaired
and engage people. person - one they face every day!
• Reliability and safety - Al systems should perform When wearing the headband, a user can walk into a room
reliably and safely. and they will be alerted if there is a person they know close
by. The headset will do this by using the cameras to scan
Transparency - Al should be understandable. the room and using the speakers above the users ears to
play sounds they recognise, that will tell them information
• Privacy and security - Al systems should be secure about who is in the room, whether the user knows them
and respect privacy. and where they are.
• Accountability - People should be accountable for Al
systems.
Figure 1: A user wears an adapted HoloLens device running an Al system to recognise people in the room.
Microsoft
For example, a user can walk into the room and they The way Microsoft makes sure the data is kept private
hear a click sound from the headset that sounds like it is and secure is to only store hashes of the data for people's
approximately 1 metre away to their left side. This lets faces. A hash is a type of encrypted message that is very
the user know that a person is stood about 1 metre to their secure. This data is stored without any time stamp or
left. If the Al system then recognises this person's face, the location data to minimise the risk of anyone using this data
user will hear a bump sound and then the name of for malicious intent.
the person. If a user hears a click, but the system cannot
There are lots of implications that need to be considered
detect the other person properly, possibly because it
cannot scan their face properly, the user will hear an elastic
when a system collects and stores data about people.
band stretching sound that will guide the user to turn their Will they feel happy for their face and dimensions to be
scanned? Will they see this as an invasion of their privacy?
face toward the person, to allow for a better placement
for scanning. This feature can also help the user turn their
They may also be concerned with what happens to their
data when it has been scanned. There is also the data that
face toward the other persons, to indicate that they want
to communicate. Many social and communication cues are is stored about the people that know the user. Will the
bystander need to give their consent for this data to be
visual, and fully sighted people can often take them for
stored? Will the bystander worry about how this data is
granted, such as knowing when someone is making eye
used? There could also be a whole range of security issues
contact with them. This feature of the Al system can alert
the user to some of those cues and give them a greater with the storage of this data that you may have already
level of communication and connection with the other learned about if you have studied Chapter 5 of this book.
person.
Questions
This Al system heavily relies on analysing data, it has to
1 How do you feel about your features, such as your
constantly read and update the data from the surrounding
face, being scanned by a person wearing this kind of
environment. It has to compare this data to stored data
system?
to see if it recognises a person. Therefore, one of the key
principles of responsible Al to consider in this project is 2 Do you think it is important to create responsible Al?
the privacy and security of data. Why?
ACTIVITY
385 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
> Glossary
Command words
The command words and definitions in this section evaluate: judge or calculate the quality, importance,
are taken from the Cambridge International syllabuses amount or value of something.
(0478/0984/2210) for examination from 2023. You explain: set out purposes or reasons I make the
should always refer to the appropriate syllabus relationships between things evident I provide why and I
document for the year of your examination to confirm or how and support with relevant evidence.
the details and for more information. The syllabus
give: produce an answer from a given source or recall I
document is available on the Cambridge International
memory.
website www.cambridgeinternational.org.
identify: name I select / recognise.
calculate: work out from given facts, figures or
information. outline: set out the main points.
compare: identify I comment on similarities and I or show (that): provide structured evidence that leads to a
differences. given result.
define: give precise meaning. state: express in clear terms.
demonstrate: show how or give an example. suggest: apply knowledge and understanding to
situations where there are a range of valid responses in
describe: state the points of a topic I give characteristics
order to make proposals / put forward considerations.
and main features.
Key words
1- dimensional array: an array that has only one index. adware: a software based cyber issue that automatically
2- dimensionsal array: an array that has two indices, creates popup advertisements.
abnormal test data: data that a program should not analogue: continuous data that can be any value within
accept. a range.
access levels: the amount of direct access a user is given analogue data: a continuous stream of data that is
to data and resources. This could be set to be only certain processed by humans.
sections of a whole collection of data and resources, analysis: the first stage of the program development life
accumulator (ACC): a register that is built into the ALU cycle that involves investigating the problem.
that stores the result of any interim calculations, AND operator: returns True when both inputs are True,
acknowledgement: a message that is sent from one device anti-malware: a type of software that scans a computer or
to another to indicate whether data is received correctly, device with the purpose of finding and removing malware,
active script: this is the script that is used to produce any anti-virus: a type of software that scans a computer for
of the interactive elements of a web page. viruses with the purpose of finding and removing them,
actuator: a mechanical part that causes another device application software: software that allows the user to
or part to move. perform a useful task.
address: a memory location in RAM. architecture: the design of a computer system, including
address bar: the section of a web browser where you type the components it contains.
the web page address. arithmetic logic unit (ALL): the component in the CPU
address bus: wires used for the transmission of addresses that performs all the mathematical and logical operations
between components in a computer. required when processing data and instructions.
Glossary
arithmetic operator: a symbol that performs a bot: the name given to a computer that has had malware
mathematical function, e.g. ‘+’ adds two values together, downloaded onto it that will cause it to be used in a
array, a data structure where you can store multiple data DDoS attack.
items, of the same data type, under one identifier, botnet: a network of bots that are created to carry out a
artificial intelligence: a part of computer science that DDoS attack.
looks at creating machines that can think and perform boundary test data: data that is on the edge of being
tasks a person would usually perform. accepted, and data that is on the edge of not being
assembler: converts assembly language into machine code, accepted.
assembly language: code written in mnemonics that brute-force attack: a type of cyber threat that involves
allows direct manipulation of the hardware. It must be repeatedly inputting a password until the correct one is
converted into binary code to run. found, to try and break into an account or device,
assignment: a type of programming statement that stores bubble sort: a sorting algorithm that moves through the
data in a variable or constant. list repeatedly swapping values in pairs.
asymmetric: a type of encryption that uses two different cache: a type of storage that is built into the CPU, to
keys to encrypt and decrypt data. store the most frequently used data and instructions,
auto-completion: a feature of an editor that gives the cascading style sheet (CSS): a scripting language that is
user options when they start typing a command, used to create a presentation template for a web page. It
includes what kind of font and colour text will appear
auto-correction: a feature of an editor that identifies
on the web page.
spelling errors and changes them.
CASE statement: a type of selection construct where
automated: a device that is operated without human
there is a list of different values to compare a single
interaction.
value against.
automated system: a system that is designed to operate
casting: converting data from one data type to another
without the need for any human intervention,
data type.
automatic repeat request (ARQ): a type of error
cell: the intersection of the rows and columns of
detection method that uses acknowledgement and
transistors in solid-state storage.
timeout to see if data has arrived correctly after
transmission. central processing unit (CPU): a component in a
computer system that processes data and instructions,
automation: the use of automated equipment in a
process, e.g. a factory. certificate authority: the awarding organisation that
checks if another organisation is real and secure before
average: the mean of a set of values, the total divided by
awarding them a digital certificate.
the quantity.
char: A single character, e.g. A’, ‘1’,
binary: a base-2 number system that uses the values 0
and 1. character set: it contains all the characters that are in
that character set and the binary value that is assigned
biometric device: a device that allows a user to record
to each character.
and input a biometric password.
check digit: a type of error detection method that is
biometric password a type of password that uses a
used for data entry. A calculation is performed on the
persons biological data, such as their fingerprint,
data entered to create a value. Check digit values are
blockchain: a method that is used to track all the compared to see if the data entered is correct,
transactions made with a cryptocurrency.
checksum: a type of error detection method that
bookmark: a link that can be created to allow you to performs a calculation on the data to create a checksum
quickly find a web page again. value. Checksum values are compared after transmission
Boolean: a data type. True or False. to see if they match.
Boolean operator: a symbol that joins multiple logical cipher text: the name given to data after transmission,
comparisons, can be AND OR or NOT. clock speed: the number of fetch-decode-execute cycles
bootstrap: the first commands loaded when a computer that can be performed in a second.
starts, it checks hardware and loads the firmware. cloud storage: data storage that is owned by a third party
and accessed by the user, using the internet.
387 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
coding: the writing of a program using one or more decomposition: taking a system and splitting it into
programming languages. smaller sub-systems, which can in turn be split into
colour depth: the number of bits that are used to create smaller sub-systems.
each colour in an image denary: a base-10 number system that uses the values 0-9.
command line interface: a type of operating system design: the second stage of the program development life
where the user types commands. cycle, which involves decomposition of the problem and
comment: text within a program to describe its function, algorithms created ready for implementation,
it is not executed when the program is run. digital: discrete data that is stored as Is and Os.
compiler: a translator that converts a high-level language digital certificate: a certificate that is awarded to a
into a low-level language. It checks all code before website if they can prove that they are a real organisation
running the program. and take measures to securely transmit their data.
compression: a method that uses an algorithm to reduce digital currency: a currency that exists electronically
the size of a file. rather than physically.
concatenation: joining two or more strings together, digital data: discrete data that only uses the values 0
constant: a named memory location that can store data. and 1.
The data cannot change whilst a program is running, digital ledger: a database that is a list of all the
control bus: wires used for the transmission of control transactions recorded by the use of blockchain.
signals between components in a computer, distributed denial of service (DDoS) attack: a type of
control gate: a component that controls the flow of cyber threat that targets a web server to cause it to crash
electric current. and prevent access to the web pages that it stores.
control unit (Cl): the component in the CPU that DIV: integer division. The remainder from the division is
controls all the operations in the CPU. ignored, e.g. 5 DIV 2 = 2.
cookie: small text file that is used to store personal data, domain name: a specific part of a URL that contains the
by a web browser. unique name for the web server.
core: the part of the CPU that contains all the domain name server (DNS): a special server that contains
components that are used to perform the fetch-decode- a database of domain names and their corresponding IP
execute cycle. address.
count-controlled loop: a type of iteration. Code is run a double: a data type. Decimal numbers.
finite number of times. Usually a for loop. double entry check: two different people enter the same
counting: statements in a program that record how many data which are then compared.
of something there are; a type of program, it adds one driver: a program that controls a device, for example, a
for every item to find out how many there are. printer or a keyboard.
cryptocurrency: a type of digital currency that uses dynamic IP: an IP address that can change each time the
encryption procedures. device connects to a network.
current instruction register (CIR): a register that is built echo check: a type of error detection method that sends
into the CU that holds the current instruction that is a copy of the transmitted data back to the sender to be
being processed in the CPU. compared with the original data sent.
data backup: a copy of data that is stored separate from editor: a feature of an IDE that allows the user to enter
the computer. and amend program code.
data bus: wires used for the transmission of data and embedded system: a computer system that performs a
instructions between components in a computer, dedicated function.
data packet: a unit of data that is used to transmit data encryption: a method of securing data for storage or
across a network. transmission that scrambles it and makes it meaningless,
data type: the characteristics of a piece of data. Common encryption key: a type of algorithm that is used to
data types are string, integer, real and Boolean, encrypt data.
database: an example of application software to store ethernet: another type of connection that can be used to
and manipulate data. transmit data within a network.
Glossary
executable file: a file produced by a compiler that can hypertext transfer protocol secure (HTTPS): a secure
be run independent of translator software and does not version of the HTTP that encrypts data for transmission,
include the source code. identifier: a name given to a variable, constant, data
expert system: a system that attempts to replicate the structure (e.g. array) or subroutine.
knowledge of an expert. IF statement: a type of selection construct where the
extreme test data: data that is on the edge of what is result of the condition is either true or false,
allowed. index the number of the space in the array.
fetch-decode-execute cycle: the cycle through which data inference engine: part of an expert system that makes the
and instructions are processed. decisions.
field: an individual piece of data, e.g. date of birth, infrastructure: the physical structure, such as all the
file handling: programming statements that allow text components and cables, that are used to connect devices,
files to be opened, read from, written to and closed, input: the user entering data into the program, usually
firewall: a cyber security method that is used to examine from a keyboard.
incoming and outgoing traffic from a computer or input device: a device that allows data to be entered into
network. a computer system.
firmware: instructions that are stored in the ROM and instruction set: a set of commands that can be processed
are loaded when the computer starts. by a certain CPU.
floating gate: a component that can store electrical charge, integer: a data type. Whole numbers.
flowchart: a diagrammatic representation of an Integrated Development Environment (IDE): a piece
algorithm. of software that allows a user to write, test and run
format check: a type of validation that makes sure the program code.
data meets a specific order, e.g. 1 number, then 3 letters, interface: the method by which a user communicates
full-duplex: a transmission method where data is with a computer.
transmitted in both directions at the same time, interference: disruption, such as electromagnetism, to
function: a subroutine that does return a value to the data when it is transmitted.
program that called it. Internet of Things: the connection of computer systems
global scope: the variable or constant can be accessed and everyday devices, using the Internet, to allow data
from any part of the program. to be exchanged.
Graphical User Interface (GUI): a type of operating internet: a very large global network that allows users to
system that includes windows, icons, menus and pointers, access the world wide web.
hacker: the name given to a perpetrator that carries out internet protocol (IP) address: the unique address that is
an act of hacking. given to a device when it is connected to a network,
hacking: the act of gaining unauthorised access to data. interpreter: a translator that converts a high-level
This is normally done to steal or corrupt the data, language into a low-level language. It checks one line of
half-duplex: a transmission method where is transmitted code and then executes it before checking the next,
in both directions, but only one direction at a time, interrupt: a signal sent to the processor to tell it that its
hard drive: a storage device that stores data permanently, attention is required.
until it is deleted by the user. interrupt handler (IH): a program that organises
hexadecimal: a base-16 number system that uses the interrupts into an order based upon priorities,
values 0-9 and characters A-F. interrupt service routine (ISR): a program that retrieves
high-level language: a type of programming language an interrupt and performs the required action(s).
that uses English-like commands. iteration: a programming construct. Code is run
hypertext markup language (HTML): a scripting (web multiple times - either a finite number of times (count-
authoring) language that is used to create web pages, controlled), until a condition is true (post-condition), or
while a condition is true (pre-condition).
hypertext transfer protocol (HTTP): a protocol that is
used for the transmission of web pages and related data knowledge base: part of an expert system that stores the
across the internet. facts.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
length check: a type of validation that checks the metadata: additional data that is stored with an image
number of characters is within a set limit. that can provide information such as the dimensions of
library routine: a pre-written subroutine that can be the image and the time and date the image was taken,
called from within a program. microprocessor: an integrated circuit that is able to
linear search: a search algorithm that visits each item of perform many of the functions of a CPU.
data in turn to check whether it is the data being looked minimum: the smallest item in a set of data,
for. mnemonic: instruction code used in assembly language.
local scope: the variable or constant can only be accessed MOD: remainder division. The remainder after the
in the subroutine it is declared within. division is performed, e.g. 5 MOD 2 = 2.
logic expression: a mathematical representation that is natural language interface: a type of operating system
used to represent an electrical circuit or system, that allows the user to type or speak commands,
logic gate: a very small component in a computer system navigate: move around web pages, or move back or
that controls the flow of electricity. forward to previous web pages.
logical operator: a symbol that performs a comparison nested statement: a construct (selection or iteration) that
resulting in True or False. Can be equals, not equal to, is inside another construct.
less than, less than or equal to, greater than, greater
network: computers and devices that are joined together
than or equal to.
using cables or wireless technology.
loop: another name for iteration.
network interface card (NIC): the component in a
lossless: a compression method that reduces the size of a computer that is used to connect it to a network,
file by temporarily altering the data.
non portable: a program that cannot be run on different
loss): a compression method that reduces the size of a types and manufacturers of computers.
file by permanently removing data.
normal test data: data that a program should accept.
low-level language: a language closer to the machine’s
NOT operator: returns True if the input is False, and
language, this could be assembly language or binary code.
False if it is True.
MAC address: a unique address that is given to a
operating system: a program that manages the computer,
computer at the manufacturing stage that can be used to
allows the user to communicate with the computer, and
identify the computer.
allows software to be run.
machine code: binary code, an example of a low-level
optical storage: a type of secondary storage that uses
language.
lasers to store data.
machine learning: a computer program that can adapt its
OR operator: returns True when one, or both, inputs are
stored rules or processes.
True.
magnetic storage: a type of secondary storage that uses
output: data that is displayed to the user usually on
the properties of magnetism to store data,
screen.
maintainable program: a program that has key features
output device: a device that can be used to obtain the
to help it be understood at a later date.
results of data that has been processed.
malware: a type of malicious software that is
overflow error: a type of error that occurs when a
downloaded onto a user’s computer or device,
number larger than a register can store is generated,
maximum: the largest item in a set of data,
packet: a small unit of data.
media access control (MAC) address: the unique address
packet header: a section of a packet of data that
that is given to a NIC by the manufacturer,
contains information about the contents of the packet
memory address register (MAR): a component in the and its destination.
CPU that holds the address of the data or instruction to
packet sniffer: a piece of software that is used to
be located in RAM.
examine the contents in a packet of data.
memory data register (MDR): a component in the CPU
packet switching: a method of transmitting data packets
that holds the data or instruction that are fetched from
across a network. Each data packet is able to take an
RAM.
individual pathway across the network.
Glossary
page: a unit of data. presence check: a type of validation that makes sure data
parallel: a transmission method where data is sent has been entered.
multiple bits at a time down multiple wires, prettyprint: a feature of an editor that changes the
parameter: a value that is sent to a subroutine, colour of text, for example, to highlight key words,
parenthesis: brackets in a mathematical statement. They primary ke\: a unique identifier for a record.
determine which calculations are performed first, primary storage a type of storage that is directly
parity check: a type of error detection method that adds accessed by the CPU.
an additional bit to each byte to create an odd or even procedure: a subroutine that does not return a value to
sum. the program that called it.
payload: the actual data that the user is sending to the process: an action that is performed, for example,
receiver. x = x + 1.
perceptual music shaping: a process that is used in lossy program counter (PC): a component in the CPU
compression that removes sounds that are not normally that stores the address of the next instruction to be
heard by the human ear. processed.
peripheral: a hardware device, used to input, store or program development life cycle: a series of structure step/
output data from a computer, that is not directly part of activities that are followed to produce a system.
the computer itself. programmable: a computer that will run the commands
perpetrator: a person that carries out an illegal or stored in it.
immoral action. protocol: a set of rules for transmitting data,
persistent cookie: a type of cookie that is stored by the proxy server: a method of cyber security that examines
web browser until it is deleted by the user or because it requests sent by devices to access the web pages stored
has expired. on a web server.
pharming: a type of cyber threat that involves pseudocode: code-like statements that are used to design
downloading malicious software onto a user’s hard an algorithm but do not follow any specific language.
drive, that redirects a request aimed at a genuine
RAM (random access memory): a component in the
website to a fake website instead. The fake website will
CPU that holds data and programs that are currently in
encourage the user to input their personal data, allowing
use.
it to be stolen.
range check: a type of validation that makes sure data is
phishing: a type of cyber threat that involves sending a
between the minimum and maximum.
user a fake email that is designed to look genuine. It will
encourage the user to provide their personal data either ransomware: a software based cyber threat that encrypts
by clicking a link to a fake website, or by responding to a user’s data to stop them gaining access to it until a
the email. ransom (money) is paid.
pixel: a very small dot of colour that is displayed with real: a data type. Decimal numbers.
many other to create an image. record: all of the records in a table about one object, e.g.
plain text: the name given to data before encryption, all the personal details about one student.
port: an entry point into a computer or network, register: a small component in a computer system that is
used to temporarily store data.
portable: a program that can be run on different types
and manufacturers of computers. render: the method of processing all the web page data,
such as HTML, to display the web page.
post-condition loop: a type of iteration. Code is run until
a condition is true. The condition is checked after the resolution: the dimensions of an image.
code in the loop is run, therefore the code always runs robot; a machine that replicates human actions or
once. movement.
pre-condition loop: a type of iteration. Code is run while robotics: an area of computer science that looks at the
the condition is true. The condition is checked before creation and use of robots.
running any code in the loop, therefore the code might ROM (read only memory): a type of primary storage
never run. that stores the start up instruction for the computer.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
router: a network component that examines a data software: a series of instructions written in a
packet to obtain its destination address and then programming language that performs a function,
forwards the packet to this address. solid-state storage: a type of secondary storage that uses
rule base: part of an expert system that stores the rules transistors to store data.
based upon the knowledge. sorting algorithm: a series of steps that will rearrange a
run length encoding (RLE): An algorithm that groups set of data into an order, e.g. ascending numerical data,
together repeating patterns and indexes them, sound sampling: a little piece of sound that is recorded at
run-time environment: a feature of an IDE that allows regular time intervals.
a program to be run and lets the user interact with the spreadsheet: a type of application software that performs
program. calculations on data.
sample rate: the number of samples recorded each spyware: a software based cyber threat that spies on a
second. user’s action whilst using a computer, such as logging
sample resolution: the number of bits that are used to their key presses.
record each sound sample. static IP: an IP address that does not change each time
scope: the sections in the code where the variable, or the device connects to a network.
constant, can be accessed. string: a data type. Any characters including letters,
script: a set of statements that are executed, numbers and/or symbols.
search algorithm: a series of steps that searches for a structure diagram: a hierarchical diagram that shows the
specific value in a set of data. decomposition of a system.
secondary storage: a type of storage that is designed to Structured Query Language (SQL): a standard language
store data permanently, until it is deleted by the user, used to define and manipulate databases.
secure sockets layer (SSL) protocol: a type of protocol subroutine: a self-contained piece of code that has an
that encrypts data for transmission. It is the protocol, identifier and can be called from elsewhere in a program,
that is combined with the HTTP to create HTTPS, symmetric: a type of encryption that uses the same key
selection: a programming construct. A condition is to encrypt and decrypt data.
checked and this determines which code is run, or system software: a type of software that manages the
not run. hardware and software in a computer.
semiconductor chips: an electronic circuit, where tab: a website function that allows you to open multiple
transistors are set on a semiconductor material, such web pages in the same window.
as silicon.
table: a set of data about one type of object, e.g. students,
sensor: a type of input device that is used to capture data
test data: the input data that is used to test a system,
from its immediate environment.
testing: repeated use of a system to try all different
sequence: a programming construct. Instructions are run
possibilities to make sure the system is fully working and
once and in the order they are written.
cannot be broken.
serial: a transmission method where data is sent one bit
timeout: a period of time that is set and used to wait for
at a time down a single wire.
an acknowledgement to be received.
server: a component that acts as a central resource for
totalling: statements in a program that add together a set
the storage of data and applications or for providing a
of data to produce the total; a type of program, it adds
service.
up multiple values to find the total.
session cookie: a type of cookie that is deleted when the
trace table: a structure to complete when walking
web browser is closed.
through an algorithm manually, where the values that
simplex: a transmission method where data is change are written in each row.
transmitted in a single direction only,
trailer: a section of a packet of data that contains
single: a data type. Decimal numbers. information about any error checking methods that may
social engineering: a cyber threat that involves be used.
manipulating or deceiving people into providing transistor: a device that acts as a switch or gate for
confidential or personal data. electronic signals.
Glossary
translator: a type of software that converts code written validation: the checking of data to make sure it is
in one programming language into another, usually a reasonable and within set bounds.
high-level language into a low-level language, variable: a named memory location that can store data.
transmission media the cables that are used to transfer The data can change whilst a program is running,
data in a network. verification checking that data is entered accurately, that
transport layer security (TLS) protocol: an updated it is the same as the original.
version of the SSL protocol. virtual memory a type of memory that can be used as an
trojan horse: a software based cyber threat that is used extension to the RAM.
to disguise other malware to try and smuggle it into a virus: a software based cyber threat that replicates itself
computer or network. with the aim of corrupting data or filling up the available
truth table: a method to show all the different outcomes memory space in a computer, causing it to crash,
of an electrical circuit or system, dependent on the visual check: comparing the data entered with the
inputs it receives. original side-by-side.
two-step verification: a process that involves inputting voltage the pressure that forces the charged electrons to
two different kinds of data to enter an account or flow in an electrical circuit.
device. web browser: a piece of software that retrieves and
type check: a type of validation that checks data is the displays web pages.
correct data type. web page: a single page within a website,
uniform resource locator (URL): another name for the
web server: a network component where the web pages
text-based address for a website.
for a website are stored.
USB: an industry standard that is used to transmit data.
website: a collection of web pages, normally about a
USB cable: a type of transmission media that uses the related topic or purpose.
USB method to transmit data.
window: a viewing area that is created in which a
I SB connection: a collective name for using a USB software application or file can be opened,
cable plugged into a USB port to transfer data from one
word processor a type of application software that
device to another.
allows the user to create text-based documents,
I SB device the name of a device that plugs into a USB
world wide web: the collection of all the web pages and
port on a computer.
websites that have been made available.
USB port: a socket that is a part of a device or computer
worm: a software based cyber threat that replicates itself
that enables you to insert a USB cable.
across a network using vulnerabilities that it finds, with
username: a text-based identification that is given to a the aim of clogging up the bandwidth.
user that identifies the level of access that they have to
zombie the name given to a bot that has malware
stored data and resources.
downloaded onto it to allow it to be used in a DDoS
utility programs: system software that performs attack, but it currently isn’t being used in this way. It is
housekeeping activities. effectively a dormant or sleeping bot.
393 )>
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK
> Index
1- dimensional arrays 270-7 artificial intelligence (Al) 136-7
2- dimensional arrays 277-84 case study 384-5
expert systems 139
abnormal test data 157-8 machine learning 137-8
accelerometers 64, 65 ASCII 21
access levels 120-1 assemblers 88
accumulator (ACC) 59 assembly language 79, 86
acknowledgement 47 assignment statements 198-201
acoustic sensors 64 auto-completion 90
active script 98 auto-correction 90
actuators 127 automated systems 63, 126-9
addition 211 automatic repeat request (ARQ) 47
address bar 101 automation 130-1
address bus 57 see also robots
addresses 57 averages 171-2
adware 113
algorithms 144-5, 149 Berners-Lee, Tim 97
averages 171-2 binary system 9
bubble sort 161-6 addition 16-18
counting 168-9 conversion to/from denary 10-13
data validation 173-7 logical binary shifts 19-20
finding the maximum 170-1 negative numbers 20
finding the minimum 170 biometric devices 107
finding the purpose of 184-6 Bitcoin 105
flowcharts 149-53 bits 11,25
linear search 159-61 blockchaining 105-6
totalling 167 bookmarks 101
trace tables 179-83 Boolean data 202, 298
alphanumeric data 298 Boolean logic see logic circuits; logic gates
analogue data 10 Boolean operators 227, 307-8
analysis 145-6 bootstrap 81
AND gate 327-8 botnets 109-11
AND operator 227, 308 bots 110
anti-malware software 110, 114 boundary test data 157-8
application software 80, 81, 83 break points 91
arithmetic logic unit (ALU) 59 brute-force attacks 106-7
arithmetic operators 209-14 bubble sort 1613
arrays 270 characters 165-6
1- dimensional 270-7 numerical data 163—4
2- dimensional 277-84 bytes 25
accessing data 272-3, 278-9
using iteration in 274-7, 281-4 caches 60, 61
using variables as indices cascading style sheets (CSS) 98
273—4, 279-80 CASE statements 216, 224-6
Index
> Acknowledgements
The authors and publishers acknowledge the following sources of copyright material and are grateful for the permissions
granted. While every effort has been made, it has not always been possible to identify the sources of all the material used,
or to trace all copyright holders. If any omissions are brought to our notice, we will be happy to include the appropriate
acknowledgements on reprinting.
Thanks to the following for permission to reproduce images:
Cover Nerthuz/Getty Images; Inside Introduction Yuichiro Chino/GI; Flashpop/GI; Sompong Rattanakunchon/GI;
Compassionate Eye Foundation/Robert Daly/GI; Monty Rakusen/GI; THOMAS SAMSON/GI; Justin Paget/GI;
Deepblue4you/GI; Maximum PC Magazine/GI; Science Photo Library/GI; Mikroman6/GI; PC Format Magazine/
GI; Maximum PC Magazine/GI; OMAR TORRES/GI; PC Format Magazine/GI; Georges Mir/GI; Blackred/
GI; Chapter 1 KTSDESIGN/SCIENCE PHOTO LIBRARY/GI; Matejmo/GI; Fotosearch/GI; Chapter 2 Andrew
Brookes/GI; shapecharge/GI; Westend61/GI; Carol Yepes/GI; Alengo/GI; Chapter 3 Viaframe/GI; Andrey Popov/
GI; Yod67/GI; Artiemedvedev/GI; fStop Images Caspar Benson/GI; Anthony Danielle/GI; Steve Russell/GI;
Westend61/GI; Deepblue4you/GI; Zelma Brezinska/GI; Karl Tapales/GI; lvcandy/Gl; Powerbeephoto/GI; Kittichai
Boonpong/GI; Chapter 4 Andriy Onufriyenko/GI; Everett Collection/Shutterstock; Andrew Steele/GI; Mikimad/GI;
Lushik/GI; Malli Themd/Shutterstock; OMAR TORRES/GI; Daniel Acker/Bloomberg via GI; Science & Society
Picture Library/GI; Chapter 5 Aaron Tian/GI; MoMo Productions/GI; Harry Kikstra/GI; zf L/GI; Fotograzia/GI;
popJop/GI; Brian Killian/Wirelmage/GI; MARK GARLICK/SCIENCE PHOTO LIBRARY/GI; Sorbetto/GI;
Daniel Sambraus/GI; Sitthiphong/GI; ET-ARTWORKS/GI; Tommy/GI; Luis Alvarez/GI; Eternity in an Instant/
GI; Education Images/Universal Images Group via GI; Jakub Porzycki/NurPhoto via GI; Chapter 6 MR.Cole/GI;
Science & Society Picture Library/GI; Construction Photography/Avalon/GI; Christopher Furlong/GI; Heritage
Images/GI; Alexander Koerner/GI; Chris Hondros/Gl; Scharfsinn86/GI; Smith Collection/Gado/GI; Bruce Bennett/
GI; SEBASTIEN BERDA/GI; Chapter 7 Rizky Panuntun/GI; Stanislaw Pytel/GI; mikroman6/GI; Chapter 8 Filo/
GI; Marc Volk/GI; Chapter 9 Yuichiro Chino/GI; PM Images/GI; Chapter 10 Nikada/GI; benimage/GI; Chapter 11
MarsYu/GI; Westend61/GI; Klaus Vedfelt/GI; Microsoft case studies SeventyFour/GI
GI = Getty Images
Images within case studies supplied by Microsoft Research, photos by Jonathan Banks for Microsoft. Microsoft
product screenshots are used with permission from Microsoft.
Microsoft is a registered trademark of Microsoft Corporation.
Adobe product screenshot(s) reprinted with permission from Adobe.