100% found this document useful (13 votes)
88K views410 pages

Computer Science For IGCSE Cambridge Course Book 2022

Uploaded by

harry2wang4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
88K views410 pages

Computer Science For IGCSE Cambridge Course Book 2022

Uploaded by

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

Cambridge

UNIVERSITY PRESS

Computer Science
for Cambridge IGCSE™& O Level
COURSEBOOK

Sarah Lawrey & Victoria Ellis


Cambridge IGCSE™ & O Level Computer Science

Build upon the fundamentals of computational thinking and programming with


this coursebook, developed to support you through the Cambridge IGCSE™ &
O Level Computer Science syllabuses (0478/0984/2210). Bring computer science
to life through real-life contexts and applications, including a new 'Introduction
to programming scenarios' chapter and case studies from Microsoft® Research.
A three-tiered approach to programming tasks across the coursebook
develops both skills and confidence for learners of all levels of understanding.
Answers to all questions are accessible to teachers for free online at
www.cambridge.org/go

• 'Computer science in context' feature connects you to real-life scenarios


and technology
• 'Skills focus' sections develop your mathematical, computational thinking and
programming knowledge, including step-by-step examples and questions
• New self-evaluation checklist and peer assessment features encourage
you to reflect on your own progress and learn from one another
• A wealth of new exam-style questions in every chapter provides you with
exam practice activities throughout the course
• Access all your Cambridge GO resources anytime, anywhere and create
your own collection in 'My Resources'

This resource is endorsed by \>


Cambridge Assessment International Education
Cambridge Completely Cambridge
Supports the full Cambridge IGCSE, Cambridge University Press works with Cambridge
IGCSE (9-1) and 0 Level Computer Science Assessment International Education and experienced
syllabuses (0478/0984/2210) for examination authors to produce high-quality endorsed textbooks
from 2023 and digital resources that support Cambridge Teachers
and encourage Cambridge Learners worldwide.
Has passed Cambridge International's
rigorous quality-assurance process To find out more visit
cambridge.org/cambridge-international
Developed by subject experts

For Cambridge schools worldwide

Brighter Thinking ISBN 978-1-108-91514-4

Better Learning Cambridge 9781108915144

UNIVERSITY PRESS
9 781 08 915144 >
Building Brighter Futures Together
Cambridge
UNIVERSITY PRESS

Computer Science
for Cambridge IGCSE™ & O Level
COURSEBOOK

Sarah Lawrey & Victoria Ellis


Cambridge
UNIVERSITY PRESS

University Printing House, Cambridge CB2 8BS, United Kingdom


One Liberty Plaza, 20th Floor, New York, NY 10006, USA
477 Williamstown Road, Port Melbourne, VIC 3207, Australia
314-321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi - 110025, India
79 Anson Road, #06-04/06, Singapore 079906

Cambridge University Press is part of the University of Cambridge.


It furthers the University’s mission by disseminating knowledge in the pursuit of education,
learning and research at the highest international levels of excellence.

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

Printed in Malaysia by Vivar Printing


A catalogue recordfor this publication is available from the British Library
ISBN 978-1-108-91514-4 Coursebook Paperback with Digital Access (2 Years)
ISBN 978-1-108-82414-9 Digital Coursebook (2 Years)
ISBN 978-1-108-82416-3 Coursebook eBook
Additional resources for this publication at www.cambridge.org/go
Cambridge University Press has no responsibility for the persistence or accuracy of URLs for external or third-party internet
websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain, accurate
or appropriate. Information regarding prices, travel timetables, and other factual information given in this work is correct
at the time of first printing but Cambridge University Press does not guarantee the accuracy of such information thereafter.
Exam-style questions and sample answers have been written by the authors. In examinations, the way marks are awarded
may be different. References to assessment and/or assessment preparation are the publisher’s interpretation of the syllabus
requirements and may not fully reflect the approach of Cambridge Assessment International Education.
Cambridge International copyright material in this publication is reproduced under licence and remains the intellectual
property of Cambridge Assessment International Education.

NOTICE TO TEACHERS IN THE UK


It is illegal to reproduce any part of this work in material form (including photocopying and electronic storage)
except under the following circumstances:
(i) where you are abiding by a licence granted to your school or institution by the Copyright Licensing Agency;
(ii) where no such licence exists, or where you wish to exceed the terms of a licence, and you have gained the written
permission of Cambridge University Press;
(iii) where you are allowed to reproduce without permission under the provisions of Chapter 3 of the Copyright,
Designs and Patents Act 1988, which covers, for
example, the reproduction of short passages within certain types of educational anthology and reproduction
for the purposes of setting examination questions.
DEDICATED
< >TEACHER
L AWARDS

Teachers play an important part in shaping futures.


Our Dedicated Teacher Awards recognise the hard
work that teachers put in every day.
Thank you to everyone who nominated this year; we have been inspired and moved
by all of your stories. Well done to all of our nominees for your dedication to learning
and for inspiring the next generation of thinkers, leaders and innovators.

Congratulations to our incredible winner and finalists!

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

Building Brighter Futures Together


> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

> 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

2 Data transmission 33 6 Automated and emerging


2.1 The structure of a data packet 35 technologies 125
2.2 Packet switching 36 6.1 Automated systems 126
2.3 Methods of data transmission 38 6.2 Robotics 132
2.4 The universal serial bus (USB) 6.3 Robots in context 132
interface 43
6.4 Artificial intelligence 136
2.5 Detecting errors in data transmission 44
2.6 Encryption 49 Algorithm design and
problem solving 143
3 Hardware 54
7.1 Program development life cycle 145
3.1 The role of the CPU 56
7.2 Analysis 146
3.2 The fetch stage 57
7.3 Design 146
3.3 The decode stage 58
7.4 Pseudocode 154
3.4 The execute stage 58
7.5 Coding 157
3.5 Factors that can affect the
7.6 Testing 157
performance of a CPU 60
7.7 Common algorithms 159
3.6 Input and output devices 62
7.8 Trace tables 179
3.7 Data storage 66
7.9 Finding the purpose of an algorithm 184
3.8 Virtual memory 69
7.10 Finding errors in a program and
3.9 Cloud storage 70
correcting the errors 187
3.10 Network hardware 72
Contents

Programming 196 10 Boolean logic 324


8.1 Programming concepts 198 10.1 The role of logic gates 326
8.2 Data types 202 10.2 The NOT logic gate 326
8.3 Input and output 205 10.3 The AND logic gate 327
8.4 Arithmetic operators 209 10.4 The OR logic gate 329
8.5 Sequence 214 10.5 The NAND logic gate 330
8.6 Selection 216 10.6 The NOR logic gate 331
8.7 Iteration 231 10.7 The XOR logic gate 333
8.8 Totalling 241 10.8 Logic expressions 337
8.9 Counting 243 10.9 Representing truth tables 339
8.10 String manipulation 245 10.10 Representing logic expressions 344
8.11 Nested statements 251 10.11 Representing problem statements 347
8.12 Subroutines 255
11 Programming scenarios practice 353
8.13 Library routines 265
8.14 Maintainable programs 267 11.1 Programming scenario 355
8.15 Arrays 270 11.2 Method 1: Identifying the inputs,
processes and outputs 355
8.16 File handling 286
11.3 Writing the code 357
Databases 295 11.4 Method 2: Practically carrying out the
program and identifying the stages 365
9.1 Database structure 297
9.2 SQL 302 Microsoft case studies 381
9.3 SELECT . . . FROM 302
9.4 SELECT . . . FROM . . . WHERE 305
Glossary 386
9.5 Order by 311 Index 394
9.6 SUM 312
Acknowledgements 400
9.7 COUNT 313
Coursebook answers
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

> How to use this book


Throughout this book, you will notice lots of different features that will help your learning. These are explained
below. Answers to all questions and activities are accessible to teachers in the ‘supporting resources’ area of
cambridge.org/go.

GETTING STARTED

This contains questions and activities on subject knowledge you will need before starting this chapter.

COMPUTER SCIENCE IN CONTEXT PROGRAMMING TASKS


This feature presents real-world examples Programming tasks give you the opportunity
and applications of the content in a chapter, to develop your programming and
encouraging you to look further into topics. The problem-solving skills.
'Computer science in context' feature that opens
Each task is divided into three parts:
each chapter also ends with discussion questions.
Getting started
• These questions will help build your basic
KEY WORDS problem-solving skills.

Key vocabulary is highlighted in the text when it is Practice


first introduced. Definitions are then given in the
margin and can also be found in the glossary at • These questions will ask you to design a
the back of this book. possible solution to a problem or complete a
coding task.

SKILLS FOCUS Challenge


• These questions will stretch and
This feature supports your computational thinking, challenge your problem-solving, logic and
mathematical and programming skills. The features programming skills even further.
include useful explanations, step-by-step examples and
questions for you to try out yourselves.

TIPS

These are short suggestions to remind you about


important learning points.
How to use this book

COMMAND WORDS ACTIVITY

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.

Further Information: This feature highlights the


advanced aspects in this book that go beyond the
immediate scope of the syllabus.

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

See Needs Getting Confident


1 can...
topic more work there to move on
add two 8-bit binary numbers.
112....... 1
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

> How to use this series


V The coursebook provides coverage of the full Cambridge IGCSE™ and
Cambridge
O Level Computer Science syllabuses (0478/0984/2210) for first examination
Computer Science from 2023. Each chapter explains facts and concepts and uses relevant
real-world contexts to bring topics to life, including two case studies from
Microsoftk Research. There is a skills focus feature containing worked examples
and questions to develop learners’ mathematical, computational thinking and
programming skills, as well as a programming tasks feature to build learners’
problem-solving skills. The programming tasks include ‘getting started’ skills
development questions and ‘challenge’ tasks to ensure support is provided for
every learner. Questions and exam-style questions in every chapter help learners
to consolidate their understanding.

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

advice for identification of different learner needs and suggestions of


appropriate interventions to support and stretch learners.
The digital teacher’s resource also contains scaffolded worksheets
for each chapter, as well as practice exam-style papers. Answers are
freely accessible to teachers on the ‘supporting resources’ area of the
Cambridge GO platform.

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

p 1 ■' to* ^fF A


>
‘<’iV
, •
I• • < •■ S-:.’
♦ 4*
f «, r • >>i
* V *
• »> • • *-J
’uJV
> > w e kX^lA? %
V
• I «
i >/ « •
*
Xi^vi ;» b ’
' *\
4 V
• ; >,
I
1 ♦ ' x*
< A .
I * to V V*J <
I * I I ' * \
i *■ \ r« 4«
4
) CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

What is computer science?


Computer science is the study of computers and computational thinking.
It includes the purpose and operation of hardware, software and networks.
Computer science involves studying theoretical ideas about how data is processed and
stored, and what would be necessary to perform such theoretical operations. It is also
the practical application of these ideas to create new hardware and software.
Studying hardware involves learning about the basic design of computers and how
they operate, including how they perform calculations, logical operations and how they
store data. It involves understanding how and why binary is used in a computer for
these processes.
Studying software involves learning about the different programming concepts and
how to apply these in different programming languages. It involves looking at how
translators are used to convert programming languages into the necessary binary state
needed for a computer to process. It also involves learning about different types of
software, such as operating systems and applications.
Studying networks involves learning about how data is transmitted across a network,
including some of the components involved in this process. It also involves looking at
the risks involved in using a network and how you can use different methods to help
prevent exposure to these risks.
Introduction

Why should you study


computer science?
Over the years since their invention, computers
have dramatically changed the way many of us
live. The introduction of the personal computer
(PC) into many homes around the world has led to
the development of the internet, which began to
transform the way that many people communicate
and share information.
The use of computer systems is now a widespread
practice. They range from small embedded systems
in our everyday devices, such as refrigerators, traffic
lights, digital cameras and washing machines, to
being responsible for handling the world’s money in Hardware and software used in an industrial setting
huge banking systems.
There are many aspects of our life today that would not be possible on the same
scale without the use of computers, so studying what they are, how they work and
the many purposes they have can be both fun and exciting. It can also be very
interesting and challenging as you try to understand the complex nature of their
operation.
There are many lifelong skills that you can develop through learning about computer
science, these including logical thinking, creativity and problem solving. These are all
skills that add to your employability status in the future.
Computer scientists are needed in many different industries, so the choice of career
that you could take is very open. Industries such as science, engineering, finance,
manufacturing, sports and healthcare all use a wide variety of computers and require
lifelong skills that the study of computer science builds.
Computers advance on a constant basis, so being part of the study of how that
happens keeps your studies relevant and engaging. What are you waiting for?
Let the enjoyment begin!

Doctors performing robotic surgery Aeronautical engineer using a tablet computer


y CAMBRIDGE 1GCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Under the hood of a computer


In order to study their wider purpose, it is useful to understand what exactly is ‘under
the hood’ of a computer. Let’s look at a personal computer (PC), what are the
components that they contain?

Power supply unit Random access memory (RAM)

Computer
case
Optical
drive
Computer
case fan

Central
processing
unit (CPU)
cooling fan Hard
drive

Central
processing
unit (CPU)
(under
the fan)

Graphics card Motherboard


Inside a desktop computer case

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

Computer case fan


The components inside a computer consume power to operate. This means that they can
often get quite hot. A computer case has a fan that is attached to the side of it that spins
to keep the components within the case nice and cool. If a computer is needed for high
performing tasks that will require more power, it may need more than one case fan.

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!

CPU Cooling fan


One component that can get very hot in a computer is the CPU.
It is constantly working and it is completing millions of cycles
each second. It is vital that the CPU doesn’t get too hot or it will
no longer work. Therefore, the CPU normally has its own fan
that sits directly on top of it. This keeps it running at the best
temperature for it to operate. CPU cooling fans can just be a
simple fan, or they can be as elaborate as water cooling systems
to keep the CPU at the best temperature.

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

IN THIS CHAPTER YOU WILL:

learn why computers use binary to process data

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

learn to use two's complement to represent negative binary numbers

learn how the file size of data is measured

learn how and why data is compressed.


1 Data representation

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

DEBUGGING USING HEXADECIMAL

Computer programs are the foundation of computer games. If there is


an error with the program, this can cause unexpected behaviour in the
game. For example, a character may move the wrong way when a
button is pressed. The programmer needs to find out why the character is
moving incorrectly. The amount of code that needs to be assessed to find KEY WORDS
this error in a computer game is enormous and the binary values involved
will be vast. Therefore, the programmer will often use hexadecimal to hexadecimal: a
debug the error. One way this can be done is to look at the address for a base-16 number
variable. The address is the location in memory where the data is stored and system that uses
it is shown in hexadecimal. This address is then looked up in a table to find the values 0-9 and
the value held in the address. The value is also given as hexadecimal. If the characters A-F.
value in the address is, for example, 0000 or FFFF (this can mean that the
variable has not been initiated) the programmer will know that there is a
binary: a base-2
number system that
problem with this value and has located the variable with which the error is
occurring. The programmer can then find out why the variable is not holding uses the values 0
and 1.
a valid value.

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.

Figure 1.1: Data represented by hexadecimal letters and numbers


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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?

2 Why is it important for a programmer to be able to effectively debug a


computer program?

1.1 Binary and hexadecimal


Humans process a large amount of data on a daily basis. Did you know that when we
have a conversation with someone, we process approximately 60 bits of information
per second? Our brain is designed to process a maximum of about 120 bits per second.
That’s why it is so difficult to listen to two people talk to us at once! KEY WORDS

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

SKILLS FOCUS 1.1

CONVERTING BETWEEN DENARY AND BINARY NUMBERS

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.

SKILLS FOCUS 1.2

CONVERTING BETWEEN DENARY NUMBERS AND HEXADECIMAL

To convert a denary number to hexadecimal, it is easier to convert it to binary first.


For example:
First convert the denary number 7 to 4-bit binary.

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

Why is hexadecimal used in computer science?


Programmers often use hexadecimal when writing and analysing computer programs.
They do this because it is easy for a human to read hexadecimal, rather than binary.
For example, if a programmer looked at a set of data that is stored in registers, as
binary it could look like this:
10011100101110111000111011100010111101011010
The programmer may be trying to find out if the data stored matches the correct data
which should be:
10011100101110111001011011100010111101011010
At a glance, it is difficult to see whether the two values match or if an error has
occurred.
If that stored data is represented in hexadecimal it would be:
9CBB8EE2F5A
Comparing it to the correct value that should be:
9CBB96E2F5A
It is much easier to see that the data does not match, and the programmer can identify
that an error has occurred.
The benefits of using hexadecimal rather than binary for a programmer are:
• Hexadecimal is a shorter way of representing binary, so it takes up less space on
the computer screen or piece of paper.
• Hexadecimal is easier for a programmer to read, write and understand.
• Hexadecimal is easier to debug and locate errors in data.

ACTIVITY 1.1 KEY WORD

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.

1.2 Binary manipulation and


negative numbers
Binary addition
You need to be able to add together two 8-bit binary numbers. When binary numbers
are added together there are four rules that you will need to use:
Rule 1 is 0 + 0 = 0
1 Data representation

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

Logical binary shifts


Another process than can occur with binary numbers that are stored in a register
is called a logical binary shift. This kind of shift can move the binary values in the
number to the left or to the right.
Consider the binary number:

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.

Negative binary numbers


All the binary numbers that you have used so far have been positive binary numbers.
Numbers can sometimes be negatives number though, for example, -150. How are
negative numbers represented as binary? Binary only has two values that can be used,
a 0 and a 1, so you can’t just put a minus symbol (-) in front of the number, as that
symbol doesn’t exist in binary. Therefore, a method exists that can be used to represent
negative binary numbers and it is called two’s complement. Most modern computers
use this method.
The method of two’s complement is a simple one. First you invert all the values in the
binary number (change the Is to Os and the Os to Is), then you add 1 to the result. You
can use this process to find out how the denary value -35 is represented as binary.
Convert 35 to a binary number:

0 0 1 0 0 0 1 1

Invert each of the values in the binary number:

1 1 0 1 1 1 0 0

Then simply add 1:

1 1 0 1 1 1 0 1

11011101 is the binary representation of -35 using the two’s complement method.
1 Data representation

1.3 How do computers represent text,


images and sound?
You have already learnt that computers only process binary. This means that all data
must be converted to binary to be processed by a computer. You have already looked at
converting numbers, but text, images and sound all have to be converted to binary too,
so they can be processed by a computer. How is this done?

Converting text to binary


KEY WORD
When a computer converts text to binary to be processed it uses a tool called a
character set. There are two main types of character set that a computer can use, character set: it
ASCII and Unicode. An ASCII character set represents characters using 8-bit binary contains all the
numbers. This means that it can represent up to 256 characters (0 to 255). This is fine characters that are in
for certain languages, but some languages have an alphabet that requires more than that character set and
256 characters; therefore, Unicode was invented. A Unicode character set represents the binary value that
characters using 16-bit binary numbers. This means it can represent a much greater is assigned to each
number of characters, approximately 65 000. This means that many more characters character.
can be developed in different alphabets and also symbols such as emojis can also
be used.
Each character has a set binary value, for example, the letter A is 01000001.

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.

Converting images to binary KEY WORD

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.

COMPUTER SCIENCE IN CONTEXT

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.

Converting sound to binary


KEY WORD
Sound is made up of sound waves. When sound is recorded, this is done at set time
intervals. This process is known as sound sampling. sound sampling: a
little piece of sound
that is recorded at
regular time intervals.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Figure 1.4: A sound wave

Figure l .4 is an example of a sound wave.


If you recorded the sound at each time sample, you would have the following set of
values:

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:

Figure 1.5: A sound wave created by playing back a recorded sound

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.

1.4 Measuring data storage


Earlier in the chapter, you learnt that all data need to be converted to digital data to
be processed by a computer, and you now know how that is done for different types of
data. But how is data measured when it is stored?

COMPUTER SCIENCE IN CONTEXT

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.

SKILLS FOCUS 1.3

CALCULATING THE SIZE OF A 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)

1.5 Data compression


You may already have experience of having large files and struggling to have enough KEY WORDS
storage space to store them. One thing that can be done to reduce the size of a file
is compression. compression: a
method that uses an
Compressing a file will reduce the size of the file that can have several benefits, such as:
algorithm to reduce
• Not as much storage space is needed to store the file. the size of a file,
• It will take less time to transmit the file from one device to another. lossy: a compression
• It will be quicker to upload and download the file. method that reduces
the size of a file
• Not as much bandwidth is needed to transmit the file over the internet. by permanently
There two type of compression that can be used, lossy and lossless. Each compresses removing data.
the data in a different way. lossless: a
Lossy compression uses a compression algorithm that finds the unnecessary and compression method
redundant data in the file. This data is permanently removed from the file. This type of that reduces the
compression is mainly used on an image file or a sound file. size of a file by
temporarily altering
Unnecessary data in an image file that could be removed are colours that the human
the data.
eye cannot distinguish. This means that a lossy compression algorithm for an image file
could reduce the size of the file by reducing the colour depth. It could also reduce the
size of the file by reducing the image resolution, reducing the number of pixels used to
create the image.
Unnecessary data in a sound file that could be removed are sounds that cannot be heard
by the human ear. It could also be the removal of softer sounds that are played at the KEY WORD
same time as louder sounds, as humans will only hear the louder sound. The method that
is used to find these kinds of sounds in a sound file is called perceptual music shaping. perceptual music
This is the most common type of method that is used in the file format MP3. The size of shaping: a process
a sound file can also be reduced by reducing the sample rate and the sample resolution. that is used in lossy
compression that
removes sounds that
Questions are not normally
heard by the
7 Why do you think lossy compression is not commonly used on text files?
human ear.
8 Will lossy compression affect the quality of an image? Why?
9 Will lossy compression affect the quality of a sound recording? Why?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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:

WHEN IT IS SNOWING HEAVILY LOOK OUTSIDE.


LOOK OUTSIDE IT IS SNOWING HEAVILY.

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:

Word Position(s) in the message


WHEN 1
IT 2, 10
IS 3, 11
SNOWING 4, 12
HEAVILY 5, 13
LOOK 6, 8
OUTSIDE 7,9

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

show (that): provide


structured evidence
that leads to a given
result.

calculate: work
out from given
facts, figures or
information.

give: produce an
answer from a given
source or recall I
memory.

explain: set out


purposes or
reasons I make
the relationships
between things
evident I provide
why and/or how and
support with relevant
evidence.

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

1 can... See Needs Getting Confident


topic more work there to move on
explain why data needs to be converted to binary to
1.1
be processed by a computer.
convert between denary numbers and
1.1
binary numbers.
convert between denary numbers and hexadecimal. 1.1
convert between binary numbers and hexadecimal. 1.1
provide examples of the use of hexadecimal in
1.1
computer science.
explain why hexadecimal is used in computer science. 1.1
add two 8-bit binary numbers. 1.2
explain what is meant by an overflow error. 1.2
perform a logical binary shift on a binary number,
1.2
including left and right shifts and multiple shifts.
use twos complement to represent negative
1.2
numbers.
explain how character sets are used by a computer
1.3
to represent text.
explain how pixels are used by a computer to
1.3
create images.
explain how the file size of an image is affected by
1.3
the image resolution and colour depth.
explain how a sound wave is sampled by a computer. 1.3
explain how the file size of a sound recording is
1.3
affected by the sample rate and sample resolution.
understand how the size of a data file is measured. 1.4
calculate the size of an image file. 1.4
calculate the size of a sound file. 1.4
understand the need for data compression and the
1.5
effect it has on a file.
explain how different types of data are compressed
1.5
using lossy compression.
explain how different types of file are compressed
1.5
using lossless compression.
> Chapter 2

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

understand how data is transmitted using a range of different transmission methods

be able to choose a data transmission method for a given scenario

learn about the universal serial bus (USB) interface and how it is used to transmit data

learn how errors can occur when transmitting data

be able to describe how a range of different error detection methods work

understand why it is useful to encrypt data when it is transmitted

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.

DATA TRANSMISSION IN THE FINANCIAL WORLD


A bank has to transmit data all around
the world for thousands, possibly
millions, of people on a daily basis.
The accuracy of this data is imperative.
Imagine what would happen if one
person's hard earned money went
into another person's bank account!
When data is transmitted, there are
certain things that can cause it to
suffer errors. Interference is a big issue
in data transmission that can cause
errors in the data, therefore banks
have to make sure that they have many
error detection methods in place to
make sure that data is accurate, even
after transmission. As the accuracy
of the data is so crucial for banking
transactions, banks have to combine Figure 2.1: Financial transactions can be done online
several types of error detection, to
make sure that the data has been
thoroughly and completely analysed for errors.

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

2.1 The structure of a data packet


The amount of data that is stored in a file can be very large. If you tried to transmit
this data from one device to another, all at once, this just wouldn’t be possible or
practical. The wires or radio waves used would simply not be able to accommodate KEY WORDS
sending such large amounts of data at a single time. Therefore, for the data in a file to
be transmitted, it is broken down into very small units called packets. packet: a small unit
of data.
Each packet of data contains three different sections:
packet header: a
Packet header section of a packet
Payload of data that contains
Trailer information about
the contents of
The packet header contains a lot of important information about the data enclosed in the packet and its
the packet and its destination. The information it includes is the: destination.
• destination address internet protocol
• packet number (IP) address: the
unique address that
• originators address. is given to a device
The destination address is normally an IP address. It is the IP address of the device when it is connected
where the data is being sent. Without this address, the hardware transmitting the data to a network.
would not know where to send the data.
Each data packet in the file is given a packet number. The packets of data may not
have all been sent in the correct order, this will depend on the type of transmission
used; you will learn more about this in Sections 2.2 and 2.3. This means that when the
destination device has received all the data packets, it can use the packet number to put
them back into the correct order to recreate the file.
The originators address is also normally an IP address. It is the IP address of the
device from which the data has been originally sent. So, if you send data to another
device, the originator’s address is the address of your device. This address isn’t crucial
to the transmission process, but it does help to trace where data has been sent from in
situations such as illegal activity, or to simply request the original device to resend the
data if an error is detected. KEY WORDS

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?

2.2 Packet switching KEY WORDS


You have learnt that data is broken down into packets to be sent from one device to
another. The process of transmitting these packets is called packet switching. In this packet switching:
process, each packet of data is sent individually from one device to another. There a method of
could be several pathways across a network that the packets could be transmitted. transmitting data
Each data packet could be sent along a different pathway. A router is the device that packets across a
controls which pathway will be used to transmit each packet. You will learn more network. Each data
about how a router does this later in the chapter. Look at the diagram of a network in packet is able to take
Figure 2.2: an individual pathway
across the network.

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.

Figure 2.2: A network

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

2.3 Methods of data transmission


You might think that there is only one method that can be used to transmit data from
one device to another, but there are actually several. You need to understand how data
is transmitted using each of these methods. These include:
• serial
• parallel
• simplex
• half-duplex
• full-duplex. KEY WORDS
Serial and parallel data transmission involve the number of wires that are used to serial: a transmission
transmit the data, and how many bits of data are sent at a time. method where data is
sent one bit at a time
down a single wire,
Serial data transmission parallel: a
In serial data transmission, data is transmitted using a single wire. Each bit of data is transmission method
transmitted one at a time along the single wire. Figure 2.3 shows an example: where data is sent
multiple bits at a time
down multiple wires.

Device A Device B
Each bit of data is transmitted one at a time
along a single wire

Figure 2.3: Serial data transmission

There are several advantages and disadvantages of serial data transmission,


see Table 2.1:

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.

Table 2.1: Advantages/disadvantages of serial data transmission


2 Data transmission

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.

Parallel data transmission


In parallel data transmission, data is transmitted using multiple wires. Multiple bits of
data are transmitted along each wire at the same time. Figure 2.4 shows an example:

Multiple bits of data are transmitted at


the same time, along multiple wires
Figure 2.4: Parallel data transmission

There are several advantages and disadvantages of parallel data transmission,


see Table 2.2:

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.

Table 2.2: Advantages/disadvantages of parallel data transmission

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

Half-duplex data transmission


In half-duplex data transmission, data can be transmitted in both directions between
the devices, but only one direction at a time. Figure 2.7 shows an example:

If data is being transmitted from Device A to


Device B, then data cannot be transmitted
from Device B to Device A, at the same time.

If data is being transmitted from Device B to


Device A, then data cannot be transmitted
from Device A to Device B, at the same time.
Figure 2.7: Half-duplex 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

Use the internet to research how half-duplex data transmission is used to


create a Wi-Fi connection. Why is half-duplex, rather than full-duplex data
Figure 2.8: Wi-Fi uses half­
transmission used in Wi-Fi connections?
duplex data transmission

Full-duplex data transmission


In full-duplex data transmission, data can be transmitted in both directions between
the devices, at the same time. Figure 2.9 shows an example:
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Figure 2.9: Full-duplex data transmission

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

2.4 The universal serial bus (USB)


interface KEY WORDS

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.

Table 2.3: Advantages/disadvantages of the USB interface

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?

2.5 Detecting errors in


data transmission
The transmission of data from one device to another
is often not a perfect process. In the process of
transmitting the data, interference can occur. This
can cause data to be lost, data to be gained and data
to change. This would not be helpful and could also
lead to many issues. If a password wasn’t transmitted
correctly, then that person may not be able to log into
their account. If a person’s address wasn’t transmitted
correctly, they may not get email that needs to be sent to
them. If a person’s details are not transmitted correctly
to a company, they may not get a product or service that
they order. The accuracy of data is often vital, therefore
Figure 2.10: Procedures need to be in place to handle errors
there needs to be a procedure in place to detect any
in data transmission
errors in data so that actions can be taken to correct this.
2 Data transmission

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.

Parity check KEY WORD

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

Checksum KEY WORD


A checksum uses a calculated value to check for errors. A value is calculated from the
checksum: a
data that will be transmitted, before transmission takes place. A method such as
type of error
modulus 11 could be used to calculate the value.
detection method
that performs a
ACTIVITY 2.7 calculation on the
data to create a
Use the internet to find out how the modulus 11 method calculates a value checksum value.
from the data. You do not need to be able to remember how to do this Checksum values
method of calculation for the exam, but it will help you to know how a are compared after
checksum is calculated. transmission to see if
they match.

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?

Echo check KEY WORD

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

Draw a diagram to represent how an echo check detects errors in data.

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

Automatic repeat request (ARQ)


When an error has been detected after the data is transmitted, it is likely that the data
will need to be retransmitted. Either the sending device will need to ask the receiving
device if it received the data correctly, or the receiving device will need to tell the
sending device it did or did not receive the data correctly. This will allow the data to be
retransmitted if necessary. KEY WORDS

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

Draw a diagram to represent how an ARQ system operates using positive


acknowledgement.

In a negative acknowledgement method:


• The sending device transmits the first data packet.
• The receiving device receives the data packet and checks it for errors.
• If the receiving device detects no errors, no further action is taken.
• If the receiving device does detect errors, it will send a negative acknowledgement
back to the sender.
• If the sender receives a negative acknowledgement, it knows this means the data
was received incorrectly, so it can resend the data packet.
• A timeout is set by the sending device when it sends the data. This is just so that
the sending device knows that if it doesn’t receive a negative acknowledgement
back within that set time period, it doesn’t need to be still be waiting for it and can
send the next data packet.

47 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

ACTIVITY 2.10 REFLECTION


Draw a diagram to represent how an ARQ system operates using negative After completing
acknowledgement. activities 2.8, 2.9
and 2.10:
How have you
made sure that your
Check digit diagrams for an echo
You have learnt that errors, such as data loss, data gain and data being changed can check and both ARQ
occur when data is transmitted. You now know that these errors normally occur due methods are correct?
to interference. It is also possible for errors to occur when data entry is performed.
This could be manual data entry, for example, a human typing in a value, or it could be
automatic data entry, for example, a barcode scanner scanning a barcode to obtain the
data stored in the barcode.
A method is necessary to check for errors with data entry and this method is called a
check digit. This is how a check digit operates:
• A check digit value is previously calculated from the data that will be entered at
some point, for example, a barcode number or an ISBN number. This number is KEY WORD
stored with the data.
check digit: a type
• When the data is entered, for example, the barcode is scanned, the check digit is
of error detection
recalculated from the data entered.
method that is
• If the previously calculated check digit and the stored check digit match, used for data entry.
the data entered is correct. A calculation is
• If the previously calculated check digit and the stored check digit do not match, performed on the
data entered to
the data entered is incorrect.
create a value. Check
Although the process is similar, you should not confuse the operation of a check digit values are
digit and a checksum. Make sure that you take the time to understand the difference compared to see if
between the two. the data entered is
correct.
ACTIVITY 2.11

With a partner, discuss and write down the differences between a check digit
and a checksum.

COMPUTER SCIENCE IN CONTEXT

Companies will normally combine several error checking methods to


make sure that the data they transmit and receive is error free. This means
that the data can be checked in several ways to make sure that any error
that could occur is being checked. This is because the data that many
companies use is vital to their business, they want to do everything they
can to make sure that it does not contain any errors caused by transmitting
the data.
2 Data transmission

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.

COMPUTER SCIENCE IN CONTEXT

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.

EXAM-STYLE QUESTIONS COMMAND WORDS

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

See Needs Getting Confident


1 can...
topic more work there to move on
describe the structure of a packet of data. 2.1
describe the process of packet switching. 2.2
describe how data is transmitted using serial and
2.3
parallel data transmission.
describe how data is transmitted using simplex,
2.3
half-duplex and full-duplex data transmission.
choose a suitable data transmission for a given
context and explain why that is the best method of 2.3
data transmission.

52 >
2 Data transmission

CONTINUED

See Needs Getting Confident


■ 1 can... topic more work there to move on

describe how data is transmitted using the


2.4
USB interface.
explain how errors can occur during data
2.5
transmission.
describe how a parity check uses a parity bit to
2.5
detects errors.
describe how a checksum value can be used to
2.5
detect errors.
describe how an echo check compares data to
2.5
detects errors.
describe how an ARQ can monitor if data is
2.5
received correctly.
describe how a check digit can be used to detect
2.5
errors involving data entry.
explain why data may need to be encrypted. 2.6
describe how data is encrypted using symmetric
2.6
encryption.
describe how data is encrypted using asymmetric
2.6
encryption.
X
s?X\

> Chapter 3

Hardware

IN THIS CHAPTER YOU WILL:

• 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

• develop an understanding of virtual memory and how it is created

• 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

CONTINUED KEY WORDS


Discussion questions central processing
unit (CPU): a
1 What kind of feature would you include in a smart refrigerator that you
would find helpful? component in a
computer system that
2 Can you see any problems that might arise as a result of connecting processes data and
devices and the development of the Internet of Things? instructions.

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.

Figure 3.2: A CPU chip


3 Hardware

This is a basic representation of the fetch-decode-execute cycle:

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.

instruction set: a set


of commands that can
ACTIVITY 3.2 be processed by a
certain CPU.
Draw a diagram like the one given in Figure 3.4 to see if you can draw and
label the process for the fetch stage of the cycle.

3.3 The decode stage


The decode stage of the cycle begins when the instruction is received by the CU. The
CU is the unit in the CPU that decodes the instruction. The instruction needs to be
decoded so that the CPU can understand what is required to execute the instruction.
To decode an instruction the CU uses an instruction set. This is a set of all the
commands that are understood and can be processed by the CPU. These commands
are in machine code. Once the instruction is decoded using the instruction set, it can
now be executed.

3.4 The execute stage


The execute stage is when any actions that are required for the instruction are carried
out. This is likely to involve some mathematical and logical calculations. If these kinds
3 Hardware

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

3.5 Factors that can affect the 影响CPU的性能的因素:


1、内核的数量量
performance of a CPU 2、CPU的时钟频率,即主频
The performance of a CPU refers to how quickly the CPU can process an 3、CPU的缓存⼤大⼩小
instruction.
This is important as the more instructions that can be processed in a second, the
higher the performance of the CPU. Users often want a high performing CPU, so they
are not sat waiting and frustrated with their computer because it takes too long to
open a document, for example.
KEY WORDS
There are three main factors that can affect the performance of a CPU and this is the
number of cores it contains, the clock speed and the size of the cache. core: the part of the 内核
CPU that contains all
A single core in a CPU contains all the components that you have learnt that are
the components that
used to perform the fetch-decode-execute cycle. Therefore, if a CPU has one core, it
are used to perform
can perform one fetch-decode-execute cycle at a time. If a CPU has two cores (this
the fetch-decode-
is often called a dual core processor) it can perform two fetch-decode-execute cycles
execute cycle.
at the same time, one on each core. Some CPUs have four cores (this is often called a
quad core processor) and can perform four fetch-decode-execute cycles all at the same clock speed: the 时钟
time. Imagine completing a task: if you can only do one thing at a time to complete number of fetch- 频率
the task, it might take you quite a long time but if you could do four things at once to decode-execute
complete the task, you will complete it much quicker. Therefore, if a CPU has multiple cycles that can be
cores, its performance can be increased. performed in a
Multiple cores also allow a computer to multitask. If it can process more than one second.
instruction at a time, it can perform more than one task at a time. cache: a type of 缓存
storage that is built
into the CPU, to store
the most frequently
used data and
instructions.

Figure 3.5: Multiple cores allow a computer to multitask


3 Hardware

ACTIVITY 3.4

The performance of a CPU is not always increased by the addition of more


cores. Use the internet to find out why the performance may not always be
increased.

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

It is possible to change the speed of a CPU using overclocking.


Use the internet to find out what is meant by overclocking.

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.

COMPUTER SCIENCE IN CONTEXT

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

3.6 Input and output devices


You now know how a computer processes data, but how does it receive that data and KEY WORDS
how do we see the result of the processing? This is possible through the use of input
and output devices. output device: a
An input device is any device that allows data to be entered into a computer system. device that can be
This data could take many forms including text, images and sound. used to obtain the
results of data that
Common examples of input devices are: has been processed.
• barcode scanner input device: a
• digital camera device that allows
data to be entered
• keyboard into a computer
• microphone system.

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

Input device Description of data input Example of use


Barcode scanner It scans a barcode so It is used in a supermarket
that the data stored to get the price of a
in the barcode can be product and as part of a
obtained. stock control system.
Digital camera
Keyboard
Microphone
Optical mouse
QR code scanner
Scanner (2D and 3D)
Touch screen
(resistive, capacitive
and infra-red)

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.

Output device Description of data output Example of use


Actuator It is a component that Can be used in an
outputs an action, often automated system to
a type of movement, that move or turn on/off
causes another device another device,
to operate. e.g. a light.
Digital light processing
(DLP) projector
Inkjet printer
Laser printer
Light emitting diode
(LED) screen
Liquid crystal display
(LCD) projector
Liquid crystal display
(LCD) screen
Speaker
3D printer KEY WORDS
Many computer systems that you encounter in your daily life are automated systems. sensor: a type of
You can learn more about what an automated system is and how they work in input device that is
Chapter 6. used to capture data
A type of input device called a sensor is used in an automated system. The sensor is from its immediate
used to capture different types of data to be processed by the system. The sensor environment.
captures analogue data from its immediate surrounding environment. This data can
automated system:
then be processed and analysed by a computer system. Sensors are normally set to
a system that is
capture data at given time intervals. This could be as constant as every single second or
designed to operate
even fraction of a second. It could also be set to be every minute or at particular times
without the need
of the day. for any human
Table 3.1 shows the different types of sensor that you need to know, a description of intervention.
the type of data that they capture and an example of a how they might be used.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Type of sensor Type of data captured Example of its use


Acoustic This type of sensors measures These sensors are used in many applications that involve
the level of sound in an sound. An acoustic sensor can be used in a security system.
environment. It can be placed near a window and constantly measure the
level of sound. If it captures a reading that shows a sudden
increase in sound, this could mean that the window has
been broken and the building may be at risk.
Accelerometer This type of sensor measures These sensors are used in a wide variety of devices.
acceleration forces. These may Mobile phones use an accelerometer to know which way
be static forces, such as the up it is faced, to automatically turn the screen on and off.
continual force of gravity. They They can be used to monitor for earthquakes, as they can
can also be dynamic forces, such capture the initial vibrations created. They can also be
as those created by movement used in cars to sense when a crash has occurred, so that
and vibrations. airbags can be inflated.
Flow This type of sensor measures the These sensors are often used in factories and sites such
amount of liquid, gas or steam as nuclear power plants. They make sure that the liquid,
that is flowing through or around gas or steam flows at a constant temperature through
a certain environment. an environment, such as a pipe. This makes sure that the
pipes don't rupture and break due to too much flowing
through them.
Gas This type of sensor measures These sensors can be used in people's homes. They can
the presence and concentration be set to measure a certain gas, such as carbon monoxide.
of a gas within the immediate They constantly capture the data in the immediate
atmosphere. atmosphere to see if too much carbon monoxide is
present, which could endanger the health of anyone living
in the home.
Humidity This type of sensor measures These sensors can be used in farming and agriculture to
the level of moisture in the make sure that the air in areas such as greenhouses has
immediate atmosphere. the correct level of moisture to provide the best growing
conditions for the fruits and vegetables. They can also be
used in places such as art galleries, to make sure that the
humidity level is constant. Too much or too little can
ruin paintings.
Infra-red This type of sensor measures These sensors can also be used in security systems. This
infra-red radiation. This type can be done in two different ways. The device containing
of radiation can be emitted the sensor can emit infra-red radiation and when this
in different amounts by both bounces back to the device, the readings can show from
objects and people. the distance it has travelled whether an intruder is present.
It can also operate by capturing the infra-red radiation
emitted by the intruder.
Level This type of sensor measures These sensors can be used in a car to make sure that
whether a substance, such as essential liquids, such as oil and fuel, do not get too low.
a liquid, is at a certain level or
amount.
Light This type of sensor measures These sensors can be used in automatic lighting systems.
the ambient light in a certain Streetlights can be fitted with a light sensor that will
environment. It can also measure allow the light to turn on in the evening, when it
the presence of a direct light, becomes darker.
such as a laser beam.
(continued)
ambient
英 [?æmbi?nt]
adj.
周围环境的;周围的;产生轻松氛围的
3 Hardware

Type of sensor Type of data captured Example of its use


Magnetic field This type of sensor measures the These sensors can be used to count how many cars pass
presence of magnetic field that through a certain area, for example into a car park. The
may be emitted by an object. car will disrupt the Earth's naturally magnetic field as it
passes over the sensor and the data can be captured by
the sensor.
Moisture This type of sensor measures the These sensors can also be used by farming and
amount of water that is present agriculture, to make sure that the fruits and vegetables
in a substance, such as soil. have the best level of water in the soil to help them grow.
PH This type of sensor measures the These sensors can be used by environmental agencies to
pH level of a substance. make sure that local lakes and river are not being polluted.
Pressure This type of sensor measures the These sensors could also be used in a security system.
force of pressure that is applied They can be placed at the base or sides of an opening,
to the sensor or device. This such as a window or a door. When that window or door
could be the pressure created is opened, the pressure will decrease, and the system will
by a solid object, or it could be recognise that an intruder has entered.
created by liquid or gas.
Proximity This type of sensor measures These types of sensors can be used in robots in
how close an object is in manufacturing. They allow the robots to measure how
接近 comparison to the sensor. It does close they are to different objects, when moving
this by emitting electromagnetic around a factory.
这种类型的传感器 radiation or an electromagnetic
测量物体与传感器 field and measures the radiation
的距离。 as it returns to see if there are
any changes.
Temperature This type of sensor measures These types of sensors are used in air conditioning
the temperature of an object systems. They allow the temperature of a room to be kept
or substance by either directly at a certain level.
touching it or capturing
data from the surrounding
environment.

Table 3.1: Different types of sensor

Figure 3.6: An accelerometer can sense a crash so that


airbags inflate Figure 3.7: Streetlights use light sensors
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

3.7 Data storage


You need to store data in a computer system on a constant basis. This might be
temporarily, whilst it is being processed, or on a more permanent basis for future use. KEY WORDS
For these purposes, there are two main categories of storage that exist in a computer,
they are primary storage and secondary storage. primary storage: a
Primary storage is a category of storage that is directly accessed by the CPU. This type of storage that
is directly accessed
means that the CPU has a direct connection to it and that data is sent between the CPU
and the primary storage using this connection. There are two main types of primary by the CPU.
storage, random access memory (RAM) and read only memory (ROM). There are several secondary storage:
characteristics of each type of primary storage, these include those shown in Table 3.2: a type of storage that
is designed to store
Characteristics of RAM Characteristics of ROM data permanently,
It is volatile storage. This mean that until it is deleted by
It is non-volatile. This means that if
it requires power to store data. If the the user.
power is removed, the contents of
power is turned off, the contents of RAM the ROM are retained. Non-volatile ROM (read only
are lost. Volatile storage is sometimes storage is sometimes referred to as memory): a type of
referred to as temporary storage. permanent storage. primary storage that
It stores data and programs that are It stores programs that initially boot stores the start up
currently in use by the computer. the computer, such as the bootstrap instruction for the
and the BIOS. computer.
Its contents are constantly being The contents of ROM are fixed
chanqed as data is processed by and do not normally change. It is
the CPU. possible to reprogram it, but this is a
complex process and only normally
attempted in circumstance when a
computer system is failing to
boot correctly.
It is possible to increase the amount It is not easy to alter the ROM
of RAM a computer has by adding available in a computer system.
further RAM components

Table 3.2: Characteristics of primary storage


3 Hardware

Figure 3.9: Technician changing a computer's RAM Figure 3.10: The inside of a hard disk drive

ACTIVITY 3.6 KEY WORDS

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

Draw a diagram to represent the operation of optical storage.

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

COMPUTER SCIENCE IN CONTEXT

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

3.8 Virtual memory cell: the intersection


of the rows and
So far, all the storage that you have learnt about has been physical storage. This means columns of transistors
that it is an actual component storage unit that you can see and touch. There is another in solid-state storage.
type of storage that can be created in a computer and this is called virtual memory. It is
called virtual memory, as unlike physical storage, it isn’t a component that you can see transistor: a device
or touch. that acts as a switch
or gate for electronic
You may have noticed that this chapter includes the term memory and storage. You signals.
may find these used interchangeably in lots of different resources. There is a slight
difference between the two, but even the defined difference is a little contradictory. control gate: a
component that
Technically, memory is used as a term for short term temporary storage of data, and
controls the flow of
storage is used as a term for the permanent storage of data. For example, RAM stores
electric current.
data temporarily and is a type of memory, random access memory. A hard disk drive
is a type of storage as it stores data permanently, until the user deletes it. This seems a floating gate: a
simple distinction, but ROM is also a type of memory, read only memory, but it stores component that
data permanently too. Therefore, the difference is not completely clear, but it is mostly can store electrical
considered that memory is temporary and storage is permanent. However, you don’t charge.
need to become too worried about picking the correct term!
virtual memory:
Virtual memory is also a type of memory that is created for temporary use. It is created a type of memory
as an extension to RAM. Sometimes, a computer is given a large number of tasks to that can be used as
complete at a given time. This means that it will need a lot of data to do this. All this an extension to the
data will need to be sent to the RAM to be ready to be processed. A computer system RAM.
only has a set amount of RAM, so what happens when this RAM becomes full? It
needs some extra help! This is where virtual memory can help. page: a unit of data.
Virtual memory is created in a computer system with a hard drive component.
A section of that hard drive is partitioned off and is effectively an extra bit for RAM
instead. When the RAM gets full, the computer system can transfer some data to
the virtual memory to be held there until it is needed. It will choose to send data that
isn’t as immediately required as other data. The data that is transferred is collected in
a structure called a page. These pages of data are transferred to the virtual memory
to make sure there is enough room in the RAM for the immediate data that is being
processed. Once the pages of data are required again, they can be sent back to the
RAM to be processed. The diagram in Figure 3.13 shows the process:
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

3.9 Cloud storage KEY WORDS

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!

COMPUTER SCIENCE IN CONTEXT

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

Storing data in the cloud Storing data locally


You do not have to pay for the hardware to store the You will need to purchase the hardware to store your
data. data. These costs can be high if you have a lot of data
to store.
You do not have the responsibility for the security of You will need to make sure that your data storage is
the hardware that stores the data. However, you are well maintained and that it is regularly checked and
relying on a third party making sure that your data updated for security issues.
is safe. If they do not do this correctly, they may put
your data at risk.
You can access the data and resources using different You do not need an internet connection to access
devices from anywhere that you have an internet your data, therefore it is available at all times that you
connection. However, if your connection fails or is not have local access to that data.
available, you will not be able to access your data.
If your connection is slow, this can also mean that
accessing your data is slow.
You can increase and decrease the amount of storage You might have redundant hardware, that you have
space you need very easily, when you need to. paid for, that isn't used as the amount of data that you
need to store has decreased.
Table 3.3: Comparisons of storing data in the cloud and locally

ACTIVITY 3.10 KEY WORDS


Do you store any data in cloud storage? If so, do you ever worry about network: computers
doing this? Discuss with a partner about the advantages and disadvantages and devices that are
of storing data in the cloud, compared to local storage. Reach a conclusion joined together using
about whether you think the risk is worth it. cables or wireless
technology.
As part of your discussion research at least one more advantage and one more
disadvantage and make note of these. You can then share your thoughts from network interface
your discussion with the rest of your class and see who thinks cloud or local card (NIC): the
storage is better, and why. component in a
computer that is used
to connect it to a
network.
3.10 Network hardware router: a network
At the beginning of this chapter, you learnt about the hardware required within a component that
examines a data
computer and local to a computer that enable the temporary and permanent storage of
data. You have now learnt that data can be stored remotely, in a cloud storage system, packet to obtain its
destination address
but that an internet connection is required to access the data stored in the cloud.
and then forwards
The hardware required for this connection creates a network. You will now learn what
the packet to this
hardware is required to create a connection to other devices and the internet.
address.
When two or more devices are connected, this is called a network. Some basic hardware
devices are required to create a network, these are a network interface card (NIC), transmission media:
a router and you may need some transmission media. the cables that are
used to transfer data
in a network.
3 Hardware

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

Figure 3.15: A network interface card (NIC) KEY WORD

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.

Figure 3.16: A home 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

1 A student has a computer that has a Von Neumann architecture.


The CPU in the computer performs the fetch-decode-execute cycle
to process data and instructions. COMMAND WORDS

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.

To count the number of competitors


who finish a race.
To detect a person who is approaching
an automatic door system.

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

See Needs Getting Confident


1 can... there to move on
topic more work
explain why a computer system needs a CPU. 3.1
describe the role of each component in a CPU. 3.1
explain how data is fetched into the CPU, including
3.2
the components used.
explain how data is decoded and executed by the
3.3
CPU, including the components used.
explain what an embedded system is and identify
3.1
examples of where one might be used.
describe the purpose of an input device and provide
3.6
examples.
describe the purpose of an output device and
3.6
provide examples.
identify the different types of data that is captured
3.6
by different sensors.
choose a suitable sensor for a given scenario. 3.6
give characteristics of primary data and explain the
3.7
role of RAM and ROM.
give characteristics of secondary storage. 3.7
describe how data is written to and read from
3.7
magnetic storage.
describe how data is written to and read from
3.7
optical storage.
describe how data is written to and read from solid
3.7
state storage.
explain how virtual memory is created and when it is
3.8
needed in a computer system.
describe what cloud storage is and how it is used. 3.9
explain the advantages and disadvantages of storing
3.9
data in the cloud, rather than storing it locally.
> Chapter 4

Software

IN THIS CHAPTER YOU WILL:

explore the different types of software that run on computers


understand the role and function of an operating system in a computer
explore the different types of programming language
describe and use the software used to write a computer program
learn about the software used to translate program code.
4 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?

DEVELOPMENT OF PROGRAMMING LANGUAGES

The very first programmable digital computer was


developed during World War 2 in the United States
of America; the Electronic Numerical Integrator
and Computer (ENIAC). Its purpose was to perform
calculations faster than a human. It allowed the
storage of a 10-digit number and could perform
addition and subtraction. This computer could only
perform the task it was designed to perform.
From this, assembly language was created that
allowed a user to write a program that could then be
converted into binary code (see binary interpretations
in Chapter 1). These languages required the user to
state which memory locations were being accessed
(for example, store the data in memory location 3,
access the data from memory location 4. This takes Figure 4.1: The ENIAC
a lot of expertise to write a long program). Each
program had to be written to the assembly language
of the computer it was to run on. If you wanted the
same program on two computers from different
manufacturers, or different versions, then you would
have to write the program again in that computer's
language.
Fortran was the first significant high-level
programming language first released in 1957 by IBM.
This was different from previous languages because it
was the first language that did not require the user to
write in assembly language. It used more user-friendly
commands that were then converted into code that
could be run. Another benefit of this new language
was that it was not machine-dependent, you could Figure 4.2: Close-up of an original computer similar to
write a program on one computer, and run it on an a Turing machine
entirely different one.
Discussion questions
1 Can you think of any more problems that can arise from only writing programs in assembly language?
2 How has the development of programming languages impacted the use of computers?
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

4.1 Types of software KEY WORDS

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.

4.2 Operating system


An operating system (OS) is an example of system software, you may be familiar with
brands such as Windows, Linux and macOS for PCs and laptops. Other computers also
have operating systems, for example, a mobile phone may have an Android OS, or iOS.
The overall purpose of these operating systems is to allow you, the user, to interact
with the hardware.
The OS has many different roles that are described in the following sections.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

COMPUTER SCIENCE IN CONTEXT

Have you every spoken a command to a computer? For example, Amazon's


Alexa, Microsoft's Cortana or Apple's Siri? These are examples of natural
language interfaces. You do not have to speak specific commands, the
programs analyse the words you have said and decide on a response. There is
more about how this is done in Chapter 6.

Managing files KEY WORD


A user will use application software to create files. The OS allows the creation of
peripheral: a
directories that the files can be stored within. It also allows the user to move files, copy
hardware device,
files, delete files, name and rename files, plus many other actions such as sorting by date.
used to input, store
or output data from a
computer, that is not
Managing peripherals and drivers directly part of the
A computer cannot be used without input and output devices. These are called computer itself.
peripherals. Anyone can build a peripheral, and it will be programmed by the person
4 Software

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.

Providing a platform for running applications


Application software needs to run on a computer. The software could be written by
anyone using any language. The OS allows the application software to run on the
computer by fetching instructions from it and executing them.

Managing user accounts


Most computers need a user to set up an account. This can include preferences, as well
as a username and password (text and/or biometric). The OS allows a user to set-up an
account, keeps the data separate for multiple accounts, and restricts the access by using
the password.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

An interrupt has a priority level. A high-priority interrupt needs the attention


quickly, for example, hardware failure. A low-priority interrupt needs the KEY WORDS
processor but it’s not urgent, for example, data input. This is managed by the
interrupt handler (IH). interrupt handler
(IH): a program that
When an interrupt is generated it is put in a queue according to its priority.
organises interrupts
The sequence of activities is:
into an order based
• When the processor finishes its current fetch-decode-execute cycle (or before the upon priorities.
starting the next FDE cycle), it checks the interrupt queue.
interrupt service
• It checks whether there is an interrupt with a higher priority than the current task routine (ISR):
it is processing. a program that
• If it is, it: retrieves an interrupt
and performs the
• Stores the current process and fetches the interrupt. required action(s).
• Checks the source of the interrupt.
• Calls the relevant interrupt service routine (1SR . This is a sequence of
instructions that handle the interrupt.
• When finished the stored process is returned to memory or another higher-
priority interrupt is fetched.
• If it isn’t, it runs another FDE cycle.

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

4.4 Types of programming language


When you are writing computer programs you will make use of specific software that
allows you to write, edit, test and run the programs you write. KEY WORDS

Programming languages can be categorised as high-level and low-level. high-level


language: a type
of programming
High-level language that
uses English-like
A high-level language uses human-language style words. These could be English words commands.
that we recognise and use day-to-day. For example, if, while, output, print,
input; as people we understand these, but they are also high-level language instructions. low-level language:
You will be learning to use a high-level language, for example, Python, Java and VB.NET. a language closer
to the machine's
Here are some examples of high-level language statements:
language, this
Python: could be assembly
language or binary
print("This is a high-level language statement")
code.
VB.NET: portable: a program
Dim x as integer that can be run on
x = Console.readline() different types and
manufacturers of
Java: computers.
numl = 10;
num2 = 5;
num3 = numl + num2;
A program that is written in a high-level language is considered portable; you can write
a program on one computer, and run it on a different computer.

Figure 4.9: Code written in a high-level language


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Low-level KEY WORDS


There are two main types of low-level language, machine code and assembly language.
machine code:
A computer executes machine code, this is in binary (Is and Os). If you write a binary code, an
program in a high-level language it needs to be converted into machine code before it example of a low-
can executed. Different computers may have different machine code (for example, level language.
depending on the manufacturer). This means that machine code is non portable; you
can write a program in machine code and it may not run on a different computer. assembly language:
code written in
An example of machine code is: 01100110 mnemonics that
Assembly language is an in-between stage. It uses mnemonics to represent code, for allows direct
example, to store data in a memory location it may use the mneumonic STO. This is a manipulation of the
mid-way stage. Each high-level language statement is converted into assembly language hardware. It must be
instructions, which are then converted into machine code. converted into binary
code to run.
non portable:
a program that
cannot be run on
different types and
manufacturers of
computers.
mnemonic:
instruction code
used in assembly
language.

Figure 4.10: Machine code

Examples of assembly language are:


LDD count
ADD 1
STO count
In assembly language, the program has to state which memory locations are being
used. In the previous example, LDD count, the count is the memory location.
One high-level language statement may need several assembly language instructions.
The previous three assembly language instructions are the same as the single high-level
language count = count + 1.

ACTIVITY 4.2

Assembly language instructions are split into operators and operands.


Find out what an operator and an operand is. Find some examples of each.
4 Software

Choosing a language
High- and low-level languages have their own benefits and drawbacks. Some of these
are shown in Table 4.2.

High-level language Low-level language


Easier for users (humans) to understand, More difficult for users to understand, read, write and amend.
read, write, amend.
Easier for users (humans) to debug code. Harder for users to debug code.
Portable, machine independent. Not portable, machine dependent.
It must be converted into a low-level Machine code does not need converting.
language before it can be run.
Assembly language must be assembled before execution,
but this is faster than from a high-level language.
One statement can represent many low- Several instructions are needed for each high-level language
level instructions. statement.
Cannot directly manipulate the hardware. Can directly manipulate the hardware, e.g. writing to specific
memory locations. This can make the program more efficient
in terms of speed and memory usage.

Table 4.2: Benefits and drawbacks of high- and low-level languages

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.

Program code High-level, assembly or machine code


LDX 10
INC
STO 10
valuel = input("Enter value")
print(valuel + 1)
01100011
11000011
10101010
KEY WORD
9 Harry needs to write a utility program that uses as little memory as possible.
Give the most appropriate type of programming language Harry should use and translator: a type
justify your choice. of software that
converts code written
in one programming
4.5 Translators language into
another, usually a
In Section 4.4 you learnt that high-level language programs, and assembly language
high-level language
programs, need to be converted to machine code to be executed. This is done using
into a low-level
a translator.
language.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Assembler KEY WORDS


If you have a program written in assembly language, then an assembler is used to
assembler: converts
convert the instructions into machine code for the processor the code is being run on.
assembly language
into machine code.
Interpreters and compilers interpreter: a
translator that
If you have written a program in a high-level language then you can use an interpreter
converts a high-level
or a compiler to translate the instructions.
language into a
An interpreter: low-level language.
• reads one line of the high-level language code It checks one line
of code and then
• checks that it is syntactically correct: executes it before
• if it is not, it stops and reports an error to the user checking the next,

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

Table 4.3: Comparison of interpreters and compilers

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

SKILLS FOCUS 4.1

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.

Environment (IDE) auto-correction:


a feature of an
When you write a computer program you will most likely use an Integrated editor that identifies
Development Environment (IDE). This is a piece of software that includes an editor for spelling errors and
you to enter and amend your code. This editor may include other features such as: changes them.
• Auto-completion; you start typing a command and it suggests options for you to prettyprint: a feature
select the correct one. of an editor that
• Auto-correction; if you spell a command incorrect it changes it to what you meant changes the colour of
to type. text, for example, to
highlight key words.
• Prettyprint; this changes the colour of words, e.g. commands and identifiers.
This helps you spot key terms and whether you have entered them correctly or not. run-time
environment: a
• Block minimising; you can make sections of code, e.g. procedures, minimised so
feature of an IDE that
there is less code to read through. allows a program to
The IDE will also include the relevant translator, that you can select to translate the be run and lets the
code. It will also provide a run-time environment; this is where the outputs from the user interact with the
executed code is displayed, it can be a command line or GUI depending on your program.
language and the code entered.
4 Software

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

Software is created using programming languages.


Two types of software are application and system software.
The Operating System performs many functions including memory management, handling interrupts
and providing an interface.
An interrupt is a signal sent to the processor to get its attention.
A high-level language uses English-like terms that need translating before it can run and a low-level
language is assembly or machine code.
Assembly language is turned into machine code using an assembler.
High-level languages are turned into a low-level language using a compiler or interpreter.
An IDE helps the user write, test and run program code.

EXAM-STYLE QUESTIONS

1 Tick one box in each row to identify if the software is an example of system
software or application software.

System software Application software


Word processor
Defragmentation
Operating System
Image manipulation
System clean-up
Database
Web browser
Spreadsheet COMMAND WORDS

2 State what is meant by an interrupt. [2] state: express in


3 Describe the difference between system software and application clear terms.
software using an example of each. [3] describe: state the
4 An operating system performs memory management. points of a topic /
a Describe memory management. [3] give characteristics
b Give two other functions of an operating system. [2] and main features,
[Total: 5] give: produce an
5 A printer sends an interrupt to the computer to say that it is out of paper. answer from a given
source or recall /
Describe the stages involved in the processor handling the interrupt. [5]
memory.
6 The following sentence describes the requirements for application
software. Fill in the missing gaps.
The application software runs on the.......................................
............................................. this runs on the firmware, and it is loaded
by the................................................. [2]
4 Software

CONTINUED

7 Qui is writing a program using a high-level language.


COMMAND WORD
a Describe what is meant by low-level language, and high-level language. [4]
b Explain why a person will usually write a program using a explain: set out
high-level language and not a low-level language. [3] purposes or
c Give one reason why a person might prefer to write a program using reasons / make
a low-level language. [1 ] the relationships
between things
d Qui needs to use a translator while writing the program.
evident / provide
State what type of translator Qui should use, justify your choice. [3] why and/or how and
e Qui uses the translator in his Integrated Development support with relevant
Environment (IDE). evidence.
Describe the other features of an IDE that Qui can use to write
and test his program. [6]
[Total: 17]
8 Explain the role of the operating system in a computer. [8]

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

See Needs Getting Confident


I can...
topic more work there to move on
describe the difference between application and
4.1
system software.
describe the role and basic functions of an
4.2
operating system.
describe how hardware, firmware and an operating
4.2
system are required to run application software.
describe the role and operation of interrupts. 4.3
describe the characteristics, advantages and
4.4
disadvantages, of high-level and low-level languages.
describe the use of an assembler, compiler and
4.5
interpreter.
describe the advantages and disadvantages of a
4.5
compiler and an interpreter.
describe the use of, and features of, an IDE. 4.6
> Chapter 5

The internet
and its uses

IN THIS CHAPTER YOU WILL:

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.

Figure 5.1: A parent helping a child to safely access the internet

THE EFFECTS OF MALWARE

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?

5.1 The internet and the world KEY WORDS

wide web internet: a very large


global network that
The internet and the world wide web: aren’t they the same thing? Although the terms allows users to access
are used interchangeably, they aren’t the same thing. Bonus points if you knew that the world wide web.
already! The internet is an infrastructure. This means it is all the components and cables
infrastructure: the
that are used to connect one device to another. Another way that the internet can be
physical structure,
described is that it is one huge network. More specifically, it is a type of network called
such as all the
a wide area network (WAN). This is a type of network that spans a large geographic
components and
area, in this case the whole world! The internet is an incredible structure if you think
cables, that are used
that homes and businesses all over the world are able to use it to connect to each other.
to connect devices,
Millions and millions of people use this huge infrastructure.
network: computers
and devices that are
joined together using
cables or wireless
technology.
world wide web:
the collection of all
the web pages and
websites that have
been made available,
website: a collection
of web pages,
normally about a
related topic or
purpose.
Figure 5.3: The internet connects millions of people web page: a single
page within a
The world wide web is the collective term for all the websites and web pages that are website.
available. The world wide web is accessed by using the internet.
5 The internet and its uses

COMPUTER SCIENCE IN CONTEXT

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.

5.2 Requesting and retrieving protocol: a set of


rules for transmitting
data.
web pages domain name: a
A URL is a fundamental component of the world wide web. Each website and web
specific part of a URL
page on the world wide web has a text based address. This address is called a URL.
that contains the
To access the web page, a user types the URL into the address bar of a web browser.
unique name for the
A URL has three main components: the protocol, the domain name and the web page web server.
or file name.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Figure 5.5 shows an example of a URL: https://www. cambridge.org /education


1 Y
KEY WORDS
There is a whole process involved in
requesting and retrieving web pages that protocol domain web page domain name server
you need to understand, the URL and its name name (DNS): a special
three components are fundamental to this Figure 5.5: The components of a URL server that contains a
process. So how is a web page requested database of domain
and retrieved by our computers? names and their
corresponding IP
To start the process, the user opens their web browser and types the URL into the
address.
address bar. The web browser then sends the URL for the website to the domain name
server (DNS). The DNS is a special kind of server that stores all the different domain web server: a
names (part of the URL shown in Figure 5.5) along with their equivalent IP address. network component
The DNS looks through its database of domain names to find the equivalent IP where the web pages
address. As you can imagine, there are billions of websites, so these are not all stored for a website are
on a single DNS. Therefore, the first DNS will search its database and if it doesn’t stored.
find the domain name, it sends it to the next DNS. This will happen until the domain
name is found, or if it is not found, a message is sent back to the web browser to say hypertext transfer
that the website is not found. When the DNS find the domain name, it sends the protocol (HTTP): a
equivalent IP address back to the web browser - the IP address of the web server that protocol that is used
stores the website. This process is summarised in Figure 5.6. for the transmission
of web pages and
DNS searches related data across
for domain the internet.
Web browser
name to find
sends URL to hypertext markup
URL its equivalent
DNS language (HTML):
IP address a scripting (web
authoring) language
that is used to create
web pages.
cascading style
sheet (CSS): a
scripting language
IP address that is used to create
a presentation
template for a web
Figure 5.6: A web browser requests an IP address from a DNS page. It includes
what kind of font
The web browser receives the IP address for the website from the DNS. It now knows and colour text
where to find the website. The web browser sends a request to the web server to ask will appear on the
for the web page from the website. It uses a protocol called the hypertext transfer webpage.
protocol (HTTP) to send the request to the web server. Each web page is created active script: this is
using hypertext markup language (HTML), cascading style sheets (CSS) and may the script that is used
include active script such as JavaScript. When the web server receives a request for a to produce any of the
web page, it sends the data for the website, including the HTML, CSS and any active interactive elements
script, back to the web browser using the HTTP The web browser then renders the of a web page.
HTML and CSS and runs any active script to display the web page. This process is
summarised in Figure 5.7.
5 The internet and its uses

Web browser uses Web server sends


the IP address to the data, including
send a request to HTML, CSS and
the web server to active script to the
obtain the data for web browser
the web page
Request for web page

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

This process is summarised in Figure 5.8.

Web browser asks


Web server sends
the web server to
send its digital its digital certificate
Request for digital certificate to the web browser
certificate

Encrypted data transmission

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.

5.3 The purpose of a web browser


You may have noticed that the web browser has a key role in the requesting and retrieving
of web pages. The main purpose of a web browser is that it is a software application that
allows you to access information that is available on the world wide web. As you learnt
previously, it does this by requesting the HTML files and other data required to create the
web page, then renders this data so that you can view the web page.
One thing to note about a web browser is that some people confuse it with a
search engine. This is because some web browser software development companies also
5 The internet and its uses

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

Google address bar: the


section of a web
browser where you
type the web page
address.
user history: a record
made on your web
browser of all the
Figure 5.9: Example of a search engine Figure 5.10: Examples of web browsers web pages that you
have visited.

ACTIVITY 5.3 bookmark: a link that


can be created to
Can you think of two more examples of a web browser? Use the internet to allow you to quickly
check if you are correct. find a web page
again.

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

The main features are shown in Figure 5.11.

Navigation buttons Tab Address bar

Main window: Settings: This is


This is where where you will
you will see the find your history
HTML rendered and bookmarks
and the web and favourites
page displayed (you may also
find these on a
toolbar below
the address bar)

Figure 5.11: The main features of a web browser

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.

User visits the web page that


is stored on the web server

Session cookies are


temporarily stored by
user's web browser
until the browser is
closed and the session
ends. The cookies are
then deleted.

Session cookies are sent from


web server to user's web browser
Figure 5.13: Session cookies

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

User visits the web page that


is stored on the web server

Persistent cookies
are permanently
stored by user's
web browser until
the user or the
web browser
deletes them.

Persistent cookies are sent from


web server to user's web browser
Figure 5.14: Persistent cookies

Internet users have mixed feelings about cookies.


This is because they can have a very useful role
but can also be used for improper activities.
Cookies do build up an online profile about
your details and preferences. Some people feel
this is an invasion of their privacy. Other people
also believe that this data can be gathered to
build a profile about you and add to the risk of
your identity being stolen. If you are worried
about this being a possibility, you can limit the
use of cookies in your online activity by
changing the settings for your web browser.

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?

COMPUTER SCIENCE IN CONTEXT

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

5.4 Digital currency KEY WORD


When you pay for products and services using the internet, you will normally use a
digital currency. A digital currency is one that exists electronically (see Figure 5.16). digital currency: a
It is a method of payment that is similar to paying with coins and bank notes. currency that exists
However, rather than exchanging physical bank notes and coins to make the payment, electronically rather
the currency is exchanged digitally using computers. There are several different forms than physically.
of digital currency, the most popular are payments using credit cards, mobile phones
and smart watches. The most common of these is using credit cards when making
payments using the internet.
When the data about the payment with the digital currency is sent from one computer
to another, it is encrypted to keep it secure. The method of encryption used is what
you learnt about previously, in Section 5.2, using the HTTPS protocol. The payment
details for the use of a digital currency can be stored in a persistent cookie. That means
that each time you visit the website to buy a product, your payment details will be
automatically entered so you don’t need to type them in each time.

Figure 5.16: Digital currency exists electronically and can be sent between computers

One type of digital currency that


you may have heard of is Bitcoin.
This type of digital currency is KEY WORDS
more specifically known as a
cryptocurrency. The banks that cryptocurrency:
we use to manage our money on a a type of digital
daily basis are called centralised currency that
systems. This means that there is uses encryption
an authority at the centre procedures.
managing the process in which
they are used. In this case, the blockchain: a
bank is the authority. A method that is
cryptocurrency is a decentralised used to track all the
Figure 5.17: A cryptocurrency is a digital currency transactions made
system, this means that there is
that is managed by a decentralised system with a cryptocurrency.
no central authority, like a bank,
managing the process of digital ledger: a
payments. Payments are also encrypted using this type of currency. As there is no database that is a list
central authority managing the system of payments with this type of digital currency, of all the transactions
a different system called blockchain is used to keep track of the payments. recorded by the use
In its most basic form, blockchain is a list of all the records made with the digital of blockchain.
currency. This is called a digital ledger (Figure 5.18). Each time a payment is made with
the digital currency, a record is added to the ledger that includes a digital signature
with the time and date that the payment is made. In blockchaining, once these records
are added to the digital ledger, they cannot be changed. Data that is stored in a digital
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

Blockchain Digital Ledger

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

COMPUTER SCIENCE IN CONTEXT

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?

5.5 Cyber security


Whilst the internet and the world wide web can be a very fun and interesting place, it
does also have some issues and threats that you definitely need to be aware of.
You need to know how these cyber threats are created, what the motivation is behind
those who use them, and what kind of security solution you can put in place to try and
prevent them from happening. One thing to note is that each security solution may not KEY WORDS
be a complete prevention, sometimes it is better to have several solutions in place. Also,
perpetrators are always looking to develop ways to beat security solutions, so no perpetrator: a
solution will be 100% effective in preventing an attack. However, if you don’t have any person that carries
security solutions in place, you are putting your personal data at a far greater risk of out an illegal or
these cyber threats. So, what are the cyber threats that you need to know? immoral action,
brute-force attack:
Brute-force attack a type of cyber
threat that involves
You may have heard someone being described as a brute person. This normally means repeatedly inputting
people think they are strong and forceful. This is exactly what a brute-force attack is a password until the
on your computer, a strong and forceful attack. Imagine that someone is banging on correct one is found,
a locked door, pushing and shoving it in every way that they can, until the door gives to try and break into
way and opens. In a brute-force attack, a perpetrator tries to break into your computer an account or device
or account. They do this by repeatedly entering different password combinations until
they manage to enter the correct one. They may try to do this manually, by typing
in each password combination themselves. They could also do this by developing a
5 The internet and its uses

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.

Data interception KEY WORDS


Billions of pieces of data are sent across the large network that is the internet on a data packet: a unit
daily basis. A lot of this data is people sending their personal data to do things like buy of data that is used to
products and services, and log into their online accounts. Perpetrators would very transmit data across a
much like to get hold of their information so that they can use it in criminal activity, network.
such as identity theft and fraud. A way that they will try and do this is by intercepting
data packets as they are transmitted across the network from one device to another. packet sniffer: a
This is often done by using a piece of software called a packet sniffer, this is normally piece of software that
installed onto a piece of hardware that the packets will pass through, for example, a is used to examine
router. This software is used to examine packets of data that are sent across a network the contents in a
to see if they contain data that looks useful. If they do, the software will report the packet of data.
useful data packets it has found back to the perpetrator.
5 The internet and its uses

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.

Figure 5.19: If your data is intercepted by someone, will it be encrypted?


Check if the URL uses HTTPS

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

Figure 5.20: A botnet can cause a DDoS attack

In summary:

What happens? Malware is sent to lots of computers to turn them into


bots to create a botnet. The perpetrator then uses
the botnet to send many requests to a web server, all
at the same time.
What is the aim? The aim is to cause the web server to crash. The
perpetrator may be doing this to demand money for
it to stop, or as an act of revenge or activism.
What security solutions The company can use a proxy server to act as a
can be used? barrier that filters requests to the web server. You can
scan your computer with anti-malware on a regular
basis to try and prevent it being used as a bot.

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

Hacking KEY WORDS


Hacking is the act of trying to gain unauthorised access to data. A perpetrator that
hacking: the act of
does this is known as a hacker. They can do this by using a range of technical skills
gaining unauthorised
that allow them to break into a computer or a network. This can be done by going
access to data. This
through methods such as a brute-force attack (this is sometimes known as cracking) or
is normally done to
by exploiting vulnerabilities in a computer or a network, which are areas that the
steal or corrupt the
hacker can identify that lack the protection of security solutions.
data.
Hackers will gain access to a system for several reasons. This could be to steal your
hacker: the
data to try and steal your identity, as an act of revenge, to corrupt your data or to leak
confidential data about a company or project, or an act of activism. name given to a
perpetrator that
The main way that you can stop your computer being hacked is to have as many security carries out an act of
solutions in place as possible. One of the main security solutions that can be used is hacking.
a firewall. A firewall is a barrier that can be used between your data and the rest of a
network. It can be software based or hardware based. Any data that is sent into and out firewall: a cyber
of your computer is examined by the firewall. Rules can be set for this data by giving your security method
firewall a set of criteria to examine the data against. The data that is sent through the that is used to
firewall is compared to the criteria. The firewall can be set to accept the data and allow examine incoming
it to pass through the firewall, or reject the data and stop it from passing through the and outgoing traffic
firewall, depending on whether it does or does not meet the criteria. This added security from a computer or
solution may help identify data that a hacker has sent that looks malicious and reject this network.
data to stop the hacker getting into the computer or network. A firewall can also be used port: an entry point
to close certain ports to a network. A hacker may look to find a vulnerability, such as an into a computer or
open port, to get into a network. A firewall can be set to close as many ports as it can that network.
are not being used, to try and prevent a hacker exploiting an open port to gain access.
One kind of vulnerability that hackers may try to exploit is out of date software.
Sometimes, a software company may find that they have an issue
with their software that could allow a hacker to gain unauthorised
access. If you have downloaded this software, you have also created
this vulnerability on your computer. As software companies become
aware of these issues, they develop their software and issue updates
to protect against hackers. It is therefore vital that you update your
software on a regular basis when software updates are released. This
helps limit any vulnerabilities you have on your computer that a
hacker can exploit. A way to make sure that your software is always
up to date is to set your software to automatically update. This
means that as soon as a software update is released, your computer
will automatically download the update and you don’t need to
remember to do this.
You can also password protect all your data with strong or biometric
passwords to help stop a hacker gaining unauthorised access to your Figure 5.21: Good security will protect
data. And you can add two-step verification to all your accounts.
computers against hackers
In summary:

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

Questions KEY WORDS


9 What is a hacker? virus: a software
10 How can you prevent a hacker gaining access to your data? based cyber threat
that replicates
itself with the aim
Malware of corrupting data
Malware is a term used to describe any malicious software that is designed to disrupt or filling up the
your computer or data. There are several types of malicious software that you need to available memory
know about: virus, worm, trojan horse, spyware, adware and ransomware. See Table 5.1. space in a computer,
causing it to crash,
Malware Description worm: a software
Virus This is a computer program that is downloaded onto your hard based cyber threat
drive. Once it has downloaded it replicates itself and corrupts that replicates itself
your stored data or uses up all the available memory in your across a network
computer, causing it to slow down and crash. using vulnerabilities
Worm This is a computer program that also replicates itself. It has that it finds, with the
a different aim to a virus though. It looks to find vulnerability aim of clogging up
holes in a network to use to replicate itself. In doing this it will the bandwidth.
clog up the bandwidth of a network and slow the trojan horse: a
network down. software based cyber
Spyware This is a computer program that is downloaded onto your hard threat that is used
drive and is designed to record your actions on your computer. to disguise other
A common form of spyware is a keylogger. This records all malware to try and
the key presses that a you carry out on your keyboard. This smuggle it into a
data is then sent to the perpetrator where it can be analysed computer or network,
to identify patterns in your data. Patterns in your data could
reveal personal data such as your passwords. This can allow spyware: a software
access to your online accounts for fraud and identity theft. based cyber threat
that spies on a user's
Trojan horse This is a computer program that is used to disguise other action whilst using
malware. It is designed to look like a harmless piece of a computer, such
software, such as an application or game, but it contains other as logging their key
malware such as a virus or spyware. Once the trojan horse presses.
is downloaded onto your hard drive, it releases the other
malware that it contains. adware: a software
Adware This is a computer program that is designed to automatically based cyber issue
created pop up and banner adverts when you are online. that automatically
These adverts are often unwanted and can be irritating and creates popup
frustrating. The adware creators are given money by the advertisements.
companies that appear in the advertisements when you click ransomware: a
on them. software based cyber
Ransomware This is a computer program that is downloaded onto your hard threat that encrypts
drive or other hardware. It is designed to encrypt your data a user's data to stop
and stop you from gaining access to it. The creators of the them gaining access
ransomware will demand a ransom (a set amount of money) for to it until a ransom
the data to be decrypted. They will often threaten to release (money) is paid.
and leak all your stored data if the ransom is not paid.
Table 5.1: Different types of malware
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

Figure 5.23: Malware can be sent to a computer via email


5 The internet and its uses

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

Figure 5.25: An onscreen virtual keyboard

In summary:

What happens? Malicious software is downloaded onto your


computer or network.
What is the aim? Malicious software is used to corrupt your data, gain
access to your data or damage your hardware.
What security solutions Anti-malware software, including anti-virus and
can be used? anti-spyware, a firewall, exercising caution when
downloading software and creating a backup of data.

Pharming KEY WORDS

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.

Any personal data


Perpetrator

Figure 5.26: Pharming is a cyber threat where fake websites are used to steal data

In summary:

What happens? Malicious software is downloaded onto your hard drive


that will redirect you to a fake web page when you
input the genuine URL.
What is the aim? KEY WORD
To get your personal data to commit criminal activity
such as stealing your money, identity theft or fraud. phishing: a type of
What security solutions Anti-malware software, visually checking the web page cyber threat that
can be used? and only downloading data from trusted sources. involves sending a
user a fake email
that is designed
Question to look genuine. It
will encourage the
11 What can you do to prevent a perpetrator getting your personal data user to provide their
through pharming? personal data either
by clicking a link to
a fake website, or by
Phishing responding to the
Phishing is also used by perpetrators to try and get your personal data, such as your email.
username and password for your online accounts. They can then log into the account,
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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 KEY WORD

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

access level: the


amount of direct
access a user is
given to data and
resources. This could
Figure 5.29: Employees can be contacted by perpetrators pretending to be colleagues
be set to be only
certain sections of a
whole collection of
ACTIVITY 5.8
data and resources.
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.
REFLECTION

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

EXAM-STYLE QUESTIONS COMMAND WORDS


1 State the name given to the infrastructure that allows a user to access state: express in
the world wide web. [1] clear terms.
2 A URL is the name given to the text based address for a web page.
identify: name I
The web page name is one part that is used to create the URL.
select / recognise
a Identify the name for one other part of a URL. [1 ]
b State the name of the hardware that finds the corresponding
IP address for a URL. [1 ]
[Total: 2]
3 The given paragraph describes how a web page is located and
retrieved to be displayed on a user’s device. Complete the missing
words in the paragraph. [5]
The user types the URL into the address bar in the
This is sent to the where the corresponding
IP address is found. The IP address is sent to the web browser. The web
browser uses the IP address to send a request to the
where the web pages are stored using the
protocol. The web pages are sent to the web browser. The web browser
renders the to display the web page.
4 One function of a web browser is to store cookies.
a Identify two other functions of a web browser. [2]
b State the name of the type of cookie that is stored in a
computer until it is deleted by the user or by the web browser
when it expires. [1 ]
COMMAND WORDS
[Total: 3]
5 Give one benefit of using blockchain to track a digital currency. [1 ] give: produce an
6 A website company is worried about a distributed denial of service answer from a given
(DDoS) attack being carried out on their web server. source or recall I
memory.
a State the name of a security solution that can be used to help
prevent a DDoS attack taking place. [1 ] describe: state the
b Ina DDoS attack, a perpetrator creates a botnet. points of a topic /
Describe how the botnet is created by the perpetrator. [3] give characteristics
and main features.
[Total: 4]
7 Draw a diagram to show how data interception is carried out. [3]
5 The internet and its uses

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.

This is software that can be used to scan a


computer for malicious files.

This can be hardware or software based and it


examines traffic incoming and outgoing from a COMMAND WORD
computer system or network.
explain: set out
purposes or
This is connected to a user's username and reasons / make
provides information about what data the user is the relationships
allowed to access on a system. between things
evident / provide
9 A student finds that a perpetrator has managed to hack into their social why and/or how and
media account. support with relevant
Explain two ways the perpetrator could have managed to do this. [4] evidence.

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

See Needs Getting Confident


1 can...
topic more work there to move on
explain the difference between the internet and the
5.1
world wide web.
explain what is meant by a URL and what the different
5.2
parts of it are.
describe how data is sent using both the HTTP and
5.2
HTTPS protocols.
describe how web pages are located, retrieved and
5.2
displayed using a web browser, DNS and a web server.
explain the main purpose of a web browser and I can
5.2
identify other functions that they often have.
explain how cookies are used and what the difference is
5.3
between a session cookie and a persistent cookie.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

Design a robot. Consider a scenario where a robot would be useful in your


daily life. Identify the tasks you would like the robot to perform. Describe
how the robot will work, for example, the inputs that would be used (and the
hardware, e.g. sensors that might do this), how the robot will decide what to
do, and what its output will be.

WHAT IS INTELLIGENCE?

There are many ideas on what it is to be intelligent, with one key


area being the ability to learn. How did you develop intelligence?
From when you were very young you started to learn. Each time
you experienced something new, you learnt from it, for example,
if you cried then someone might pick you up. So, next time you
wanted to be picked up, you cried.
The desire to create intelligent computers has been around
since the very first machines. Even looking back to ancient
history there are stories about bringing objects to life.
Achieving artificial intelligence has made the most steps over
the last 20 to 30 years. There are now systems that simulate
some human activities, and systems that can learn both with and
without a person telling them what to learn. These programs all
still run on rules, that are programmed into them to follow, so are
they intelligent? Humans learn by developing rules and storing
Figure 6.1: A brain
these in memory, so are we intelligent?
Discussion questions
1 What do you think is meant by intelligence?
2 How would you test whether a computer is intelligent, or not? What would you test it against?
3 Do you think that computers that learn and act independently should be created?

6.1 Automated systems KEY WORD

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.

Features of automated systems


An automated system usually has the following features:
• Sensors - to measure the environment.
• Microprocessor - to process the data from the sensors and determine if an action
needs to be taken.
• Actuators - to create a movement.
6 Automated and emerging technologies

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

This can also be shown in a diagram in Figure 6.2:

Figure 6.2: The process in which doors open automatically when a person is detected
6 Automated and emerging technologies

SKILLS FOCUS 6.1

CONTROL AND MONITORING SYSTEMS

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.

Figure 6.4: A control or monitoring system can be thought of as a 'story' of input,


process and output

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?

Automation in context KEY WORD

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

6.2 Robotics KEY WORDS

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.

6.3 Robots in context


Robots in medicine
Developments include the use of robot nurses that can move around a hospital to visit
and interact with patients. This can save the doctors and nurses time so that they can
spend more time doing other tasks.
Robots are also used to perform procedures such as operations. For example,
if a surgeon is not present in the hospital, even on the other side of the world,
they can control the robot performing the procedure. This means that a patient
will not have to wait for their procedure, and specialists are not required in
every hospital because they can share resources.
The use of robots in medicine also has drawbacks. If there are any errors in
the programming, or someone gains access to the programs and changes them,
then the result could cause harm. If a surgeon is controlling a robot from a
different location and the network connection is lost, then the procedure will
stop. This means there needs to be backup systems ready to work if there are
any problems.
6 Automated and emerging technologies

Figure 6.7: Robots preparing for surgery

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.

Figure 6.8: A lawnmower working without a driver


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

COMPUTER SCIENCE IN CONTEXT

A security robot can be used to protect a house. It could record what is


happening as videos, and detect motion or sound. These can be set to patrol
an area and alert someone if an abnormality (something unusual) is detected.

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.

6.4 Artificial intelligence


Can computers think? This is a question that has been asked and sought after for many
years. Alan Turing developed a test in 1950, called the Turing Test, to assess whether
a computer can display intelligence. The test involves a person holding a conversation
with a computer program, and another person. If they cannot work out which is the
computer and which is the person they are talking to, then it is has passed the Turing
Test. Some people do not think that this would demonstrate intelligence, the computer
is still following a set of rules that are pre-written.

What is artificial intelligence? KEY WORD

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.

Machine learning KEY WORD


Some Al systems do not learn, for example, in a computer game the characters can
move and interact with your character and adapt to what you do, but they are not machine learning:
learning what you do, they are following their pre-programmed rules. a computer program
that can adapt
Machine learning can be supervised, or unsupervised. its stored rules or
Supervised means that user is telling the program what its data means, for example, in processes.
the image recognition example the user says this image shows a horse.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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?

Expert systems KEY WORDS

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.

COMPUTER SCIENCE IN CONTEXT

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

An automated system performs actions without human intervention.


An automated system has sensors, a microprocessor and actuators.
Robotics is the creation and management of machines that perform actions that humans perform.
A robot contains a mechanical structure, electrical components including parts of an automated system,
and it can be programmed to perform specific actions.
Robots can be found in a range of areas, for example, medicine and transport, and have advantages and
disadvantages in each context.
Artificial intelligence is an area of computer science that aims to develop systems that mimic human
intelligence.
Machine learning is one area of artificial intelligence where a program can amend its own data and algorithms.
An expert system attempts to simulate a human expert in a specific area.
An expert system is made up of a knowledge base, rule base, inference engine and interface.
6 Automated and emerging technologies

EXAM-STYLE QUESTIONS COMMAND WORDS

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

1 can... See Needs Getting Confident


topic more work there to move on
describe what an automated system is. 6.1
describe the hardware used within an automated
6.1
system.
describe the role of sensors, microprocessors and
6.1
actuators used in automated systems.
describe the advantages and disadvantages of an
6.1
automated system in a given scenario.
define the term robotics. 6.2
give examples of the use of robotics. 6.2
describe the characteristics of a robot. 6.2
describe the advantages and disadvantages of
6.3
robotics in a given scenario.
define the term artificial intelligence. 6.4
describe the main characteristics of an Al system. 6.4
describe machine learning. 6.4
describe the key features of an expert system. 6.4
describe the use of an expert system for a given
6.4
scenario.
> Chapter 7
Algorithm
design and
problem solving
IN THIS CHAPTER YOU WILL:

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.

THE USE OF ALGORITHMS

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:

person(ali) Ali is a person.


person(jennifer) Jennifer is a person.
person(tyler) Tyler is a person.
friend(jennifer,tyler) Jennifer is friends with Tyler is a person.
friend(tyler,ali) Tyler is friends with Ali.

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.

Figure 7.1: A person reading programming statements

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

7.2 Analysis KEY WORDS


This first stage involves looking at the problem and the system that is needed. The problem
is explored, and the requirements of the program are identified. Decomposition is used decomposition:
to split the problem into subproblems. Subproblems allow the developers to identify the taking a system
requirements for each component part, and then tackle these separately in the next stage. and splitting it into
Once you have decomposed the problem, each of the subproblems can be implemented as smaller sub-systems,
a subprogram. which can in turn
be split into smaller
sub-systems.
7.3 Design design: the second
Once the requirements have been identified, the program designers can begin planning stage of the program
how the program will work in the design phase. This can include an overview of the development life
program using a structure diagram, and the designing of algorithms using flowcharts cycle, which involves
and pseudocode. decomposition
of the problem
and algorithms
Structure diagram created ready for
A structure diagram is developed by decomposing a program into its subprograms. implementation.
The diagram has the name of the program at the top, and below this its subprograms. structure diagram: a
Each subprogram can be split down further as well if required. hierarchical diagram
that shows the
Example 1 decomposition of a
A calculator needs to allow the user to enter numbers system.
and the symbol, calculate the result and output this. process: an action
The name of the program is at the top. The boxes that is performed,
below are ready for subprograms (Figure 7.2). for example,
X <- X + 1.
One way of splitting up a small program is to think Figure 7.2: A structure diagram
of inputs, processes and outputs. A calculator has for a calculator
an input, processes and output, so these can be
added to the diagram (Figure 7.3).
The subprograms can then be split further. The calculator needs two numbers and a
symbol to be entered (e.g. 2 + 3). Add these boxes below input (Figure 7.4).
The process is dependent on the symbol entered. In this calculator, there is +, - , *
and /. Each of these could be given a separate box (Figure 7.5).

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

numberl + ■ numberl - numberl * 1 numberl /

Figure 7.5: Expanding the process subprograms


number2
1 number2
1 number2
1 number2

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

Figure 7.9: Subprograms for the chess program

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

Input Input Assign Display


player! player2 colours new board

Figure 7.10: The New players subprogram Figure 7.11: The New game subprogram

Check won

Check player Check player


move check move checkmate

Figure 7.13: The Check won subprogram


7 Algorithm design and problem solving

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.

Flowcharts KEY WORD

A flowchart is a diagrammatic representation of an algorithm. Figure 7.14 shows some flowchart: a


of the set of standard symbols. diagrammatic
representation of an
algorithm.

Figure 7.14: Flowchart symbols

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

Shape Description Examples


Start/stop A flowchart begins with a Start
box, with one arrow from it. Start

A flowchart ends with a Stop box,


with one arrow going into it.
1

(
1
Stop

Figure 7.15: Start/Stop

Input A single input of a value with an


identifier for that value. / input number /

One arrow should go into the


box, and one arrow should
come out.
I
/ input letter /

Figure 7.16: Input

Output An output of text in speech


marks, and/or the identifier of
a value / output number /

/ output "error" /

/ output "number is" /


/ & number /

Figure 7.17: Output

(continued)
7 Algorithm design and problem solving

Shape Description________________ Examples


Process An action that is being
performed, usually a
mathematical calculation.
One arrow goes into the box,
and one arrow comes out of
the box.

Decision A question with two outcomes,


yes or no (or true or false). The
question is a comparison from:
= equal to
> greater than
< less than
>= greater than
<= less than.
You can have more than one
condition by includinq AND
or OR.
See Chapter 8, Section 6 for the
use of these operators.
One arrow goes into the box.
Two arrows come out, one
labelled yes (or true) and the
other no (or false).

Table 7.1: Flowchart symbol examples

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.

Figure 7.20: A flowchart for a calculator


7 Algorithm design and problem solving

Example 2
Figure 7.21 shows a flowchart for a password validation program.

Figure 7.21: 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

6 Draw the flowchart symbol for each statement:


a Start
b INPUTx
c INPUT y
d ISx>y?
e x =x + y
f Stop
7 Draw a flowchart to take three numbers as input, find and output the
largest number.

7.4 Pseudocode KEY WORD

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.

Valid pseudocode Invalid pseudocode


INPUT Value Input the value X
FOR X = 0 to 9 Loop 10 times
OUTPUT Value + X In each loop output the loop number added to the input value
NEXT X
numl = input input = numl
num2 = input input = num2
if numl > num2 then if numl is greater than num2 then output numl
print(numl) if numl is not greater than num2 then output num2
else
print(num2)
Endif

Table 7.2: Valid/invalid pseudocode examples

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

Find an example of a flowchart and turn it into a pseudocode algorithm.

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

Statement Valid Invalid


x = x + 1

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

10 Write a pseudocode algorithm to:


• take three values as input KEY WORDS
• multiply the numbers together coding: the writing
• output the result. of a program
11 Write a pseudocode algorithm to: using one or more
programming
• take 10 numbers as input (using a loop)
languages.
• add together the values
• output the total with an appropriate message. testing: repeated use
of a system to try all
different possibilities
to make sure the
7.5 Coding system is fully
working and cannot
Once you have decomposed your problem into subproblems, and you have designed the
be broken.
algorithms using flowcharts and/or pseudocode then you can start writing the program
in your chosen programming language. This is often referred to as coding. test data: the input
This will also include some iterative testing. This is testing that is carried out while the data that is used to
program is being developed, for example, if you write the program code for one of the test a system.
subproblems, then you will test it with a range of different data to make sure it is fully normal test data:
working before moving onto the next step. data that a program
should accept.
abnormal test data:
7.6 Testing data that a program
When you have finished your program, you need to carry out testing to make sure it: should not accept.

• fully works extreme test data:


data that is on the
• does not crash edge of what is
• meets all requirements. allowed.
You will need to identify appropriate test data to use to test the program. boundary test
There are four types of test data: data: data that is on
the edge of being
• Normal - data that the program should accept. extreme 极值 accepted, and data
• Abnormal data that the program should not accept. boundary 边界 that is on the edge of
not being accepted.
• Extreme - data that is at the edge of what is allowed.
• Boundary - data that is on the edge of being accepted and being rejected.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 1
A program allows the user to enter their age as a whole number between 10 and 100
years.

Test data type Example data


Normal Any number between 10 and 100 inclusive,
e.g. 10, 20, 50, 100, etc.
Abnormal Any data that is not a number between 10 and 100,
e.g. 9, -1, 101,200, "age", "30", 12.2.
Extreme The largest number accepted - 100.
The smallest number accepted - 10.
Boundary Either side of the largest bound - 100 and 101.
Either side of the smallest bound - 9 and 10.

Example 2
A user needs to enter a password at least 8 characters long.

Test data type Example data


Normal Any set of 8 or more characters, but they must be text
(have speech marks),
e.g. "abcdefgh" " 12fghj567812".
Abnormal Any set of characters with 7 or less characters,
e.g. "1234567“, "seven".
Extreme Any with 8 characters only,
e.g. "12345678", "ajrkdhJK".
Boundary Either side of the 8 character bound, 7 characters or 8
characters,
e.g. "1234567", "12345678", "abcdefg", "iJHFD7hJ",

ACTIVITY 7.4

In pairs find a computer game to play. Anything as simple as a puzzle game,


to a full 3D adventure game. Discuss how this game might have been tested.
What data would be used as inputs?

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:

Test type Test data


Normal
Abnormal
Extreme
Boundary

7.7 Common algorithms KEY WORDS

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

"a" "v" "i"

Compare the "a" with They are not the same.


Compare the "v" with They are not the same.
Compare the "!" with ”#". They are not the same.
There are no more values, so "#” is not found.

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

One method of sorting data is using a bubble sort. bubble sort: a


sorting algorithm
A bubble sort takes the first 2 values; value 1 and 2, and compares them. If they are the
that moves through
wrong way around it swaps them. It then puts these back and takes values 2 and 3 and
the list repeatedly
compares them. If they are the wrong way around it swaps them. This repeats until it has
swapping values in
worked all the way through the list once. It then starts again with the first two values.
pairs.
It is called a bubble sort because it acts like a bubble moving across all the elements to
the end, then starting from the beginning.
There are two ways to tell the algorithm when to stop.
1 The algorithm has been through the entire list, the number of elements in the
list -1. So if there are 10 elements, the algorithm runs 9 times. If there are
100 elements, the algorithm runs 99 times. If there are XElements, the algorithm
runs XElements - 1 times. This is the easiest way to program it, but it is not
efficient. All elements might be in the correct order to begin with, but it is still
going to run through the same number of times.
2 Either the algorithm has run through the list XElements - 1 times, or it has run
through the list, checking all of the elements, and it has not made any changes.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

//reset changes each time a new pass starts


Changes <- FALSE
//loop through each element in the array

//check if the data is in the correct order


FOR Index <- 0 to LENGTH(DataArray) - 1
IF DataArray[Index] > DataArray[Index + 1] THEN
//if not swap the items
Temp <- DataArray [Index]
DataArray[Index] <- DataArray[Index + 1]
DataArray [Index + 1] <- Temp
Changes <- TRUE
ENDIF
NEXT Index
ENDWHILE

SKILLS FOCUS 7.1

BUBBLE SORT OF NUMERICAL DATA

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

Now you have completed 1 pass, check if it should stop!


Compare to the two criteria:
a you have passed through all numbers 3 times [False, only 1 pass has 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 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?

SKILLS FOCUS 7.2

BUBBLE SORT WITH CHARACTERS INTO DESCENDING 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'?

PROGRAMMING TASK 7.2

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.

Totalling KEY WORD

Totalling is adding a group of values together to give a total. totalling: statements


in a program that add
For example, a person buys items at a supermarket. The items cost: $0.50, $1.00, $1.00,
together a set of data
$15.50, $21.30 The total is 0.5 + 1 +1 + 15.5 + 21.3 = $39.30
to produce the total.
To do this in a program you need to:
Initialise a variable to store the total, e.g. Total <- 0.
Add the value to the current contents of the total, e.g. Total <- Total + Value.

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 KEY WORD

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

//if the number is less than 10


IF NumberArray[x] < 10 THEN
CountBelowlO <- CountBelowlO + 1 //increment the counter
//if the number is greater than 20
ELSEIF NumberArray[x] > 20 THEN
CountAbove20 <- CountAbove20 + 1 //increment the counter
END IF
NEXT X

Finding the minimum


The minimum value is the smallest value within a set. For example, the marks for a
class are entered and the lowest mark is the minimum.
To do this in a program you need to:
• initialise a minimum variable to be a large value, beyond those that will be entered,
e.g. Minimum <- 9999.
• Compare each value to the minimum variable, e.g. IF Number < Minimum.
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

• If it is, it replaces the minimum value, e.g. minimum <- number.


This means the new value is the minimum, so the next time a value is compared, it
is checking it with the new minimum value.

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

Finding the maximum KEY WORD

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

Finding the average KEY WORD

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 on input KEY WORD

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?

There are different types of validation.


7 Algorithm design and problem solving

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

Data <- INPUT ()


IF LENGTH(Data) < 10 THEN
OUTPUT("Invalid")
ELSE
OUTPUT("Valid")
ENDIF

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

Type check KEY WORD


Data can be in different forms, including an integer (whole number), real (decimal number),
string (any characters), Boolean (true or false). There are two ways of writing a type check: type check: a type of
validation that checks
1 Use a function such as . GetDataType () to return the data type, that you can
data is the correct
then compare to the one you want.
data type.
2 Use a function such as . Is Integer () to return True if it is an integer and
False otherwise.

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

Presence check KEY WORD


A presence check makes sure that some data has been entered. Programming languages
can make use of the value null, or for a string value an empty string represented by "". presence check: a
type of validation
that makes sure data
Example 1 has been entered.
Using selection:
This algorithm outputs Invalid if there is no data entered.
INPUT Data
IF Data = NULL THEN //check if the data entered is null
OUTPUT("Invalid")
END IF

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

Format check KEY WORD


Some data may need to be entered in a specific way, for example, a date must be:
/ /_____ , where each space is a number - a format check makes sure the data is format check: a
entered this way. An ID number may need to be 1 number followed by 3 characters. type of validation
that makes sure the
Example 1 data meets a specific
order, e.g. 1 number,
Using selection:
then 3 letters.
An ID number entered needs to be 1 number followed by 2 characters. This algorithm
checks the characters and outputs whether it meets the required format.
INPUT IdNumber
//check if the first character is a number, and characters 2
//and 3 are strings
IF(SUBSTRING(IdNumber, 0, l).IsNumeric = TRUE AND
SUBSTRING(IsNumber, 1, 2) = TRUE) THEN
OUTPUT("Valid")
ELSE
OUTPUT("Invalid")
ENDIF
Note that SUBSTRING (String, X, Y) starts at character x in the string, and returns y number
of characters.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

Check digit KEY WORD

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

Verification of data KEY WORDS


When entering data from another source, for example, a paper copy, it is important to
make sure you have entered exactly what was written originally. This is called verification: checking
verification, a check that you have copied the data accurately. that data is entered
accurately, that it
There is a difference between entering data accurately, and entering the correct data.
is the same as the
Verification only checks you have copied it accurately, the actual data may still be
original.
incorrect if the original was incorrect.
visual check:
Two forms of verification are a visual check and double entry.
comparing the data
A visual check is where you compare the data entered to the original. For example, entered with the
reading each line from a paper copy and checking it is identical on the computer. original side-by-side,
A double entry check is where the same data is entered twice, usually by different people. double entry check:
The computer will then check whether there are any differences in what they each entered. two different people
enter the same
COMPUTER SCIENCE IN CONTEXT data which are then
compared.
Have you ever had to enter data into a program twice? You have most likely
done this when entering your email address, or a password. Think about why
it was important that your email and password were entered accurately. What
could have happened if they were not?

PROGRAMMING TASK 7.6

A user needs to enter a series of data that each require validation. The table
shows the data and the requirements:

Data Validation requirements


Username Minimum length of 5 characters.
Date of birth In the format NN/NN/NNNN, e.g. 01/01/2020.
Type of character Limited to: "Elf", "Fairy", "Gnome", "Magician".
Starting strength A number between 1 and 5 inclusive.
Starting health 10 minus the starting strength input.

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

7.8 Trace tables KEY WORD

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.

SKILLS FOCUS 7.3

TRACE TABLE WITH SELECTION

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

numberl number2 OUTPUT

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.

Run line 2 of the code (input values 1, 3):


INPUT Numberl
INPUT Number2
IF Numberl > Number2 THEN
OUTPUT(Numberl)
ELSE
OUTPUT(Number2)
ENDIF

numberl number2 OUTPUT


1 3 <---------------- The second line
inputs the second
value given, 3.
Run the IF statement:
Use the values in the
INPUT Numberl table, numberl is 1,
INPUT Number2 number2 is 3.
IF Numberl > Number2 THEN 4
OUTPUT(Numberl) IF 1 > 3 This is
ELSE FALSE so run the
OUTPUT(Number2 )<— ELSE
ENDIF
OUTPUT the value
in number2
numberl number2 OUTPUT
1 3 3
7 Algorithm design and problem solving

SKILLS FOCUS 7.4

TRACE TABLE WITH LOOPS


When you are following an algorithm that includes a loop (iteration), some of the
code will be repeated. To follow the code run one line at a time as before, and when
you get to the end of the loop, go back to the start of the loop.
For example: trace the following algorithm with the input values 4, 3, 2, 1, 0.
01 Count <- 0
02 Inputvalue <- 1
03 Total <- 0
04 WHILE Inputvalue > 0 DO
05 INPUT Inputvalue
06 Total <- Total + Inputvalue
07 Count <- Count + 1
08 ENDWHILE
09 OUTPUT "The total is ", Total
10 OUTPUT "There were ", Count, ' Numbers"
Start by creating the trace table with each of the variables and the output.
There are 3 variables in this algorithm:

Count InputValue Total OUTPUT

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

Count InputValue Total OUTPUT


0 1 0

2 Run line 04.


04 WHILE Inputvalue > 0 DO
LOOP is 1 so this is TRUE meaning that the code inside the loop is run
Run line 05 with the first input value of 4.
05 INPUT Inputvalue

Count InputValue Total OUTPUT When a variable


0 1 0 has a new value, it
4 < is written below the
previous one.
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

3 Run lines 06 and 07.


06 Total <- Total + Inputvalue Total <-0 + 4
07 Count <- Count + 1 Count <-0 + 1

count inputValue total OUTPUT


0 1 0
1 4 4
4 Line 08:
08 ENDWHILE
sends you back to line 04.
04 WHILE InputValue > 0 DO
Inputvalue is 4, so while 4>0 is TRUE to run line 05 with the second input value of 3.
05 INPUT InputValue

count inputValue total OUTPUT


0 1 0
1 4 4
3
5 Lines 06 and 07 run.
06 Total <- Total + InputValue Total <-4 + 3
07 Count <- Count + 1 Count <-1 + 1

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7
6 Line 08 ENDWHILE returns to line 04.
04 WHILE InputValue > 0 DO WHILE 3 > 0 is TRUE. Run lines 05, 06 and 07.
05 INPUT InputValue InputValue <- 2
06 Total <- Total + InputValue Total <-7 + 2
07 Count <- Count + 1 Count <-2 + 1

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7
3 2 9
7 Line 08 again returns to line 04. WHILE 2 > 0 is TRUE. Run lines 05, 06 and 07.
05 INPUT InputValue InputValue <- 1
06 Total <- Total + InputValue Total <-9 + 1
07 Count <- Count + 1 Count <-3 + 1
7 Algorithm design and problem solving

CONTINUED

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7
3 2 9
4 1 10

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

count inputValue total OUTPUT


0 1 0
1 4 4
2 3 7
3 2 9
4 1 10
5 0 10
9 Line 08 returns to line 04 again. WHILE 0>0 is FALSE this time, so the loop
does not run.
Jump to line 09 run line 09 and 10.
09 OUTPUT "The total is ", Total
10 OUTPUT "There were ", Count, " numbers"

count inputValue total OUTPUT


0 1 0 Be careful with your
1 4 4 outputs. They must
2 3 7 match the output
in the code. For
3 2 9 example, 'The total
4 1 10 is W is correct,
5 0 10 The total is 10 but 'total = 10' is
incorrect.
There were 5 numbers <—

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

7.9 Finding the purpose of an algorithm


A trace table can help you work out the purpose of an algorithm. By following an
algorithm step-by-step you can see what happens to the values, what changes are made,
and when these are made. From this you can determine the purpose of the algorithm.

SKILLS FOCUS 7.5

FINDING THE PURPOSE WITH A TRACE TABLE

Describe the processes in this algorithm and state its purpose.


INPUT Valuel
INPUT Value2
INPUT Value3
IF Valuel > Value2 AND Valuel > Value3 THEN
OUTPUT(Valuel)
ELSEIF Value2 > Valuel AND Value2 > Value3 THEN
OUTPUT(Value2)
ELSE
OUTPUT(Value3)
ENDIF
OUTPUT(Valuel + Value2 + Value3)
1 First test the algorithm with a set of data that you come up with (if they are not
provided for you). For example, test this algorithm using l, 2 then 3.
2 Create a trace table by following the algorithm with the data input.
Valuel Value2 Value3 OUTPUT
1 2 3 3
6

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

Valuel Value2 Value3 OUTPUT


10 5 1 10
16

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)

quantity Total value small OUTPUT


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

SKILLS FOCUS 7.6

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

7.10 Finding errors in a program and


correcting the errors
To find an error in an algorithm you need to know the purpose of the algorithm.
You can then test the algorithm with different data, completing trace tables if needed,
to find out what the algorithm actually does. Once you know the difference between
what it does and should do, you can start to identify the errors and the changes you
need to make.

COMPUTER SCIENCE IN CONTEXT

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.

SKILLS FOCUS 7.7

USING A TRACE TABLE TO FIND ERRORS IN A PROGRAM

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.

Total Quantity Number OUTPUT


1 1
1 2 1
2 3 2
3 4 3
4 5 4

Now look at the results and where it has gone wrong:


1 The total is overwritten each time, it should be added to.
2 Total starts with 1 but this will add another 1 to the total, so it should be 0.
3 Only four numbers can be input, it should be five.
Let’s take each of the problems one at a time to solve them.
1 The total should not be overwritten. Line 05 overwrites the total.
This should be Total <- Total + Number.
2 The total should not start at 1, it should be 0. Line 01 writes 1 to total.
This line should be Total <- 0.
3 Only 4 numbers are input, it should be 5. There are two ways this can be
changed, both are valid. Either Line 02 can be Quantity <- 0 or line 03 can
be WHILE Quantity < 6.

SKILLS FOCUS 7.8

FINDING ERRORS BY READING THE CODE

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

The fourth requirement:


Calculate the average value.
The average is calculated by totalling the inputs and then dividing by the number of inputs.
Line 08 totals the data entered, but it uses the wrong identifier, it should be data not DATA.
Total <- Total + Data
Line 11 works out the average correctly.
The fifth requirement:
Output the average value.
Line 12 outputs the average correctly.
In this case the errors and corrections have been identified along the way. You can also
combine this with using test data to check both the original algorithm and to check that your
corrections are accurate.
Questions
1 Complete the trace table for the following algorithm with the input data: 20 50 60 25 35.
Total <- 0
Average <- 0
Counter <- 0
WHILE Counter <= 5 DO
INPUT Mark
Total <- Total + Mark
Counter <- Counter + 1
ENDWHILE
Average <- Total / Counter
OUTPUT "The total is ", Total
OUTPUT "The average is ", Average

Total Average Counter Mark OUTPUT


7 Algorithm design and problem solving

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

I) State the purpose of the algorithm.


3 Explain the purpose of the following algorithm:
Valid <- 0
Invalid «- 0
Continue <- "Y"
WHILE Continue = "Y" DO
INPUT Value
IF Value >= 10 AND Value <= 20 THEN
Valid <- Valid + 1
ELSE
Invalid <- Invalid + 1
ENDIF
OUTPUT "Continue?"
INPUT continue
ENDWHILE
OUTPUT "valid = ", Valid
OUTPUT "invalid = ", Invalid
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

SUMMARY

Programs are developed by following a program development life cycle.


The program development life cycle is made up of; analysis, design, coding and testing.
In the analysis stage the problem is identified and decomposed.
In the design stage the algorithms are planned.
In the coding stage the program is written.
In the testing stage the program is tested.
Decomposition is the splitting of a system into sub-systems.
Decomposition can be shown using a structure diagram.
Algorithms can be planned using flowcharts and pseudocode.
A linear search checks each item of data in turn.
A bubble sort compares the items in pairs repeatedly.
Totalling is adding together the values.
Counting is adding l to the count for each item.
To find the minimum value, a variable needs to be initialised with a large value.
To find the maximum value, a variable needs to be initialised with a small value.
Validation is checking data entered is reasonable and within bounds.
Validation checks include; range check, length check, type check, presence check, format check and check digit.
Verification checks that data has been input accurately.
Verification checks include visual check and double entry check.
Four types of test data are normal, abnormal, extreme and boundary.
A trace table is used to dry run an algorithm. It can be used to find the purpose of an algorithm
and to find errors in the algorithm.

EXAM-STYLE QUESTIONS COMMAND WORDS

1 Define the term algorithm. [1] define: give precise


2 One stage of the program development life cycle is the analysis. meaning.
Identify and describe two other stages. [4] identify: name /
3 Describe the purpose of decomposition. [2] select / recognise
4 A computer game allows a user to load a saved game or to start a new game. describe: state the
The game then loads the puzzle for that level. The user controls a character points of a topic /
by using the arrow keys on the keyboard. The left arrow moves the character give characteristics
left, the up makes the character jump, right moves the character right, and main features.
down makes the character lie down.
a Draw a structure diagram for the game. [4]

192 )>
7 Algorithm design and problem solving

CONTINUED

b Write an algorithm using a flowchart to represent the input of a


key from a user, and then move the character. [6]
c When the user starts a new game, they have to input a name that is
made of at least 8 letters. This is validated using a length check.
i Identify one other appropriate validation routine that could be
used to validate the name. [1]
ii Write, using pseudocode, the length check validation for the name. [4]
[Total: 15]
5 Complete the trace table for the following algorithm, with the input data:
blue 5 Y blue 1 Y yellow 3 Y white 5 X

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

Blue White Yellow Continue Colour Quantity OUTPUT

[5]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

COMMAND WORD

show (that): provide


structured evidence
that leads to a given
result.
7 Algorithm design and problem solving

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

See Needs more Getting Confident to


1 can...
topic work there move on
identify the stages in the program development
7.1
life cycle.
use decomposition to split a system into
7.2
sub-systems.
create structure diagrams, flowcharts and
7.3
pseudocode algorithms.
explain how a bubble sort and linear
7.7
search works.
describe and produce algorithms that include
finding the maximum, minimum and 7.7
average values.
understand the need for validation and
verification and write programs that make 7.7
use of each.
identify appropriate test data for an algorithm. 7.6
complete a trace table for an algorithm. 7.8
check a program for errors and amend
7.10
the program.
explain the purpose of an algorithm. 7.9
> Chapter 8

Programming
IN THIS CHAPTER YOU WILL:

• learn how to write programs using pseudocode


• use variables and constants
• learn about the appropriate use of basic data types
• write programs that use input and output
• write programs that use sequence
• write programs that use arithmetic operators
• write programs that use selection including IF and CASE statements
• write programs that include logical and Boolean operators
• write programs that use iteration including count-controlled, pre-condition and post-condition loops
• write programs that use totalling and counting
• write programs that perform the string handling methods length and substring
• write programs that use nested statements
• understand the purpose of subroutines
• understand the differences between procedures and functions
• write programs that use subroutines
• understand the purpose and use of parameters
• write programs with subroutines that take parameters
8 Programming

GETTING STARTED

Find a computing program (or part of a program) that is written in the


programming language you will be using in-lesson. Work with a friend to
identify what each of the different lines of code do. Present your findings to
the class by showing them each line of code and explaining its purpose.

PROGRAMMING LANGUAGES

There are lots of different procedural programming •solidierenO

languages, for example, Java, VB.NET, Python, ilidieren Makro

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

need semi-colons at the end of each line of ng - Cells(Rows.Count, 1).End(xlDp).Row


ng - Cells(l, Columns.Count) .End(xlToLeft) .Column
code. There are, however, a set of programming ng - ActiveSheet.Name a 4 "R1C1" 4 ":R" 4 zrng 4 "C" 4
ActlveWorkbook.PivotCaches.Create(SourceTypei-xlConsolidati

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

fundamentals are, and how these work, then to xlHidden


With ActiveSheet.PivotTables("PlvotTable2").PivotFields^
.Orientation - xlRowField
program in a new language you just need to check ActiveSheet.PivotTables(’PivotTable!-).RowAxisLayout xlTabular
the syntax which that specific language uses. ActiveSheet.PivotTables("PivotTable!").RepeatAllLabels xlRepeat
ActiveSheet.PivotTables("PivotTable!").PivotFields("Zeile ) .Sub
False, False, False, False, False, False, False, False, Fala
•ActiveSheet.PivotTables("PivotTable2").PivotFields("Spalte ).Su
For example, a FOR loop (a type of count- • False, False, False, False, False, False, False, False, Fei
•ActiveSheet.PivotTables("PlvotTable2").PivotFields("Wert ).Sub
• False, False, False. False, False, False, False, False, Fa
controlled loop that you will learn about later in ■ActiveSheet.PivotTables("PivotTable!").PivotFields("Seitel ).3
• False, False, False, False, False, False, False, False, Fa
the chapter) that will output the numbers 1 to 10. On Error GoTo Fehler

In pseudocode (a generic non-language specific


language) this could be:

FOR Count <- 1 TO 10


OUTPUT(Count)
NEXT Count Figure 8.1: Image of a man reading program code
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

8.1 Programming concepts


This chapter will introduce different code examples. It will show how to do each of the
procedures in three different languages (Java, VB.NET and Python) and pseudocode.
The pseudocode (red font) will always appear as the first code in each example.

Variables and constants


What are variables and constants?
When you are writing a program, you will need to store data; whether this is data that KEY WORDS
has been input, the result of calculations or any for any other reason. You can store
data in variables and constants. variable: a named
memory location
A computer has memory, e.g. RAM. This is made of lots of spaces where you can put
that can store data.
data. Imagine this table is memory. Each of the boxes can store a piece of data.
The data can change
0 whilst a program is
running.
1
2 constant: a named
3
memory location that
can store data. The
4 data cannot change
5 whilst a program is
6 running.
7 identifier: a name
given to a variable,
In memory location 0 is the data 10. In memory location 1 is the data red.
constant, data
Each variable and constant is one of these spaces in memory that is given an identifier structure (e.g. array)
(it has a name). In this table the memory numbers have been replaced with their or subroutine.
identifiers. The memory space with the name number 1 is storing the piece of data 10.
8 Programming

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

8.2 Data types


Data in programs can be of different types. For example, it could be numeric or text.
You will need to tell your program what type of data you want it to store. Some
programming languages need you to declare what type of data your variable will store KEY WORDS
when you first use it. In some programming languages you need to swap data between
types, for example, Python will only output string (text) data, so if you try and output string: a data type.
a number without turning it into a string it will produce an error. Any characters
including letters,
Table 8.1 shows common data types:
numbers and/or
Data type Description Example data symbols.
String Text - characters numbers and "hello" data type: the
symbols. "123" characteristics of
a piece of data.
The data will always need to be inside "help!" Common data types
speech marks, either1 ' or " ".
are string, integer,
Integer Whole numbers. 1 real and Boolean.
23 integer: a data type.
-300 Whole numbers,
45656 real: a data type.
Real, single, Decimal numbers. 1.2 Decimal numbers,
double 23.0 single: a data type.
Decimal numbers,
-20.49
3949.3834 double: a data type.
Decimal numbers.
Boolean Either true or false. TRUE
FALSE Boolean: a data type.
True or False,
One character or number of symbol. "h"
HgH char: A single
The data will always need to be inside character, e.g. 'A1,
speech marks, either " or "". H q it
■r, ■*■.
Table 8.1: Common data types

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

Storing different data types

Storing a string in a variable:


Colour <- "red"
Storing an integer in a constant:
CONSTANT Value *-10
Storing a real number in a variable:
Price <-22.4
Storing a Boolean in a variable:
Flag <- TRUE

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

Converting between data types


You might need to turn one data type into another data type. This is not required as KEY WORD
part of the specification, but when you are programming in your chosen language you
might have to do it for your program to work. This is called casting. You can do this by casting: converting
using the name of the data type you want the data to become. data from one data
type to another data
Example 1 type.
Convert a string to an integer:
Number «- int("123")
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

2 Write a pseudocode statement to assign the word "house" to a variable named


MyWord.
3 Write a pseudocode statement to declare a constant named MultiplyValue
with the value 10.

8.3 Input and output


Output KEY WORD
A program at some point will probably need to give information to the user. It does
this using output. When outputting strings (characters, letters, etc.). output: data that is
displayed to the user
usually on-screen.
Example 1
Output the words, Hello World:
OUTPUT("Hello world")

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

PROGRAMMING TASK 8.1

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

8.4 Arithmetic operators arithmetic


operator: a symbol
Arithmetic operators instruct a program to perform calculations. Table 8.2 describes the that performs
most common operators, many of which you will know from mathematics. a mathematical
function, e.g. '+'
Operator Description Example
adds two values
+ Adds two values together. 10 + 2 gives 12 together.
11.3 + 9 gives 20.3
- Subtracts the second value from the 10-2 gives 8
first. 11.3 - 9 gives 2.3
★ Multiplies two values together. 2 gives 20
11.3 * 9 gives 101.7
/
Divides the first number by the 10/2 gives 5
second. 11.3 / 9 gives 1.256
DIV Gives the whole number after DIV (10, 2) gives 5
the first number is divided by the DIV (11, 9) gives 1
second, i.e. it ignores any decimals.
MOD Gives the remainder after the first MOD (10, 2 ) gives 0
number is divided by the second, MOD (11, 9) gives 2
i.e. how many are left.
A
Power of. 2 A 3 = 8
3 A 2 = 9

Table 8.2: Common operators


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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)

COMPUTER SCIENCE IN CONTEXT

Many of these arithmetic operators should be familiar to you from


mathematics, where you should be used to working out expressions. In
programming the same principles are used, you write the formulae but not the
answer - the computer works that out because the input data can be changed.
8 Programming

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

8.5 Sequence KEY WORD

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.

Logical operator Description Example


= or == Equals to 10 = 10? would give TRUE. 10 is equal to 10.
10 = 2? would give FALSE. 10 is not equal to 2.
<> or I= Not equal to 10 <> 10? would give FALSE. 10 is not, not equal to 10.
10 <> 2? would give TRUE. 10 is not equal to 2.
< Less than 10 < 11? would give TRUE. 10 is less than 11.
10 < 10? would give FALSE. 10 is not less than 10.
11 < 10? would give FALSE. 11 is not less than 10.
(continued)
8 Programming

Logical operator Description Example


<= Less than or 10 <= 11? would give TRUE. 10 is less than or equal to 10.
equal to
10 <= 10? would give TRUE. 10 is less than or equal to 10.
11 <= 10? would give FALSE. 11 is not less than or equal to 10.
> Greater than 10 > 11? would give FALSE. 10 is not greater than 11.
10 > 10? would give FALSE. 10 is not greater than 10.
11 > 10? would give TRUE. 11 is greater than 10.
>= Greater than or 10 >= 11? would give FALSE. 10 is not greater than or equal to 11.
equal to
10 >= 10? would give TRUE. 10 is greater than or equal to 10.
11 >= 10? would give TRUE. 11 is greater than or equal to 10.

Table 8.3: Logical operators

SKILLS FOCUS 8.2

COMPARISON OPERATORS

Comparison operators are used in comparison statements; both selection and


iteration. The operators are very similar and you need to know the difference
to make sure you know, a, how to read the statements to make sure you follow
an algorithm correctly, and b, which to select when you are writing your own
comparison statements.
A common error is when less than and greater than are confused. The shape of
them can help you to work out which is correct.
IF (10 < 2 ) The smaller part of the < is nearest the left, the 10. This is the less
than part. So the statement reads if 10 is less than 2. This would result in False
because 10 is not less than 2.
IF (150 > 25) The larger part of the > is nearest the left, the 150. This is the
greater than part. So the statement reads if 150 is greater than 25. This would result
in True because 150 is greater than 25.
IF (33 <= 34) The smaller part of the <= is nearest the left, the 33. This is the
less than part. There is also an equals after the less than sign. So the statement reads
if 33 is less than or equal to 34. This would result in True, 33 is less than 34.
IF(5O >= 70) The larger part of the >= is nearest the left, the 50. This is the
greater than part. There is also an equals after the less than sign. So the statement
reads if 50 is greater than or equal to 70. This would result in False, 50 is not greater
than or equal to 70.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

i f(numl < num2){


System.out.printIn(num2);
}else if(num2 < numl){
System.out.printIn(num2);
}else{
System.out.printin("They are the same");
}

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

What is the difference between IF and CASE statements? Is there a scenario


when one is more appropriate than another? Write one example of each
where that is the most appropriate type to use.

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?

Boolean Operators KEY WORDS


There are three Boolean operators that you can use to join conditions: the AND Boolean operator:
operator, the NOT operator and the OR operator. These are described in Table 8.4. a symbol that joins
multiple logical
Boolean Description Example
comparisons, can be
operator
AND, OR or NOT.
AND If both conditions are IF 1 = 1 AND 2 =
true, the result is true. AND operator:
This will return TRUE. The left of the AND is returns True when
If one or both true, and the right of the AND is true. both inputs are True.
conditions are false,
IF 1 = 1 AND 1 > 2 NOT operator:
the result is false.
This will return FALSE. The left of AND is returns True if the
true, but the right of AND is false. input is False, and
False if it is True.
IF 1 < -2 AND 0 < -1
OR operator: returns
This will return FALSE. Both comparisons True when one, or
are false, so the result is false. both, inputs are True.
OR If one, or both, IF 1 = 1 OR 2 = 2
conditions are true, the
This will return TRUE. The left of the OR is
result is true.
true, and the right of the OR is true.
If both conditions are
IF 1 = 1 OR 1 > 2
false, the result is false.
This will return TRUE. The left of OR is true,
but the right of OR is false.
IF 1 < -2 OR 0 < -1
This will return FALSE. Both comparisons
are false, so the result is false.
NOT Reverse the condition. IF NOT (1 = 1)
If the condition is True
it becomes False. The brackets equal to TRUE, 1 equals 1.
The NOT makes it FALSE, so it becomes 1
does not equal 1.
IF NOT (End of File)
This is used with file handing. End of
File will return TRUE if there is no data
left in the file. The NOT turns this to false.
So while not at the end of the file.

Table 8.4: Boolean operators

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

PROGRAMMING TASK 8.2

A computer program needs writing to act as a calculator. The program should


take in two values and a symbol (e.g. +, * or /). Depending on the symbol
entered, the calculator should perform that calculation. For example, if 3 5 + is
entered, then the result should be 8 (3 + 5 = 8).
Getting started
1 Identify the inputs that the system will require.
2 Identify appropriate variables to store the inputs in.
3 Write a program to ask the user to enter the two numbers and symbol,
and store these in variables.

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

System.out.printIn("Do you want to stop?");


answer = scanner.nextLine();
}while(!answer.equals("Yes"));

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

Console.WriteLine("Guess the number")


guess = Console.ReadLine
Loop Until guess = numberToGuess

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

SKILLS FOCUS 8.3

CONVERTING A FOR LOOP TO A WHILE LOOP

The three different types of loop (count-controlled, pre-condition and post­


condition) can often be written as a different type of loop. For example, a count-
controlled loop can be written using a pre-condition loop, or a post-condition
loop. Pre-condition and post-condition loops can be rewritten as each other. Some
pre- and post-condition loops can be written as a count-controlled - but only if their
comparisons are for a count, e.g. looping 10 times.
A computational thinking skill is the ability to take a loop and convert it to other
loops. This demonstrates your understanding of how the different loops work and
the characteristics of each type of loop. Therefore it is good practice to experiment
by converting one loop into a different type.
For example, converting a for loop to a while loop.
Consider the for loop:
FOR X <- 1 TO 10
OUTPUT(X)
NEXT

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

Step 1: Declare your variable with its starting value.


Step 2: Take the last value and put it in the while condition.
Step 3: Increment the counter in the loop.

2 Convert the following FOR loop to a WHILE loop.


FOR New <- 100 TO 111
OUTPUT(New New)
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

8.8 Totalling KEY WORD

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

8.9 Counting KEY WORD

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

Dim count As Integer = 0


For X = 0 To 99
If arrayData(X) > 50 Then
count = count + 1
End If
Next

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.

8.10 String manipulation


A string is a piece of text. This could be made up of characters, numbers and/or symbols.
There are lots of different string manipulators that you can use; these let you alter
strings, find values in strings, etc. The two you need to know are length and substring.

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

Upper and lower


The characters a-z can be converted into uppercase and the characters A-Z can be
converted into lowercase. This can be done to an individual character, or to an entire
string at the same time. If a character is already in upper case, trying to convert it to
upper case will not change it.
UPPER(string)
LOWER(string)

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

COMPUTER SCIENCE IN CONTEXT

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.

8.11 Nested statements KEY WORD

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

Dim datalnArray As Integer


While number < 10
datalnArray = dataArray(count)
count = count + 1
If datalnArray >= 100 Then
number = number + 1
End If
End While

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

Scope KEY WORDS

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

FUNCTION identifier (parameter!., parameter2 ...)


ENDFUNCTION
If a subroutine is declared with parameters, then it must be called with the same
number of parameters. For example:
PROCEDURE Total(Numl, Num2 )
ENDPROCEDURE
This has two parameters. When the procedure is called it must have 2 numbers sent to
it. This could be numbers, e.g.
Total(1,2)
or variables, e.g.
Total(Numberl, Number2)

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

firstNumber = int(input("Enter the smallest number"))


SecondNumber = int(input("Enter the largest number"))
OutputNumbers(firstNumber, SecondNumber)

Java
public static void OutputNumbers(Integer numl, Integer num2){
for(Integer count = numl; count <= num2; count++){
System.out.printin(count);
8 Programming

public static void main(String args[]){


Scanner scanner = new Scanner(System.in);
System.out.printin("Enter the smallest number");
Integer firstNumber = Integer.parselnt(scanner.nextLine());
System.out.printin("Enter the largest number");
Integer secondNumber ^Integer.parselnt(scanner.nextLine());
outputNumbers(firstNumber, secondNumber);
}

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.

8.13 Library routines


A program library is a set of subroutines that are pre-written and that can be called
within a program.
In some programming languages the operators for MOD and DIV are library functions.
In other programming languages they are just operators. For example, 2 MOD 4 is the
same as MOD (2 , 4). KEY WORD

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

Is there such a thing as a random number? Research how computers generate


random numbers and work out if there is such a thing as a truly random number.
Find out why randomness is important in programming and what the potential
consequences are of having a system that does not generate random numbers.

RANDOM (1, 4) will return a number between 1 and 4.


As with functions, the values it returns and therefore need to be used. This could be by
outputting the return value, or saving it in a variable, e.g.
randomNumber = RANDOM(1, 100)

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

8.14 Maintainable programs KEY WORD


When you write a program there are several things to take into consideration to make it
a maintainable program. This is so that when you come back to it in a week, or a year, maintainable
you can still understand what all of the code does. It might be you are writing a program: a program
program that someone else needs to understand, so you need to make it understandable that has key features
to someone who does not know what the program does. to help it be
understood at a later
date.
Meaningful identifiers
Variables, constants, subroutines and arrays all have identifiers (names). If you call
a variable X, then there is no indication of what it is storing or what its purpose is. If
instead, it is called Total, then you know that it is storing a total.
The identifiers for subroutines are usually descriptions of their function. For example,
a procedure to output the numbers 1 to 10 could be called Functionl, but then there
is no indication of what it does. Instead, it could be called OutputITolO.

Comments KEY WORD

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

//output the first 10 elements in the array


for(Integer count = 0; count < 11; count++){
System.out.printIn(arrayData[count])
}
}

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

'find and output the largest number


If numl > num2 Then
Console.WriteLine(numl)
Else
Console.WriteLine(num2)
End If
8 Programming

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

8.15 Arrays KEY WORDS


An array is a data structure. It allows you store multiple pieces of data in one structure array: a data
with one identifier. In an array, each data item must be of the same data type. If it structure where you
stores integers, then all values must be integers. If it stores strings, then all values must can store multiple
be strings. data items, of the
same data type,
under one identifier.
1-dimensional arrays 1-dimensional array:
A 1-dimensional array has just one row of data. an array that has only
The best way to visualise an array is with a table: one index.

index: the number


Index 0 1 2 3 4
of the space in the
Data 10 5 90 26 87 array.

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.

Putting data into an array


You need to know the array identifier and the position where you want to store the
data.

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

Getting data out of an array


To access data in an array you need to know the identifier and the position of the data
you want. This will be a value, so you need to do something with this value, e.g. store it
in a variable.

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

Using variables as indices


The index in the array might be a variable that stores a number.

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

Using iteration to read and write


If you have a set of values in an array you can use iteration to loop through each of
the elements in turn. For example, you might want to output all of the values one at a
time. You could add together all of the values in an array and output the total. You
might want to take 10 values in from the user and store each one in the array.
These are all best done using a count-controlled loop. This is because you usually
know how many values you want to enter, or how many values there are in the array
that you want to work through.

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

Scanner scanner = new Scanner(System.in);


Integer ValueToFind = Integer.parselnt(scanner.nextLine());

276 y
8 Programming

for(Integer count = 0; count < 50; count++){


System.out.printIn("Enter a number");
if(values[count] == valueToFind){
System.out.printIn("Found it");
}

2-dimensional arrays KEY WORD

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,

Putting data into an array


You need to know which position, i.e. both indices, the across and the down.

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

Getting data out of an array


You need to know both indices to access the data.

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

Using variables as indices


Each index can be stored in a variable in the same way as they can be in a ID array.

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

indexl = int(input("Enter dimension 1"))


index2 = int(input("Enter dimension 2"))
data = arrayData[indexl][index2]

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

Using iteration to read and write


Due to the two dimensions, you need two nested loops to read through all the data
elements. If you think about the table again, one loop goes through the columns and
one loop goes through the rows.
The first loop will check row 1. The column will change from 0, 1,2, 3, 4. The row will
stay the same at 0.

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

It is best to use count controlled loops to go through the array.


It has the structure:
FOR row «- first index to last index
FOR column <- first index to last index
Code to run
NEXT row
NEXT count

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

for row in range(0, 3):


for column in range(0, 10):
print(arrayData[row][column]

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

8.16 File handling


If you have data in a program, when you stop or close a program all of that data is KEY WORD
lost. If you need to save data to use again later then you need to save it externally into a
text file. The storage and access of data in a file is called file handling. file handling:
programming
statements that
COMPUTER SCIENCE IN CONTEXT
allow text files to be
When playing computer games, for example, on an X-Box or PlayStation, opened, read from,
you are able to save the game and then continue from the same point next written to and closed.
time. It does this by saving data about your current progress in a file. When
your program saves, this data is updated; it might store your current position,
health, points, money, etc. When you restart the program, it goes to this file
and loads the data. This lets you start playing at the exact point you left it.

Reading from a file


You need to be able to read a single item of data, or a single line of text. This means
all of the data will be on the first line in the text file, so you do not need to check
how many lines of text are in the file. Once you have read in the data you can then
manipulate it, for example, if it is a line of text you can split it into individual words, or
use it as one item of data.
To read a value from a file you need to:
• Open the file using its filename (the filename will be a string value).
• Read the data value, and do something with it (e.g. output it, store it in a variable).
• Close the file.
You can use the pseudocode commands:
OPEN filename
variable identifier «- READ ( filename)
CLOSE filename

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

PROGRAMMING TASK 8.5

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

An array can be 1-dimensional (one index) or 2-dimensional (two indices).


Iteration can be used to read data to, or from an array, by visiting each index in turn.
Files can be used to store data once a program has finished running.

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.

Statement True False Invalid


if(10 < 20)
if(100 > < 2)
if (5 >= 5)
if(9 <= 8)
x «- 1
y - 3
if(x = y)
numl <- 100
num2 <- 2 00
i f(numl and num2)
valuel <-7 0
value2 <- 190
if(valuel <> value2)
[7]
6 The 2-dimensional integer array, numbers , has 10 elements by 20 elements.
Write an algorithm to initialise all of the elements to a random integer
value between 1 and 100. [4]
7 A program stores the x and y coordinates of a character in a game.
The function move () takes an x coordinate as a parameter. It asks
the user to enter a movement (left or right) and changes the coordinate:
• Right increases the coordinate by 1.
• Left decreases the coordinate by 1.
The function then returns the result.
a State why move () is a function and not a procedure. [1 ]
b The function move loops until the user enters either right or left.
Write the function move () . [7]
[Total: 8]
8 Complete the table by stating how each of the features helps the
maintainability of a program.

Feature How it aids maintainability


Comments
Meaningful identifiers
[2]
9 A procedure twelve () reads an integer number from the text file
number . txt (e.g. 5). It then outputs the 12 times table for that number
(e.g. 5x1, 5x2 etc.).
Write the procedure twelve () . [6]

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

1 can... See Needs Getting Confident


topic more work there to move on
use variables and constants. 8.1
learn about the appropriate use of basic data types. 8.2
write programs that use input and output. 8.3
8.4

write programs that use sequence, selection and iteration 8.5


including nested statements. 8.6
8.7
write programs that use arithmetic, logical and Boolean
8.4
operators.
8.4
write programs that use totalling and counting. 8.8
8.9
write programs that perform the string handling methods. 8.10

write programs that use purpose of procedures and 8.11


functions, including parameters and variable scope. 8.12
write programs using library routines. 8.13
create maintainable programs. 8.14
understand the use of arrays (1-dimensional and
8.15
2-dimensional) as data structures.
write programs to read data from and write data to a file. 8.16

294 y
> Chapter 9

IN THIS CHAPTER YOU WILL

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?

9.1 Database structure


Introduction to databases KEY WORDS

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?

Data types KEY WORD

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"

These are always speech marks around the data. "Hi!!"


Character A single letter, symbol or number. "H"
If it is a number it will be treated as text, i.e. you V
cannot add to it.
"1"
KEY WORDS
Boolean One of two options usually True / False or Yes / True Boolean: a data type.
No. True or False.
False
The data does not have speech marks around it. integer: a data type.
Integer A whole number. 123 Whole numbers.

999 real: a data type.


Decimal numbers.
0
-1928
Real A number with at least one decimal place. 0.0
1.2
9.99
100.92
-2.9384
Date/time A date and/or a time. 1/1/2020
8:30
2/3/2020 16:00
Table 9.1: Database data types

298 >
9 Databases

Primary key KEY WORD


A primary ke\ is a unique field in a database. This means that it cannot appear twice in primary key: a
different records. It is used to uniquely identify a record. For example, if you want to unique identifier for a
find a specific person in a database and you enter their name, there could be dozens of record.
people with the same name. If they had an ID number that is unique to only them,
then you can access their record straight away.
Look at this database again:

Book Name Author Publisher Genre Fiction


Picking daisies J. Frank Cambridge Gardening False
horticulture
Night stars K. Mars Si-fi books Science fiction True
Dreaming of the sun P. Yu Si-fi books Science fiction True
Cooking for fun W. Crisp Cookery Cookery False
penguin

Could any of these five fields be unique?


• Book name: there could be two books with the same names.
• Author: one author could write more than one book.
• Publisher: one publisher could publisher more than one book.
• Genre: more than one book could have the same genre.
• Fiction: more than one book could be False, and more than one could be True.
This means that none of these fields is a suitable primary key. So instead we add a
key field:

Book ID BookName Author Publisher Genre Fiction


1 Picking daisies J. Frank Cambridge Gardening False
horticulture
2 Night stars K. Mars Si-fi books Science True
fiction
3 Dreaming of the P. Yu Si-fi books Science True
sun fiction
4 Cooking for fun W. Crisp Cookery Cookery False
penguin

The field Book ID becomes the primary key.

Defining a single-table database


To define a single-table database you will need to decide:
1 the fields that you need
2 the data types for each field
3 the primary key.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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:

1. Identify the fields that you need


Read the description again and for each item it describes select a field name.

Description Field name


Each item has; a name, e.g. "Sparkle" Item name
a colour, e.g. "red" Colour
a weight, e.g. 2 Weight
a price, e.g. $3.99 Price
a quantity in stock, e.g. 23. Quantity

2. Identify the data types for each field


Look at the example data and the description and select the most appropriate data type
from the table.

Field name Explanation Data type


ItemName "Sparkle" - this is letters therefore string or character. Text
There is more than one letter so it is not character.
Colour "red" this is letters and there is more than 1 character. Text
Weight 2 - this is numeric, there is no decimal so it is not real. Integer
Price $3.99 - this is numeric, there is a decimal so it is not Real
integer.
Quantity 23 - this is numeric, there is no decimal so it is not Integer
real.

3. Identify a primary key


None of these fields are unique, you could have two with the same name, same colour,
etc. Therefore a new ID field needs adding to become the primary key.

Field name Data type


IDNumber Text
ItemName Text
Colour Text
Weight Integer
Price Real
Quantity Integer
9 Databases

Questions
1 Complete the table by giving an example of each type of data.

Data type Example


Boolean
Integer
Text
Character
Real
Date/time
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

2 Describe the format of a database table.


3 Identify the purpose of a primary key.
4 a A social media website stores the following information about its users:
username (e.g. daisyl23), password (e.g. HWHRU2D), online name
(e.g. Daisy), date account created (e.g. 9/9/2019), number of friends (e.g. 38).
Identify the fields and data types for a single-table database for the website,
b Identify an appropriate primary key for the table.

9.2 SQL KEY WORDS


SQL stands for Structured Query Language. This is a standard language that is used Structured Query
across most types or database to perform actions such as: Language (SQL): a
• define tables standard language
used to define
• change tables and manipulate
• add data to tables databases.

• search for data from tables (query) script: a set of


statements that are
• perform calculations using data from tables. executed.
In this specification you only need to know the last two of these: search for data and
perform calculations using data.
When you write some SQL code you are writing an SQL script. This is series of
statements that are commands that are then executed and one or more values are
returned.

9.3 SELECT ... FROM


This allows you select a set of fields from a table. All of the data in each field will be
returned.
This table is called Books.

Book ID BookName Author Publisher Genre Fiction


1 Picking daisies J. Frank Cambridge Gardening False
horticulture
2 Night stars K. Mars Si-fi books Science fiction True
3 Dreaming of P. Yu Si-fi books Science fiction True
the sun
4 Cooking for fun W. Crisp Cookery Cookery False
penguin

Select has the format:


SELECT field
FROM table

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.

Picking daisies Gardening


Night stars Science fiction
Dreaming of the sun Science fiction 4
Cooking for fun Cookery

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:

Picking daisies J. Frank


Night stars K. Mars
Dreaming of the sun P. Yu
Cooking for fun W. Crisp

303 y
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

whereas:
SELECT Author, BookName
FROM Books
will return author then book name:

J. Frank Picking daisies


K. Mars Night stars
P. Yu Dreaming of the sun
W. Crisp Cooking for fun

COMPUTER SCIENCE IN CONTEXT

SQL is known as a standard. This means that it is used (almost) universally,


no matter what software you are using, or type of database. This means that
anyone who knows SQL can use any type of database simply by entering the
same SQL code.

Questions
These questions use the following database table, PRODUCTS, about products for sale
in a shop.

ID number Name Type Cost Quantity in stock


12GH Saturn Chocolate 0.56 100
59RF Vanilla Fudge 1.99 20
3WR Peanuts Nuts 2.56 2
52D Jazz Fruit 0.23 33
6SE Signet Fudge 1.48 5

5 Write the results returned by the following SQL script:


SELECT ID number
FROM PRODUCTS
6 Write the results returned by the following SQL script:
SELECT Name, Type
FROM PRODUCTS
7 Complete the SQL script to display the prices of all the products.
SELECT
FROM PRODUCTS
8 Complete the SQL script to display the ID number and name of all the products.
ID Number,
FROM PRODUCTS

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

9.4 SELECT ... FROM ... WHERE


Including a WHERE clause in the SELECT statement allows you to select only specific
data. For example, you only want gardening books, or items that cost more than $3.00.

Single condition (single WHERE) KEY WORD

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

The following queries will use the following table, Orders:

Order ID FirstName LastName Numberitems TotalCost Posted


1A Qirat Raja 20 21.99 No
1B Simon Tong 2 3.99 Yes
1C Mei Liu 1 6.00 Yes
1D Jenny Silver 29 59.65 No

Select where has the format:


SELECT SUM field
FROM table
WHERE condition
Equal to
SELECT FirstName, LastName, Posted
FROM Orders
WHERE Posted = Yes
This will return:

Simon Tong Yes


Mei Liu Yes
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

10 Write the results returned by the following SQL script:


SELECT Student ID, Subject
FROM MARKS
WHERE Subject = "Programming 2"
11 Write the results returned by the following SQL script:
SELECT Student ID, Subject, Grade
FROM MARKS
WHERE Grade = "Pass"
12 Complete the SQL script to display the Test name, percentage and grade where the
percentage is more than 50.
Test name, Percentage,
FROM
WHERE Percentage
13 Complete the SQL script to display the student ID, subject and percentage where
the subject is Science.
SELECT Student ID,
MARKS
SUBJECT =
14 Complete the SQL script to display the student ID, test name and percentage
where the percentage is less than or equal to 25.
Test name, Percentage

KEY WORD

WHERE Boolean operator:


a symbol that joins
More than one condition multiple logical
comparisons, can be
Combining conditions requires a Boolean operator between the conditions. These are AND OR or NOT.
similar to those that you used in programming (Table 9.3).
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Operator Description Example WHERE


AND Only data that WHERE Fiction = TRUE AND Cost < 3.99.
meets both
conditions will
be returned. Only records where Fiction is TRUE and Cost is less
than 3.99 will be displayed.
OR Data that meets WHERE Fiction = TRUE OR Cost < 3.99.
one condition,
or both
conditions will Any records where Fiction is TRUE will be returned.
be returned. Any records where Cost < 3.99 will be returned.
If a record meets both then this will be returned
only once.
Table 9.3: Boolean operators

Multiple conditions have the format:


SELECT field
FROM table
WHERE conditionl logical operator condition2
The following queries will use the following table, Orders:

Order ID FirstName LastName Numberitems TotalCost Posted


1A Qi rat Raja 20 21.99 No
1B Simon Tong 2 3.99 Yes
1C Mei Liu 1 6.00 Yes
1D Jenny Silver 29 59.65 No
AND
SELECT Order ID, Numberitems, Posted
FROM Orders
WHERE Numberitems > 1 AND Posted = Yes
This query returns:

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

Selecting values in, or not in, a condition


The fields in the SELECT do not need to include those in the WHERE.
Example:
SELECT FirstName, LastName
FROM Orders
WHERE Posted = Yes
This will return the first name and last name of orders where posted is true. It does not
return the field posted. It will return:

Simon Tong
Mei Liu

COMPUTER SCIENCE IN CONTEXT

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.

Date Time Temperature Wind speed Humidity


11/12/2019 10:00 20.3 22 59
11/12/2019 13:00 23.7 15 63
11/12/2019 15:00 24.0 13 61
11/12/2019 18:00 23.9 16 60
12/12/2019 15:00 18.4 20 52
12/12/2019 18:00 17.2 18 48

15 Write the results returned by the following SQL script:


SELECT Temperature, Wind speed, Date
FROM WEATHER
WHERE Date = 11/12/2019 AND time < 15:00
16 Write the results returned by the following SQL script:
SELECT Date, Time, Humidity
FROM WEATHER
WHERE Temperature > 20 AND Wind speed < 20
17 Write the results returned by the following SQL script:
SELECT Date, Time
FROM WEATHER
WHERE Temperature > 20 OR Wind speed >= 20

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:

Order ID FirstName LastName Numberitems TotalCost Posted


1A Qirat Raja 20 21.99 No
1B Simon Tong 2 3.99 Yes
1C Mei Liu 1 6.00 Yes
1D Jenny Silver 29 59.65 No

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.

Date Time Temperature Wind speed Humidity


11/12/2019 10:00 20.3 22 59
11/12/2019 13:00 23.7 15 63
11/12/2019 15:00 24.0 13 61
11/12/2019 18:00 23.9 16 60
12/12/2019 15:00 18.4 20 52
12/12/2019 18:00 17.2 18 48
20 Write the results returned by the following SQL script:
SELECT Temperature, Wind speed, Date
FROM WEATHER
ORDER BY Temperature
21 Write the results returned by the following SQL script:
SELECT Date, Time, Temperature
FROM WEATHER
ORDER BY Humidity DESC
22 Complete the SQL script to display the date, wind speed and humidity in
ascending order of wind speed.
Date, Wind speed, Humidity
WEATHER
Wind speed
23 Complete the SQL script to display the date, time and temperature, in descending
order of humidity.
SELECT Date, Time,
FROM WEATHER
ORDER BY
24 Complete the SQL script to display the temperature, wind speed and humidity in
descending order of temperature.
Wind speed,
FROM

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

You can also use WHERE conditions, e.g.


SELECT SUM(field)
FROM table
WHERE condition
The following queries will use the following table, Orders:

Order ID FirstName LastName Numberitems TotalCost Posted


1A Qirat Raja 20 21.99 No
1B Simon Tong 2 3.99 Yes
1C Mei Liu 1 6.00 Yes
1D Jenny Silver 29 59.65 No

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:

Order ID FirstName LastName Numberitems TotalCost Posted


1A Qirat Raja 20 21.99 No
1B Simon Tong 2 3.99 Yes
1C Mei Liu 1 6.00 Yes
1D Jenny Silver 29 59.65 No
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

SKILLS FOCUS 9.1

SUM AND COUNT

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

Order ID Customer ID Total


1 6 20.00
2 2 16.25
3 8 8.99
4 2 3.00
5 4 11.50

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.

Order ID Customer ID Total


1 6 20.00
2 2 16.25
3 8 8.99
4 2 3.00
5 4 11.50
There are two records with Customer ID 2. The total for these two records are
added together.
16.25 + 3.00= 19.25
The SQL script will return:
19.25
COUNT
This counts the number of records (rows). This is not related to the values in the
fields, just how many records there are that meet the criteria.
Example 1, a set of data.
1,3,8, 9, 3. There are 5 values.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

Example 2, a table of data.

10
2
9
30
4
5
There are 6 values
Example 3, an SQL query.
This query will use the following table, SALES.

Order ID Customer ID Total


1 6 20.00
2 2 16.25
3 8 8.99
4 3 3.00
5 4 11.50
SELECT COUNT(Total)
FROM SALES
The command word COUNT tells you that you are counting records. The field in the
brackets, Total, tells you which to count.
20.00, 16.25,8.99,3.00, 11.50
The value returned will be: 5
When you are answering questions such as what does this script return when COUNT
is being used, the only answer is the number. In Example 3, the answer to the
question would just be: 5
Example 4, table with criteria using the table SALES.
SELECT COUNT(Total)
FROM SALES
WHERE Customer ID = "2"
This time there is a criteria. Only records with Customer ID being 2 are needed.

Order ID Customer ID Total


1 6 20.00
2 2 16.25
3 8 8.99
4 2 3.00
5 4 11.50
9 Databases

CONTINUED

Count how many records have Customer ID 2. There are 2 records.


The SQL script will return:
2

Questions
These will use the following table, PRODUCTS:

ID number Name Type Cost Quantity in stock


12GH Saturn Chocolate 0.56 100
59RF Vanilla Fudge 1.99 20
3WR Peanuts Nuts 2.56 2
52D Jazz Fruit 0.23 33
6SE Signet Fudge 1.48 5

1 What is the difference between SUM and COUNT?


2 What will be returned when the following SQL script is run?
SELECT SUM(Quantity in stock)
FROM PRODUCTS
3 What will be returned when the following SQL script is run?
SELECT COUNT(ID number)
FROM PRODUCTS
4 What will be returned when the following SQL script is run?
SELECT SUM(Cost)
FROM PRODUCTS
WHERE Quantity in stock > 10
5 What will be returned when the following SQL script is run?
SELECT COUNT(Name)
FROM PRODUCTS
WHERE Cost < 2.00

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

How did you


approach
Programming Task
9.3? Did you have
other queries with
you to check your
syntax and to help
you answer the
questions? How
will you make sure
you remember the
commands?
9 Databases

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

25 Write the results returned by the following SQL script:


SELECT SUM(NumberIterns)
FROM ORDERS
26 Write the results returned by the following SQL script:
SELECT COUNT(NumberIterns)
FROM ORDERS
27 Write the results returned by the following SQL script:
SELECT COUNT(Numberitems)
FROM ORDERS
WHERE NumberIterns > 10
28 Write the results returned by the following SQL script:
SELECT SUM(TotalCost)
FROM ORDERS
WHERE FirstName = "Keanu"
29 Complete the SQL script to display how many orders James Smith has made.
SELECT (FirstName)
FROM ORDERS
WHERE FirstName = "James" LastName =
"Smith"
30 Complete the SQL script to calculate the total cost of orders where 5 or more
items have been ordered.
SELECT (TotalCost)
FROM ORDERS
NumberIterns 5
31 Complete the SQL script to calculate how many orders cost more than 50.00
SELECT (Numberitems)
FROM
WHERE
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

SUMMARY

A database stores data about objects such as items, people, orders.


A field is one piece of data in a table.
A record is a set of fields about one object.
Each field has a data type.
The text or alphanumeric data type stores any combination of letters, numbers and symbols.
The character data type stores one letter, number or symbol.
The Boolean data type stores one of two values, either True or False.
The Integer data type stores whole numbers.
The real data type stores decimal numbers.
The date/time data type can store a date, time, or a date and time.
A primary key is a unique identifier in a table.
A primary key is used to uniquely identify each record.
SQL stands for Structured Query Language and is a standard for querying databases.
SELECT . . . FROM returns all the data in the field given.
SELECT . . . FROM . . . WHERE returns all the data in the field where the WHERE condition is true.
ORDER BY can be ASC (ascending) or DESC (descending) and will return the data in the order specific
by the field given.
SUM will total the values in the given field.
COUNT will return how many records meet the criteria.

EXAM-STYLE QUESTIONS COMMAND WORDS

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

4 A hairdressers uses a database, APPOINTMENTS, to store upcoming


CONTINUED
appointments. Part of this database is shown:
Appoint­ Date Time Emplo­ Customer Customer Appoint­
ment ID yee ID first name last name ment type
12 1/2/2020 14:00 JP James Smith Cut
13 1/2/2020 14:30 AD Ajay Gupta Cut and dry
14 1/2/2020 16:00 AD Eka Loke Colour
15 1/2/2020 9:45 JP Keanu Kawai Cut and dry
16 2/2/2020 11:15 JP Ariana Wang Cut
17 2/2/2020 12:30 AD Osandi Bandara Colour COMMAND WORDS

a Identify how many records are in the table. [1 ] identify: name I


b Identify how many fields are in the table. [1 ] select I recognise.
c State what is meant by a primary key, and identify the primary state: express in
key in the table APPOINTMENTS. [2] clear terms.
d Identify the output from this SQL script:

SELECT EmployeelD, Appointment type


FROM APPOINTMENTS
[2]
e Identify the output from this SQL script:
SELECT COUNT(AppointmentID)
FROM APPOINTMENTS
WHERE Appointment type = "Cut"
[1]
f Complete the SQL script to return the first and last name of all
customers with appointments on 1/2/2020.

Customer first name, Customer last name


FROM APPOINTMENTS
WHERE
[4]
g Complete the SQL script to return the number of appointments JP
has on 1/2/2020.

SELECT (Employee ID)


APPOINTMENTS
Employee ID
[5]
[Total: 16]
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

5 A single-table database, SALES, stores details of people who have bought


books online.
Sales ID Book ID Date Customer ID Quantity bought Total Cost
5 10 3/3/2020 1GHF2 1 6.99
6 151 3/3/2020 34FDD 2 10.00
7 230 3/3/2020 34FDD 1 12.00
8 230 3/3/2020 1GHF2 1 12.00
9 10 3/3/2020 P0OO1 2 13.98
10 88 4/4/2020 15DTB 2 10.50
11 209 4/4/2020 1GHF2 3 12.00
12 151 4/4/2020 34FDD 5 25.00
13 28 4/4/2020 34FDD 2 20.00
a Identify the most appropriate data types for the following fields:
• Sales ID
• Date
• Customer ID
• Quantity bought
COMMAND WORD
• Total Cost [5]
b Give the result from the following SQL script: give: produce an
answer from a given
SELECT Date, CustomerlD source or recall /
FROM SALES memory.
WHERE CustomerlD = "1GHF2"
[2]
c Complete the following SQL script to return the customer ID and
total cost of each order where more than 1 book were ordered.

SELECT Customer ID,


FROM
WHERE Total Cost
[4]
d Give the result from the following SQL script.

SELECT Sales ID, BookID


FROM SALES
WHERE Date =4/4/ 2020 AND Total Cost <= 15
[2]

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

See Needs Getting Confident


lean...
topic more work there to move on
learn about the structure and components of a
9.1
single-table database.
identify the fields necessary for a single-table database. 9.1
identify appropriate data types for specific data and
9.1
fields.
identify an appropriate primary key for a table. 9.1
understand the purpose of SQL scripts. 9.2
read and complete SQL scripts that use SELECT
9.3
FROM
read and complete SQL scripts that use SELECT
9.4
FROM WHERE.
read and complete SQL scripts that use ORDER BY. 9.5
read and complete SQL scripts that use SUM. 9.6
read and complete SQL scripts that use COUNT. 9.7
IN THIS CHAPTER YOU WILL:

know the standard symbols for a range of different logic gates


understand the function of each different logic gate
represent a logic circuit using a truth table and a logic expression
represent a truth table as a logic expression and a logic circuit
represent a logic expression as a logic circuit and a truth table

represent a problem statement as a logic expression, logic circuit and a truth table
10 Boolean logic

GETTING STARTED

Electricity flows through the components of a computer so that it is able to


operate. This electricity needs to be controlled in some way so that binary
data can be represented.
Pretend you are in an elevator and your favourite person walks in. You
have 30 seconds to impress them before you arrive at your floor with your
knowledge about how a computer controls the flow of electricity. Try and think
about everything you know about this already and practise your 30 second
speech with your friend now. Ready, steady, go!

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.

Figure 10.1: Logic gates have an output that is either 0 or 1

325 >
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

10.1 The role of logic gates


You learnt in Chapter 1 how data is converted from analogue data to digital data so
that it can be processed by a computer. Therefore, you understand that the data that
is processed by a computer has two values, 0 and 1. A computer is provided with
electricity to function and it needs a way to change this electricity from high voltage
(1) to low voltage (0) and vice versa, to be able to represent each binary value that is
required. It can do this through the use of logic gates. The reason why this chapter is
called Boolean logic is because a Boolean value only has two different states, e.g. true
or false, or in a logic gate’s case 0 or 1.
Logic gates can have several inputs and depending on the type of logic the gate uses,
it will change these inputs in one single output. All the logic gates that you will learn
about will have a maximum of two input values.
A computer uses thousands of logic gates to output the high or low voltage that is
needed to process and store the large quantity of data that it is provided with on a
daily basis. The logic gates that you will learn about are the NOT, AND, OR, NAND,
NOR and XOR gates.

10.2 The NOT logic gate


The NOT gate is the simplest logic gate. This logic gate has only one input and
one output. It is used to reverse the input into the gate to output the opposite value.
So, if high voltage (1) is input, the output will be low voltage (0). If low voltage (0)
is input, high voltage (1) is output.
Figure 10.2 shows how to draw a NOT logic gate:

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

3 Write the logic expression for a NOT logic gate.

10.3 The AND logic gate


The AND logic gate has two inputs and one output. The only time the output is 1
is when both the inputs are 1. A fun way to think about logic gates is that they are
a doorway that has a guard. You and your friend are the inputs and you need the
output to be high voltage (1) for the guard to allow you to be able to pass through the
doorway. The criteria the guard has set for you to be able to get through the doorway
for an AND logic gate is that you and your friend must both have a ticket. If neither
of you has a ticket, or only one of you has a ticket, then you will not be allowed
through the doorway.
Figure 10.3 shows how to draw an AND logic gate:

Output

Figure 10.3: An AND logic gate


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

The logic expression for an AND logic gate is:


X = AAND B
An alternative notation for an AND gate is:
X = A.B
The dot symbol (.) between the A and the B represents the AND in this expression.

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

6 Write the logic expression for an AND logic gate.

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

10.4 The OR logic gate


The OR logic gate has two inputs and one output. The output is 1 when either or
both the inputs are 1. The criteria the guard has set for you this time to be able to get
through the doorway for an OR logic gate is that you or your friend must have a ticket,
but both of you don’t need one. If neither of you has a ticket, then you will still not be
allowed through the doorway.
Figure 10.4 shows how to draw an OR logic gate:

Input 1
Output
Input 2
Figure 10.4: An OR logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X.


This is a completed truth table for an OR gate:

A B X
0 0 0
0 1 1
1 0 1
1 1 1

The logic expression for an OR logic gate is:


X = A OR B
An alternative notation for an OR gate is:
X = A+B
The plus symbol (+) between the A and the B represents the OR in this expression.

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

9 Write the logic expression for an OR logic gate.


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

10.5 The NAND logic gate


The NAND logic gate has two inputs and one output. The output is 1 when either
input is 0 or one of the inputs are 1. If both inputs are 1, the output is 0. The criteria
the guard has set for you this time to be able to get through the doorway for a NAND
logic gate is that if both you and your friend are wearing trainers, you will not be
allowed through the doorway. If neither of you, or only one of you is wearing trainers,
then you will be allowed through the doorway.
Figure 10.5 shows how to draw a NAND logic gate:

Output

Figure 10.5: A NAND logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X.


This is a completed truth table for a NAND gate:

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.

COMPUTER SCIENCE IN CONTEXT

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

12 Write the logic expression for a NAND logic gate.

10.6 The NOR logic gate


The NOR logic gate has two inputs and one output. The only time the output is 1 is
when both inputs are 0. The criteria the guard has set for you this time to be able to get
through the doorway for a NOR logic gate is that neither of you are wearing trainers.
If either or both of you are wearing trainers, then you will not be allowed through
the doorway.
Figure 10.7 shows how to draw a NOR logic gate:

input2 ZT^Output

Figure 10.7: A NOR logic gate


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

Input 1 is labelled A, input 2 is labelled B and the output is labelled X.


This is a completed truth table for a NOR gate:

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

Figure 10.8: A NOR gate is simplification of an OR gate and a NOT gate

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

15 Write the logic expression for a NOR logic gate.


10 Boolean logic

10.7 The XOR logic gate


The XOR logic gate is also known as the EOR gate. This is because it is known as the
exclusive OR gate. It has two inputs and one output. The only time the output is l is
when one of the inputs is 1. If both inputs are 0 or 1, then the output is 0. The criteria
the guard has set for you this time to be able to get through the doorway for a XOR
logic gate is that one of you is wearing trainers. If neither or both of you are wearing
trainers, then you will not be allowed through the doorway.
Figure 10.9 shows how to draw a XOR logic gate:

Figure 10.9: An XOR logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X.


This is a completed truth table for an XOR gate:

inputs are 1, the output is 0.


The logic expression for a XOR logic gate is:
X = AXOR B
An alternative notation for an XOR gate is:
X = A©B
The plus symbol (+) within a circle, between the A and the B, represents the XOR in
this expression.

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

18 Write the logic expression for an XOR logic gate.


y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

SKILLS FOCUS 10.1

REPRESENTING LOGIC CIRCUITS

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.

Figure 10.11: A simple logic circuit with labels D and E added


10 Boolean logic

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

10.8 Logic expressions


You need to be able to write a logic expression for a logic circuit. The first thing you
need to do to be able to write this is to break down the different parts of the logic
circuit. Let’s look at the logic circuit in Figure 10.14 as an example:

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:

Figure 10.16: Find the logic expression for this circuit

20 Write the logic expression for the given logic circuit:

10.9 Representing truth tables


You have learnt how to complete a truth table for a logic expression and a logic circuit.
You now need to learn how to write a logic expression and draw a logic circuit from a
truth table.

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

Looking at the truth table again:

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)

Let’s look at another truth table:

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

Let's look at the first row with an output of 1 in the table:

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:

X = (NOT A AND NOT B AND C) OR (A AND NOT B AND C) OR (A AND B AND C)


A person would normally look to then simplify this statement, but you do not need to
understand how to do this. You could research how to do this though if you wanted
to give yourself a challenge.
The second method you could use looks for the constant values in each row where the
output is 1.
10 Boolean logic

Let’s look at another truth table:

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

a Write a logic expression to represent the given truth table,


b Draw a logic circuit to represent the given truth table.

10.10 Representing logic expressions


You need to be able to look at a logic expression and create a logic circuit and a truth
table from the expression.
Let’s look at a simple logic expression:
Z =(R AND S) OR (R AND T)
You should notice that this logic expression has:
• 3 input values: R, S and T
• an output value of Z
• uses the logic gates AND and OR.
If you look at the brackets you can see that the expression has two main parts that are
joined together by an OR gate. You should learn from this that the OR gate will be the
final gate in the logic circuit. You can the draw this part of the circuit (Figure 10.20): Figure 10.20: The logic
circuit for the expression
You the need to look at the parts of the expression that are in the brackets. Each
Z = (something) OR
bracketed section is an input into the OR gate that you have drawn. This means that
(something)
the first input to the OR is the output of R AND S (Figure 10.21):

Figure 10.21: The logic circuit for the expression Z = (R AND S) OR (something)

344 )>
10 Boolean logic

The second input to the OR is the output of R AND T (Figure 10.22):

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

Let’s look at another logic expression:


X =((A AND B) OR NOT C) XOR (B NOR C)
You should notice that this logic expression has:
• 3 input values: A, B and C
• an output value of X
• uses the logic gates AND, OR, NOT, XOR and NOR.
You can use the same method as before to structure the logic circuit. You should be
able to see again that the expression has two main bracketed sections. You will also Figure 10.23: The logic
notice this time that one of those bracketed sections has brackets within it as well. circuit for the expression
First, you should notice that the final logic gate in the logic circuit will be an XOR gate. X = (something) XOR
You can now begin to draw the circuit (Figure 10.23): (something)
If you look at the larger bracketed area to the left of the XOR in the statement you
can begin to break this down. This will become the first input for the XOR gate. The
bracketed section within this is A AND B. The brackets around this mean that the
output of A AND B needs to become the input of the remaining part of this whole
section. The remaining part is OR NOT C. What you should learn from this is that the
output on A AND B will become the input to an OR gate and that the second input to
the OR gate will be NOT C. You can now continue to draw the circuit (Figure 10.24):

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

10.11 Representing problem


statements
The final thing you need to be able to do is to write a logic expression, draw a logic
circuit and complete a truth table for a problem statement.
A problem statement is when a logic problem is described in natural language and you
are given criteria for the logic of the problem within that description.
An example of a problem statement is:
A factory manufactures soap and has a system that monitors the manufacturing
process. The system has three conditions to monitor the acidity (A) the temperature (T)
and the pressure (P).
The conditions for the system are:

Input Binary value Condition


A 1 pH<=7
0 pH>7
T 1 Temperature < 50 °C
0 Temperature >= 50 °C
P 1 Pressure >=75%
0 Pressure <75%

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

COMPUTER SCIENCE IN CONTEXT

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!

EXAM-STYLE QUESTIONS COMMAND WORD

1 State the purpose of a logic gate in a computer system. [1 ] state: express in


2 Draw the single logic gate that would generate the given truth tables: clear terms.

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

3 Consider the truth table:

A B X
0 0 1
0 1 0
1 0 1
1 1 1

a Write a logic expression to represent the given truth table, [4]


b Draw a logic circuit to represent the given truth table. [4]
[Total: 8]
4 Consider the truth table:

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

Write a logic expression to represent the given truth table. [5]


5 Consider the logic circuit:

a Write a logic expression to represent the given logic circuit. [3]

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:

Input Binary value Condition


M 1 Moisture level <>80%
0 Moisture level <=80%
T 1 Temperature >35 °C
0 Temperature <= 35 °C
H 1 Humidity >=65%
0 Humidity < 65%

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*

IN THIS CHAPTER YOU WILL:

analyse problems to create programming solutions


understand how to tackle a large problem
identify the inputs, processes and outputs of a problem
use pseudocode or program code to write solutions for problems.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

GETTING STARTED

Work in pairs to discuss how you tackle a programming problem. What do


you do first? How do you check that you have met all the requirements? What
features do you add to improve the readability of your program?

PLANNING A PROGRAM

Programmers have to tackle programming


problems every day. They have to
analyse the requirements and work out
how to write a program to meet those
requirements, in the same way that you
will need to. The only difference is that
programmers have been doing this process
for a long time, they have practised and
practised. This is the best way to tackle
how to write programs; practice, practice
and more practice. Most programs follow a
pattern, they will have inputs in the system,
they will include processes (actions), and
then output results. The challenge is
working out which order to put these in.
Consider a 3D computer game, where the Figure 11.1: A person playing a computer game
player moves an online character around a
virtual world, interacting with objects and other characters. This system has inputs, processes and outputs.
For example:
• Input: an arrow key from the user (up, down, left, right).
Process: change the characters position depending on the key pressed.
Output: the character in the new position.
From this analysis a program can be written to perform these actions.
The larger the problem, the more likely a design will need to be created first. This design will identify all
of the requirements of the problem, and begin to identify the inputs, processes and outputs. For some
programs there could be thousands (or more) inputs, processes and outputs. They all need to be identified
to make sure the design covers all the requirements.
The only difference between the process with a large problem, and the problem you will be tackling is the
size. You are only going to need to identify a small number of inputs, processes and outputs and you are
working on your own. A large program could have dozens of programmers, each working on their own part
of the problem.
Discussion questions
1 What might happen if you did not identify all of the requirements before starting to tackle the problem?
2 How do you tackle a problem? Do you just start creating a solution, or do you need to identify the
requirements and components first? Or does this depend on the problem?
11 Programming scenarios practice

11.1 Programming scenario


In the Paper on Algorithms, Programming and Logic, you will be given a scenario
that you need to write an algorithm for to solve the problem. It is important that you
think about the problem and plan before you start writing a solution. This is especially
important to make sure you don’t miss anything that is in the question.
There are then two ways that you could tackle this problem. Which you choose
depends on you and which you prefer.
The first method is identifying the inputs, processes and outputs. The second method
is practically doing the programming task and identifying the steps this way.

COMPUTER SCIENCE IN CONTEXT

Consider your favourite computer game. At some point a programmer had to


identify the inputs, processes and outputs in the game.

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?

11.2 Method 1: Identifying the inputs,


processes and outputs
Identify key features
First read the problem twice before starting to work out what you need to do.

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.

Input Process Output

Identify the inputs from the scenario:

Input Process Output


First integer value.
Operator.
Second integer operator.

Then identify the outputs:

Input Process Output


First integer value. Result from the
calculation.
Operator.
Second integer operator.

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.

Input Process Output


First integer value. If + is entered add the Result from the
values. calculation.
Operator.
If - is entered subtract
Second integer operator. the values.
If * is entered multiply
the values. REFLECTION
If / is entered divide the How did you
values. investigate the
inputs, processes and
if A is entered work out
outputs for Activity
the power of.
11.2? Did you work
through each line of
ACTIVITY 11.2 code at a time, or did
you just focus on the
Open a program you have already written. Identify the inputs, processes and elements you were
outputs for this program. looking for?
11 Programming scenarios practice

11.3 Writing the code


Now you know the inputs, processes and outputs, you need to work out the order.
Usually the inputs come first, and they are a good place to start. Even if can’t identify
the processes yet, always do the inputs - they will help to get your started.
The question will likely say pseudocode or program code, this is to allow you the
freedom of what to use. It does not mean that your code must be syntactically perfect,
but it must use code structures, for example:
For x <- 1 TO 10 is code like, but,
starting with 1 loop until 10 is not code-like, this is English
statements not code statements.

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

Process 1. If + is entered add the values.


IF Operator = " + "
THEN
Result «- Numberl + Number2

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:

Input Process Output

First integer value. If + is entered add the values. Result from the calculation.

Operator. If - is entered subtract the values.


Second integer operator. If * is entered multiply the values.
If / is entered divide the values,
if A is entered work out the power of.

The output is:


OUTPUT "The result is: Result

OUTPUT Numberl , Operator , Number2 , " " , Result TIP


Example - calculator, full code: When outputting
REPEAT data, it is good
Numberl <- INPUT "Enter a number" practice to include a
UNTIL Numberl.islnteger() message to say what
the output is. This is
REPEAT the same in a small
Operator <- INPUT "Enter an operator" pseudocode problem
UNTIL Operator = " + " OR Operator = "-" ( Operator = "*" as in a large program
OR Operator = "/" OR Operator = "A" being created by
many people. If you
REPEAT run a program and
Numberl <- INPUT "Enter a number" it outputs a number
UNTIL Numberl.islnteger() without a message -
how do you know
IF Operator = " + " what that number
THEN means?
Result «- Numberl + Number2
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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.

SKILLS FOCUS 11.1

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

Identify key features


Write down the inputs, processes and outputs for this system.

Inputs Processes Outputs


Word to guess. Store each letter in Letter position if it is array.
different index.
User's letter guess. 'Not in array', if not in array.
Is user's guess letter in
User's word guess. array? 'Correct', if they guess
correctly.
Is user's word guess
correct? They lose if 10 guesses and
incorrect guess.
Count number of times the
user has guessed.
Repeat and stop when 10
letters or word is correct.

Write the inputs


WordToGuess <- INPUT "Enter a 5 character word"
UserLetter «- INPUT "Enter a letter to guess"
UserWord <- INPUT "Enter a word to guess"

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

UserWord <- INPUT "Enter a word to guess"

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

//INPUT user's guesses


REPEAT
UserLetter <- INPUT "Enter a letter to guess"
UNTIL UserLetter.IsCharacter() = TRUE

UserWord <- INPUT "Enter a word to guess"


Second: Is user’s guess letter in array? This will need to check all 5 values in the
array and output the position if it is correct. The most efficient way to do this is to
use a loop.
//INPUT word to guess
REPEAT
WordToGuess <- INPUT "Enter a 5 character word"
UNTIL LENGTH(WordToGuess) = 5

//store characters in array


LetterArray <- [SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 2),
SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess , 3, 1)]
//INPUT user's guesses
REPEAT
UserLetter <- INPUT "Enter a letter to guess"
UNTIL UserLetter.IsCharacter() = TRUE

//check for position of user's guess


FOR Count «- 0 TO 5
IF UserLetter = LetterArray[Count ]
THEN
OUTPUT "Position ", Count
ENDIF
NEXT Count

UserWord <- INPUT "Enter a word to guess"


Third: Is user’s word guess correct? This will involve checking the word input
against the first word and outputting if it is correct.
LetterArray <- [SUBSTRING(WordToGuess , 0, 1), SUBSTRING(WordToGuess, 1, 1),
SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess , 3, 1)]
//INPUT user's guesses
REPEAT
UserLetter «- INPUT "Enter a letter to guess"
UNTIL UserLetter.IsCharacter() = TRUE
CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

WHILE(Count < 10) REPEAT //loop for 10 guesses


//input user's guesses
REPEAT
UserLetter <- INPUT "Enter a letter to guess"
UNTIL UserLetter.IsCharacter() = TRUE

//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"
11 Programming scenarios practice

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?

11.4 Method 2: Practically carrying out


the program and identifying the stages
In this method you walk through the task requirements and then turn the steps that
you followed into an algorithm.

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

Perform the actions


You can do this in sequence, like in the table below. You might want to do it several times with different values:

Requirement Run-through 1 Run-through 2 Steps followed


Take one integer value, from input 10 input 2 INPUT numberl
the user
Take an operator as input; + for input + input A INPUT operator
addition, - for subtraction, /
for division, * for multiplication
or A for power of.
Take a second integer value input 20 input 3 INPUT number2
from the user.
Output the result. output 30 output 8 Check operator and output calculation.
Looking at the steps followed helps you to write the algorithm.
INPUT Number1
INPUT Operator
INPUT Number2
IF Operator = "+"
THEN
OUTPUT Numberl + 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

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

IF Operator = " + "


THEN
OUTPUT Numberl + 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
3 Messages with outputs:
REPEAT
Numberl <- INPUT "Enter the first number"
UNTIL Numberl.Islnteger - TRUE
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

4 Comments to explain the code:


//input the first number
REPEAT
Numberl <- INPUT "Enter the first number"
UNTIL Numberl.Islnteger = TRUE

//input the operator

REPEAT
Operator <- INPUT "Enter an operator"
UNTIL Operator = " + " OR Operator = OR Operator = "*" OR Operator = "/"
OR Operator = "z'"

//input the third number

REPEAT
Number2 <- INPUT "Enter the second number"
UNTIL Number2.Islnteger = TRUE

//check operator and perform calculation


11 Programming scenarios practice

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

SKILLS FOCUS 11.2

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

A program is needed to:


• Ask the user whether they want to see the:
• total number of items sold
• total cost of all items sold
• quantity of items that sold less than 10
• quantity of items that sold more than or equal to 10.
• Calculate the answer to the item selected.
• Output the total with an appropriate message.
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

Write an algorithm in pseudocode or program code to perform these actions.


You do not need to initialise the values in the array.
Walk through the problem

Requirement Run-through 1 Run-through 2 Steps followed


Ask the user OUTPUT "Select 1 for total OUTPUT "Select 1 for total OUTPUT message
what they want number, 2 for total cost, 3 number, 2 for total cost, 3
to see. for items less than 10, 4 for for items less than 10, 4 for INPUT choice.
items more than 10". items more than 10".
Enter 1. Enter 2.
Calculate 1 was chosen, so add up 2 was chosen so calculate If 1 was chosen total items.
answer. total number of items = 5 total cost
+ 6 + 8 + 10 + 2 + 15 + 3 If 2 was chosen, multiply cost by
+ 16+10 cost*quantity for each quantity and total values.
item
If 3 was chosen check if each
10*5 + 15.99 + 6, etc. value is less than 10.
If 4 was chosen check if each value
is more than or equal to 10.
Output answer "The total number of "The total cost is " OUTPUT message depending on
with appropriate items sold is 75". total Cost choice and total value.
message.

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

Step 3 - totalling cost of all items sold.


IF 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
END IF
Step 4 totalling number of items that sold less than 10.
IF 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 NumberIterns
ENDIF
Step 5 totalling number of items that sold 10 or more.
IF 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
Finally combine the code. There are four selection statements that could stay as
separate IF statements, but only one of these will ever run therefore using ELSEIF
will be more efficient.
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
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

This task goes beyond the specification.

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

PROGRAMMING TASKS 11.5

A computer program allows a user to select a username and password.


The array, Logins , has up to 1000 indices to store the current usernames
and passwords. Part of the array is shown:

Username Rainbow Star5 Foxes99 Purple123 Gamer55


Password tidjsrn8 111jdk99 3jck285hkd iii8800sndm a45i12n3

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

This task goes beyond the specification.

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

Amend your program to allow:


The players to play 11 games and output who has won the most.
The player to choose to play another player, or the computer.
The computer will need to make use of random numbers to identify
which move it should make.
Use a file to record a high score and the player who achieved this.
This should be updated, if necessary, after each game.

SUMMARY

Always read the scenario twice before starting.


Walk through the requirements, acting out each statement to identify how the system needs to work.
Identify the inputs, processes and outputs of a system.
Include validation to any inputs.
Use appropriate messages when inputting and outputting data.
Add comments to explain your code.

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

See Needs Getting Confident


1 can...
topic more work there to move on
identify the inputs for a system. 11.2
identify the processes for a system. 11.2
identify the outputs for a system. 11.2
validate input data. 11.3
use appropriate input and output messages. 11.3
add comments to explain my code. 11.3
| Microsoft

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

THE IMPORTANCE OF TESTING IN COMPUTER SCIENCE


If you haven't already, you will learn about the very Students are able to handle the pods and interact with them
important purpose of testing in the development lifecycle to identifying their commands, joining them together to
of a program. Testing is the stage that helps us understand create working algorithms. These algorithms create outputs
whether the program works correctly in all the different such as music and audio stores. This makes programming
ways that it should do. When a company creates a piece accessible to visually impaired or blind students, allowing
of technology, it also needs to thoroughly test that them to learn the basics of programming alongside their
technology to see if it works correctly and to see if it meets sighted peers using block-based languages such as Scratch.
the needs of the user. This can mean that more students have a greater ability to
choose programming as a career or hobby.
A company such as Microsoft creates innovative
technology that goes through a thorough testing process.
Often, that testing process reveals problems and issues
with the technology. You may find when you test your
programs that you find problems and issues that you
hadn't considered. This is why testing is so important!
One product that Microsoft has used extensive testing
in the development of is Code Jumper.

Have you ever considered how a student who is visually


impaired or blind can learn how to code? Code Jumper
is an innovative and pioneering product that students
that are blind or visually impaired can use to learn how
to program alongside their sighted peers. It is designed
by Microsoft and it helps to open the fun and exciting
practice of programming to all students.

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.

The software for the product had to be tested


to make sure that it worked correctly, but one
of the most challenging aspects for Microsoft
was designing the most effective hardware
for the product. It took a lot of user testing
and iteration to get it right The design team
needed to consider that the students using the
product would be picking up and handling the
product, touching it to be able to identify if it
is a pod that is designed to create a variable,
selection or iteration. They also had to think
f about the student finding the connections that
enabled them to join the pods to create the

Figure 1: An example of a program created using the Code Jumper hardware.


Microsoft

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.

Other aspects of the hardware design that had to be trialled Questions


and redesigned repeatedly were the wired connection for
joining the pods. The design team had to get the best 1 How many different types of testing do you know?
level of flexibility and the simplest audio jack system so Can you name and describe any of them to a partner?
it could be easily plugged in. Some of the problems they
2 What problems did Microsoft find with the Code
encountered came from the way that the students would
Jumper product when they tested it with the user?
touch and feel the pod for the audio jack. This could often
Do you think these problems would have been found
result in the connection being short-circuited. Just when the
without the testing? Why or why not?
team thought they had the right set-up for this, they would
trial it with students, who would react to it in a very different 3 Do you think that you do enough testing on your
way and they would again have to review the design and programs that you create? How do you know? What
change it to meet the needs of the user. kind of evidence do you have for your testing?

ACTIVITY

Think of two reasons why you think it is


important to thoroughly test a product or
program. Share these reasons with a partner.

Write a promise to yourself that you will make


sure that you test all your programming work
thoroughly. Complete the following statements
as part of your promise:
• Testing is so important because ...
• If I do not test my work thoroughly I could
get problems such as ...
Figure 3: Two students with mixed visual abilities making a
program together. • I will make sure I test my work by ...

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?

3 Do you think the data needed for the device should


be stored locally on the device or in a cloud system?
Why?

ACTIVITY

Work in a group. Imagine you are the cyber


security gurus who have been contacted by
Microsoft to make sure the data they store is
kept safe. Create a presentation for Microsoft
to tell them what you will do to keep their data
secure.
Your teacher will act as the representative for
Microsoft and choose who they think will do the
Figure 2: Data of a known person being scanned into the
best job.
Project Tokyo Al system

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

case studies cyber threats


responsible Al 384-5 brute-force attacks 106-7
testing 382-3 data interception 108-9
casting 203-4 distributed denial of service attacks 109-11
CDs 68 hacking 112
cells 69 malware 113-15
central processing unit (CPU) 6, 56 pharming 116-17
fetch-decode-execute cycle 57-9 phishing 117-18
performance of 60-1 social engineering 119-21
certificate authorities 99
char data type 202 data backup 115
character sets 21 data bus 58
characters 298 data compression 27-9
check digits 48, 176 data input and output 205-8
checksum 46 data interception 108-9
cipher text 49 data measuring units 25
clock speed 60, 61 data packets 35
cloud storage 70-1 data storage 66-9
comparison with local storage 72 cloud storage 70-2
Code Jumper 382-3 virtual memory 69-70
coding 157 data transmission 34
colour depth 23 encryption 49-50
colour scales 22 error detection 44-8
command line interface 82 full-duplex 41-2
comments 267-9, 368-9 half-duplex 41
comparison operators 216-17 interference 38
compilers 88-9 packet switching 36
compression 27-9 parallel 39
computer case fans 5 serial 38-9
computer cases 4 simplex 40
computer components 4-7 USB connections 43-4
concatenation 206 data types 10, 202-3, 298
constants 198-9 converting between (casting) 203—4
assignment 201 data validation 173-7, 357-8, 362, 367
control bus 59 data verification 177
control gate 68, 69 databases 80, 296-7
control unit (CU) 58 defining a single-table database 299-300
cookies 101—4 primary keys 299
cores 60 see also Structured Query Language (SQL)
COUNT 313-14, 315-17 debugging 9
count-controlled loops 231—4, 240 decomposition 146, 147-9
counting 168-9, 243-4 denary system 10
cryptocurrency 105-6 design
current instruction register (CIR) 58 flowcharts 149-53
cyber security pseudocode 154-5
anti-malware software 110, 114 structure diagrams 146-9
anti-virus software 114 digital certificates 99-100
data protection 115-16 digital currency 105-6
encryption 109 digital data 10
firewalls 112, 114-15 digital ledgers 105-6
passwords 107-8 distributed denial of service (DDoS) attacks 109-11
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

DIV 209, 210, 213 hacking 112


division 213 half-duplex data transmission 40, 41
domain name servers (DNS) 98 hard drive 7, 57, 67-8
domain names 97 hexadecimal system 9, 14
double data type 202 benefits of 16
double entry checks 177 conversion to/from denary 14-15
drivers 83 high-level languages 85, 87
drones 135 holographic data storage 69
dynamic IP 74-5 HoloLens 384-5
humidity sensors 64
echo check 46 hypertext markup language (HTML) 98
editors 90 hypertext transfer protocol (HTTP) 98
ELSE 220-1,228-30 hypertext transfer protocol secure (HTTPS) 99-100
ELSEIF 222-4, 228-30
embedded systems 56 identifiers 198, 267
encryption 49-50, 99, 109 IF statements 216, 218-19, 228-30
ENIAC 79 ELSE 220-1
error detection ELSEIF 222^1
in data transmission 44-8 image representation 21-3
reading the code 188-90 indices (singular: index) 270
using hexadecimal 9 variables as 273-4, 279-80
using a trace table 187-8 inference engines 139
ethernet 43 infra-red sensors 64
executable files 88, 89 infrastructure 96
expert systems 139 input devices 57, 62
extreme test data 157-8 inputs 207-8
validation 357-8, 362, 367
fans 5, 6, 7 writing code 357, 366
fetch-decode-execute cycle 56, 57-9 instruction sets 58
fields 297 integers 202, 298
file handling 286 Integrated Development Environment (IDE) 90-1
reading from a file 286-8 intelligence 126
writing to a file 288-9 see also artificial intelligence
file management 82 interfaces 82
file size calculation 25-7 interference 38
firewalls 112, 114-15 internet 96
firmware 81 cookies 101 4
floating gate 68, 69 requesting and receiving web pages 97-100
flow sensors 64 web browsers 100-2
flowcharts 149-53 Internet of Things 55
FOR (count-controlled) loops internet protocol (IP) addresses 35, 74-5
197-8, 231-^4, 240 interpreters 88-9
format checks 175-6 interrupts 83, 84
Fortran 79 IPv4 and IPv6 addresses 74
full-duplex data transmission 40, 41-2 iteration (loops) 231
functions 255, 257-60 in arrays 274-7, 281^4-
conversion between types of loop 240
gas sensors 64 count-controlled 231-4
global variables 260-1,262 post-condition loops 237-9
graphical user interface (GUI) 82 pre-condition loops 234-7
graphics cards 7 trace table 1813
Index

keys (encryption) 49-50 moisture sensors 65


knowledge bases 139 motherboard 5
multiplication 212
length checks 173^4 multitasking 83
LENGTH command 245-6
level sensors 64 NAND gate 330-1
library routines 265 natural language interface 82
light sensors 64, 65 navigation 101
linear search 159-61 nested statements 251-5
local variables 260, 261-2 network interface card (NIC) 72, 73
logic circuits 334-8 networks 36, 96
creation for problem statements 347-8 hardware 72-5
logic expressions 327, 328, 329, 331, 332, 333 nibbles 25
creation for problem statements 347-8 NOR gate 331-2
for a logic circuit 337-8 normal test data 157-8
logic gates 10, 325-6 NOT gate 326-7
AND 327-8 NOT operator 227
NAND 330-1 number systems
NOR 331-2 binary 9, 10-13
NOT 326-7 denary 10
OR 329 hexadecimal 9,14 16
XOR 333
logical binary shifts 19-20 operating systems (OS) 80, 81-3
logical operators 216-17, 305 optical drive 7
loops see iteration optical storage 67, 68
lossless compression 27, 28-9 OR gate 329
lossy compression 27 OR operator 227, 308
LOWER command 250 ORDER BY 311
low-level languages 85, 86, 87 output devices 62-3
outputs 205-7
machine code 86 writing code 359-60, 368
machine learning 137-8 overflow errors 18
magnetic field sensors 65
magnetic storage 67-8 packet headers 35
maintainable programs 267-9 packet sniffers 108
malware 95-6, 113-15 packet switching 36
DDoS attacks 109-11 packets 35
maximum values 170-1 parallel data transmission 38, 39
media access control (MAC) addresses 16, 73 parameters 255, 262-5
memory parentheses (brackets) 214
RAM 6, 57, 66 parity check 45
ROM 66 passwords 107, 112
virtual 69-70 validity checking 251
see also data storage payloads 35
memory address register (MAR) 57 perceptual music shaping 27
memory data register (MDR) 58 peripherals 82-3
memory management 83 persistent cookies 103—4
metadata 22 pH sensors 65
microprocessors 56, 127 pharming 116-17
minimum values 170 phishing 117 18
mnemonics 86 pixels 21-3
MOD 209,210,214 plain text 49
y CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

portable programs 85 search engines 100-1


post-condition loops 231, 237-9 secondary storage 66, 67
power supply unit (PSU) 6 secure sockets layer (SSL) protocol 100, 109
pre-condition loops 231, 234-7, 240 SELECT case statements 224-6
presence checks 175 SELECT FROM 302—4
pressure sensors 65 SELECT FROM WHERE 305-6
prettyprint 90 combining conditions 307-8
primary keys 299 values in or not in, a condition 309
primary storage 66 selection 216
problem statements 347-8 IF statements 218-24, 228-30
procedures 255-7 logical operators 216-17
processes 146 trace table 179-80
writing code 358, 362-4 self-driving cars 134
program counter (PC) 57 semiconductor chips 68
program development life cycle 145 sensors 63-5, 127
analysis 145-6 sequence 214-16
coding 157 serial data transmission 38-9
design 146-55 servers 70, 98
testing 157-8 proxy servers 110
programming languages 79, 87, 197 session cookies 103
high-level 85 simplex data transmission 40
low-level 86 single data type 202
programming scenario 354-5 smart devices 55
method 1 355-65 social engineering 119-21
method 2 365-73 software 80-1
protocols 97 malware 95-6, 109-11, 113-15
proximity sensors 65 operating system 81-3
proxy servers 110 programming languages 79, 85-7
pseudocode 154-5 software updates 112
solid-state storage (flash memory) 67, 68
RANDOM 266-7 sorting algorithms 159, 161-6
random access memory (RAM) 6, 57, 66-7 sound sampling 23-5
range checks 173 spreadsheets 80
ransomware 113 spyware 113
read only memory (ROM) 66 static IP 74, 75
real data type 202, 298 stepping 91
records 297 string manipulation
registers 10, 57, 58, 59 LENGTH 245-6
REPEAT UNTIL (post-condition) loops 237-9 SUBSTRING 246-9
resolution 22, 23 strings 202
robots 132 structure diagrams 146-9
uses of 132-5 Structured Query Language (SQL) 302
ROUND 265-6 COUNT 313-14, 315-17
routers 36, 72, 73—4 ORDER BY 311
rule bases 139 SELECT FROM 302-4
run length encoding (RLE) 28-9 SELECT FROM WHERE 305-9
run-time environments 90 SUM 312-13,314-15
subroutines 255, 269
sample rates 24 functions 257-60
sample resolution 24-5 procedures 255-7
scope of a variable 260 SUBSTRING command 246-9
search algorithms 159-61 subtraction 211-12
Index

SUM 312-13,314-15 UPPER command 250


symmetric and asymmetric encryption 49 user accounts 83
system software 80 user history 101
operating system 81-3 usernames 121
utility programs 80
tables 297
tabs 101 validation 173-7, 357-8, 362, 367
temperature sensors 65 variable watch windows 91
test data 157-8 variables 198-9
testing 157-8 assignment 198-201
case study 382-3 scope 260-2
timeout 47 virtual memory 69-70
totalling 167, 241-2 viruses 113, 114
trace tables 179-83 visual checks 177
finding errors in a program 187-8 Von Neumann architecture 56
finding the purpose of an algorithm 184-6
trailers (footers), data packets 35 WannaCry malware 95-6
transistors 69 web browsers 80, 97
translators 87-9 features of 100-2
transmission media 72 web pages 96
transport layer security (TLS) protocol 100 web servers 98
trojan horses 113 websites 96
truth tables 326-7, 328, 329, 330, 332, 333 WHILE (pre-condition) loops 234-7, 240
creating logic expressions and logic circuits 339-46 wide area networks (WAN) 96
creation for problem statements 347-8 windows 101
Turing Test 136 word processors 80
two-step verification 107-8 world wide web 96-7
type checks 174-5 worms 113

Unicode 21 XOR gate (EOR gate) 333


uniform resource locators (URLs) 97-8
universal serial bus (USB) interface 43 4 zombies 110
flash memory drives 68, 69
)> CAMBRIDGE IGCSE™ & O LEVEL COMPUTER SCIENCE: COURSEBOOK

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy