Edexcel Computer Science For GCSE
Edexcel Computer Science For GCSE
Steve Cushing
| endorsed for d H O D DE R
Dynamic Learning is an online subscription solution that supports teachers and students with high
quality content and unique tools. Dynamic Learning incorporates elements that all work together to give
you the ultimate classroom and homework resource.
Edexcel only endorses the Student book and Student eTextbook. The other resources referenced here
have not been submitted for endorsement.
Teaching and Learning titles include interactive resources, lesson-planning tools, self-marking tests
and assessment. Teachers can:
e Use the Lesson Builder to plan and deliver outstanding lessons
e Share lessons and resources with students and colleagues
e Track student progress with Tests and Assessments
Teachers can also combine their own trusted resources alongside those from Edexcel Computer
Science for GCSE which has a whole host of informative and interactive resources including:
e A ready-made toolkit to deliver the GCSE specification, including a Scheme of Work, lesson plans for
each chapter, outline presentations for all topics, and animated explanations for difficult key concepts
e Practical tasks and examples to develop problem-solving, computational thinking and Edexcel
language-specified programming skills in chosen languages
e Opportunities to develop independent learning skills with activity worksheets and answers, and
additional programming exercises to enhance understanding of certain topics
e Sample Tasks using Linux style commands (to provide practical experience with the command line
interface)
Edexcel Computer Science for GCSE is available as a Whiteboard eTextbook which are online
interactive versions of the printed textbook that enable teachers to:
e Display interactive pages to their class
e Add notes and highlight areas
e Add double-page spreads into lesson plans
Additionally the Student eTextbook of Edexcel Computer Science for GCSE is a downloadable
version of the printed textbook that teachers can assign to students so they can:
e Download and view on any device or browser
e Add, edit and synchronise notes across two devices
e Access their personal copy on the move
RS SS
To find out more and sign up for free trials visit: www.hoddereducation.co.uk/dynamiclearning
G CSE ee ap
date shown. O R
EXC E L Please return / renew by
ED
You can renew at: norlink.norfolk.gov.uk
or by telephone: 0344 800 8006
Please have your library card & PIN ready.
31 eT 2046
1 ANOV 2016
25 NOV 2016
NORFOLK LIBRARY
AND INFORMATION SERVICE
Steve Cushing
pov ic
wamNING
Bes LEAR TUNN
G— EDUCATIO
AN HACHETTE UK COMPANY
E In order to ensure that this resource offers high-quality support for the associated Pearson
qualification, it has been through a review process by the awarding body. This process confirms
that this resource fully covers the teaching and learning content ofthe specification or part of
a specification at which it is aimed. It also confirms that it demonstrates an appropriate balance
between the development ofsubject skills, knowledge and understanding, in addition to
preparation for assessment.
Endorsement does not cover any guidance on assessment activities or processes (e.g. practice
questions or advice on how to answer assessment questions), included in the resource nor does it
prescribe any particular approach to the teaching or delivery of arelated course.
While the publishers have made every attempt to ensure that advice on the qualification and
its assessment is accurate, the official specification and associated assessment guidance materials
are the only authoritative source of information and should always be referred to for definitive
guidance.
Pearson examiners have not contributed to any sections in this resource relevant to examination
papers for which they have responsibility.
Examiners will not use endorsed resources as a source of material for any assessment set by
Pearson.
Endorsement of aresource does not mean that the resource is required to achieve this Pearson
qualification, nor does it mean that it is the only suitable material available to support the
qualification, and any resource lists produced by the awarding body shall include this and other
appropriate resources.
The Publishers would like to thank the following for permission to reproduce copyright material.
Photo credits
p-4 both © TfL from the London Transport Museum collection; p.71 © Photodisc/Getty Images/
Business Today 35; p.133 © Robert Gray; p.150 © istockphoto.com/Mark Evans; p.218 © Robert
Gray; p.219 © Godfried Edelman/iStockphoto.com; p.293 ©Jwrodgers/ Wikimedia (http://
creativecommons.org/licenses/by-sa/3.0).
Hachette UR’s policy is to use papers that are natural, renewable and recyclable products and made
from wood grown in sustainable forests. The logging and manufacturing processes are expected to
conform to the environmental regulations of the country of origin.
Orders: please contact Bookpoint Ltd, 130 Milton Park, Abingdon, Oxon OX14 4SB. Telephone:
(44) 01235 827720. Fax: (44) 01235 400454. Email [email protected] Lines are open from
9 a.m. to 5 p.m., Monday to Saturday, with a 24-hour message answering service. You can also order
through our website: www.hoddereducation.com
© Steve Cushing 2016
First published in 2016 by
Hodder Education,
An Hachette UK Company
Carmelite House
50 Victoria Embankment
London EC4Y 0DZ
www.hoddereducation.com
Impression number 10 9 8 765 43 2 1
Year 2020 2019 2018 2017 2016
All rights reserved. Apart from any use permitted under UK copyright law, no part ofthis publication
may be reproduced or transmitted in any form or by any means, electronic or mechanical, including
photocopying and recording, or held within any information storage and retrieval system, without
permission in writing from the publisher or under licence from the Copyright Licensing Agency
Limited. Further details of such licences (for reprographic reproduction) may be obtained from the
Copyright Licensing Agency Limited, Saffron House, 6-10 Kirby Street, London EC1N 8TS.
Printed in Italy
A catalogue record for this title is available from the British Library.
ISBN: 9781471866227
Contents
38 Project 298
Constants
ee
ES ES eee
Chapter review
® Understand and be able to determine the correct
In this chapter we have explored variables and output of an algorithm for a given set of data (More
assignment. We also explored the importance of on this topic in Chapters 2, 3, 4,)
correctly naming your variables. ® Understand and be able to code an algorithm
Remember, before tackling any computer science task in a high-level language (More on this topic in
or examination question on this topic you must: Chapters 7, 8, 14, 5, 11, 10)
® Understand and be able to explain what an ® Understand and be able to explain how the choice
algorithm is, what algorithms are used for and be of algorithm is influenced by the data structures
able to interpret algorithms (flowcharts, pseudo- and data values that need to be manipulated
code, written descriptions, program code) (More on (More on this topic in Chapters 7, 8, 14, 5, 11,
this topic in Chapters 1, 2, 3, 7, 8, 14, 5, 11, 10) 10, 18)
® Understand and be able to create an algorithm ® Understand and be able to explain the benefit of
to solve a particular problem, making use of producing programs that are easy to read and be
programming constructs (sequence, selection, able to use techniques (comments, descriptive
iteration) and using appropriate conventions names (variables, constants, subprograms),
(flowchart, pseudo-code, written description, draft indentation) to improve readability and to explain
program code) (More on this topic in Chapters 2, 3, how the code works (More on this topic in
AN Tf ts, WAL, Sy, ln IC) Chapter 3)
® Understand and be able to explain the purpose of a ™Be able to use sequencing, selection and iteration
given algorithm and how an algorithm works (More constructs in your programs (More on this topic in
on this topic in Chapters 2, 3, 4, 7, 8, 14, 5, 11, 10) Chapters 3,4, 7, 8714) 5) 1a10):
: i Specification references
You should:
1.2.2 be able to decompose a problem into smaller
| 1.1.1 understand what an algorithm is, what
sub-problems
algorithms are used for and be able to interpret
algorithms (flowcharts, pseudo-code, written 1.2.3 understand how abstraction can be used
descriptions, program code) effectively to model aspects of the real world
» 1.2.1 be able to analyse a problem, investigate 1.2.4 be able to program abstractions of real-world
requirements (inputs, outputs, processing, examples
initialisation) and design solutions 4.1.1 understand the input-process-output model
Before you can succeed in computer science you must learn about
! Key points
what is called computational thinking. Computational thinking
m 4 Computational thinking involves learning how to use a set of problem-solving skills
| involves learning how to use and techniques that are used by computer programmers to
a set of problem-solving skills write programs. Computational thinking is not thinking about
and techniques that are used computers or even thinking like a computer. Computers don’t
by computer programmers to think for themselves. If you give ten computers the same
write programs. instructions and the same input, they will give exactly the same
A For the examination you will output. Computers are predictable.
need to understand how to
Computer scientists use logical reasoning to work out exactly what
create an algorithm using a
a program or computer will do. Computational thinking is about
written description.
considering a problem in a logical way so that a computer could
help us to solve it. This logical reasoning is the essential building
block of computer science. So first we need to fully understand
the techniques involved and how we start with a problem and end
up with the programming code.
Two important techniques used in computational thinking are:
@ Decomposition: This is breaking any given task or problem into
simple logical steps or parts.
® Abstraction: This is the process of taking away or removing
irrelevant characteristics in terms of the problem being solved
in order to reduce it to something simpler to understand. In
computer science, abstraction is often used for managing the
complexity of computer systems.
Decomposition
] Key points
__[ The Probleaem_| ee
A Logic programming is a Decompostition
method of writing computer
programs based on the
mathematical study of logical 7Reareech to
0 | |Approach to |
reasoning. part of the | | part of the | | part of the |
4 Decomposition means ——— | Le Lil e Problem |
breaking a problem into a
number of sub-problems,
so that each sub-problem SLCOS aaa
accomplishes an identifiable
‘ Particular
task, which might itself be The algorithm
further subdivided. Figure 1.1 Decomposition and abstraction
4 Abstraction is the process of
We will explore each of these in detail later in the book but let’s
removing unnecessary detail
start with a simple example of decomposition and abstraction as
from a probiem.
it relates to problem solving.
§ Decomposition
Decomposition is a term used
When a chef writes a recipe for a meal, he is creating a set of
for the separation of a task into
instructions that others can follow to replicate the meal. Each part
discernible parts, each of which
of the recipe is listed separately, the overall meal is decomposed
is Simpler than the whole.
into separate dishes, and these are often decomposed further, e.g.
making the pastry and the filling.
a Abstraction
1 Use this book and other
sources such as the internet You may have come across the term ‘Abstract Art’ where a painting
to research how to decompose is a set of shapes representing the picture. A good example of
a problem into smaller sub- the use of abstraction for technical purposes is the London tube
problems. map. It is the brainchild of an electrical draughtsman named
2 Use this book and other Harry Beck. Rather than emphasising the real distances and
sources such as the internet to geographical location of all the tube lines, Beck stripped away
research how abstraction can the sprawling tube network by abstracting just the information
be used effectively to model needed by travellers. He then used this to create an easy-to-read
aspects of the real world. diagram of coloured, criss-crossing lines common in electrical
diagrams.
! Key points
A |n abstraction we remove unnecessary details from a problem until we
can represent the problem in a way that is possible to solve.
A For the examination you will need to be able to interpret written
descriptions.
1 Computational thinking
Figure 1.2 A geographical map of the London underground Figure 1.3 An original abstracted map of the London
stations underground
A B
G H W M
The man (M) has taken the goat (G) to the other side of the river.
! Key points
4 Solve the rest of the man ina A Abstraction draws out the essence of a problem - by solving it we
boat problem. can also see what other problems can be solved using the same
techniques.
A For the examination you will need to be able to decompose a problem
into smaller sub-problems.
1 Computational thinking
pel
h
B CH |e) E
Figure 1.5 Four possible pathways
§ What is an algorithm?
The word ‘algorithm’ comes from the ninth-century Arab
I Key points mathematician, Al-Khwarizmi, who worked on ‘written processes
A An algorithm is not a computer to achieve some goal’. The term ‘algebra’ also comes from the
program; a computer program term ‘al-jabr’, which he introduced. You have already started to
is the implementation of an write algorithms by developing pseudo-code.
algorithm. Algorithms are at the very heart of computer science. An
A Programs must be carefully algorithm is simply a set of steps that defines how a task is
designed before they are performed. For example, there are algorithms for cooking (called
written. During the design recipes), algorithms for finding your way through a strange city
stage, programmers use tools (directions), algorithms for operating washing machines, and
such as pseudo-code and even algorithms for playing music (sheet music).
flowcharts to create models of
A scientific description of an algorithm would be:
programs.
A A process is a series of ‘a series of unambiguous steps to complete a given task in a finite
actions or steps taken in order amount of time’.
to achieve a particular end. An algorithm has input data, and is expected to produce output
data after carrying out a process, which is the actions taken to
e Question achieve the required outcome. You will need to understand this
input—process—output model as much of what you will learn in
1 What is an algorithm?
computer science is founded upon this model.
1 Computational thinking
Feedback
§§Sequences
To solve a problem there must be a sequence of steps. In computer
science, a sequential algorithm is an algorithm that is executed
sequentially, one step at a time from start to finish. It does this
without any other processing executing. Most standard computer
algorithms are sequential.
You know that this is the order that you should write an address,
but this is the exact opposite of the way that the postal system
! Key point works. There are millions of John Smiths. There may be hundreds
Many computer programmers
of Holly Roads, many of them with a number 22. The postal
system needs to know the address in the logical task order,
label their files using the date
format year, month, day as this is
meaning the order that you go about finding the address; that is
London first, next the area, then the road and then the number.
the logical way to automatically
list them, the year being the In some countries the conventional order follows the logical task
first piece of data required, the order. In Russia letters are addressed in exactly the opposite order
month next and the day last. This to the UK with the city first.
is because there can be 12 files
For your programming to work correctly, all the commands
with the same day number in a
have to be there AND they need to be in the correct sequence.
single year.
Sequencing is extremely important in programming.
* 1 Computational thinking
Let’s say we want to make a cup of tea using tea bags and a kettle.
The sequence could look like this:
Input SS ~ Process
Water An electric kettle is filled with water Tea
Tea bags Tea bags are placed in the tea pot
Boiling water The boiling water is poured into the tea pot and the
tea brews
Milk Milk is added to the cup
Sugar Sugar is added to the cup
The ‘brewed’ tea is poured into a cup
We would do the same to make more than one cup of tea but we
would only fill the kettle and boil it once. We could divide the
7 Use this book and other sequence into two parts.
sources such as the internet
to research how to evaluate Sequence 1
the fitness for purpose
Count number of people wanting tea #input
of algorithms in meeting
Fill the kettle with enough water #input and process
specified requirements.
Boil the water #process
Put tea bag in pot #input and process
Pour on water #input and process
Allow tea to brew #process
10
sss
Sequences
Sequence 2
§ Modularity
There are several advantages to designing solutions in a structured
! Key points manner. One is that it reduces the complexity as each set of steps
A A subroutine is a sequence can act as a separate module. Modularity allows the programmer
of instructions that is set to tackle problems in a logical fashion. Modules can also be reused.
up to perform a frequently
To develop modules the programmer needs to carry out what is
performed task.
called decomposition. This is to break down a problem into easy-
A A procedure is a subroutine to-understand steps.
that does not return values.
Because modules can be reused many times, this saves time and
reduces complexity, as well as increasing reliability as the modules
will have already been tested in another program. It also offers an
easier method to update or fix the program by replacing individual
modules rather than having to fix larger amounts of code.
One reason for modular (also called structured) programming is
In pSeudo-code a computer can that it avoids the increased possibility of data corruption often
repeat a group of actions using caused by using a large number of lines of code. It also ensures
REPEAT-UNTIL. that there is a logical structure in the program being written to,
which makes the code more efficient and easier to understand
and modify.
? Question Structured programming makes extensive use of subroutines,
2 What is an algorithm? block structures and ‘for’ and ‘while’ loops. We will explore all of
these later in the book.
Chapter review
. ! Key points There are a lot of different design procedures and techniques for
building large software projects. The technique discussed in this
A A flowchart is a diagram chapter, however, is for smaller coding projects and is referred to
representation of an algorithm. by the term ‘top down, structured flowchart methodology”. We will
‘ A For the examination, you will explore how to take a task and represent it using a flowchart. A
need to be able to interpret flowchart puts the sentences from a sequence into shaped boxes.
flowcharts. The shapes indicate the action.
. | A Flowcharts are a graphical
You will know from the last chapter that a sequence is where a set
method of designing
of instructions or actions are ordered, meaning that each action
programs.
follows the previous action.
;
A A well-drawn flowchart is easy
to read.
! Key point
In a flowchart the lines express
the order of execution. Figure 2.1 A sequence
14.
SSS
: Flowchart advantages ewe
te
he
§ Flowchart advantages |
@ Flowcharts are a graphical way of writing pseudo-code.
@ They are all standardised: we all pretty much agree on the
symbols and their meaning.
@ They are very visual.
§ Flowchart disadvantages
@ Flowcharts can be time consuming and difficult to modify.
@ They need special software for symbols although some software
has these built in.
® The structured design elements are not all implemented.
Representing a process
A PROCESS symbol is representative of some operation that is
carried out on an element of data. It usually contains a brief
description of the process being carried out on the data. It is
possible that the process could be even further broken down into
ae,
a
Basic elements of flowcharts |
SS =
Representing a decision
A DECISION/SELECTION symbol always makes a Boolean choice. We
e Key points
will explore Booleans in more detail later in the book. The label in
A One of the most confusing a decision symbol should be a question that clearly has only two
things in a flowchart is telling possible answers to select from.
the loops apart from the
selections. This is because
both use the diamond shape
as their control symbol. Mark
them clearly.
true?
A A ‘Decision’ symbol always
makes a Boolean choice.
[eyes
The DECISION symbol will have exactly one input arrow and two
output arrows. The two outputs will be labelled with the two
answers to the question, in order to show the direction of the
logic flow depending upon the selection made.
Selections are usually expressed as decision key words, such as ‘if
.. then ... else ... endif, switch or case’. They are at the heart of all
programming.
Condition
Then | true? | Else
Action 2
? Questions
4 What is a flowchart?
5 What is a selection? Figure 2.5 A flowchart representing a selection
2 Using flowcharts
End
Start 7) Boil kettle
Figure 2.6 A flowchart showing what - —
happens on a school morning
Pour water
in mug
Drink tea
Give dice to
next player
Slide down |
tail of snake |
End
Yes
Subprocesses
We can also use subprocesses in flowcharts using the symbol
below.
a
Basic elements of flowcharts
Chapter review
bs Specification references
22
The importance of syntax
Pseudo-code disadvantages
@ Pseudo-code is not visual like flowcharts.
@ There is no accepted standard, so it varies widely.
@ It is not an actual programming language.
2? Question @ It is an artificial and informal language.
4 What is pseudo-code? ® Some people have a tendency to put actual code in. This makes
it harder to understand.
Symbols
When we write code in English we also use symbols in the form of
punctuation. Symbols are used because they are human-readable.
The symbols you use are important as they have an effect in your
code.
these-words-are-separated-by-a-symbol #the - is the symbol used
#here
there is alsoasymbolinthis sentence #here the space is the
#symbol used
v
;\
Bess INPUT
END FOR OUTPUT
END IF REPEAT
END WHILE RETURN
FOR THEN
IF WHILE
a
Commenting on your code
Adding selection
As we discovered in the last chapter on flowcharts, another
important aspect of programming is selection. If we want to write
pseudo-code that tells a user to enter a number to a variable, and
then we want the code to see if the number they entered is a 3 or
a 4 we could write a selection algorithm in pseudo-code that could
look like this:
END IF
ea
Commenting on your code
Chapter review
In this chapter we have explored pseudo-code and ® understand how to determine the correct output of
how to use it to show program flow and decision an algorithm for a given set of data
making.
® understand and be able to use appropriate
We also explored the importance of syntax and how to conventions in pseudo-code
comment on your code.
® understand and be able to explain the benefit of
Remember, before tackling any computer science task producing programs that are easy to read and be
or examination question on this topic you must: able to use techniques such as comments and
® understand and be able to explain what algorithms descriptive names for variables, constants and
are used for subprograms alongside indentation to improve
readability and to explain how the code works
® be able to interpret and write algorithms in pseudo-
code ® be able to use sequencing, selection and iteration
constructs in your programs
® understand and be able to explain and create
algorithms to solve a particular problem, making ® understand and be able to apply structural
use of programming constructs (Such as sequence, components of a program including variable and
selection, iteration) type declarations and sequences, selection,
iteration, data structures and subprograms.
® understand and be able to explain and apply the
purpose of a given algorithm and how an algorithm
works
4 Mathematical skills in computer
science
of, and how to use, arithmetic The step-by-step process used to do the long division is called a
operators (add, subtract, divide, long division algorithm.
multiply, modulus, integer
Algorithms are used a lot in mathematics, especially in algebra.
division).
A
4 Mathematical skills in computer science
B Modules
! Key point
A module is asoftware component or part of aprogram that contains
Programmers commonly use one or more routines. Grouping related code into modules makes
a technique known as the code easier to understand and use. We will look at modules in
top-down design to break down more detail later in this book but one of the advantages of modules
an algorithm into functions and is that some of them are already written for you and many relate
modules. to mathematical operations so you will need to understand what
they can do.
A number of very useful modules exist in Python, normally in
a file named <modulename>.py. You can use any Python file as a
module by using an import statement.
The import statement for a module has the following syntax:
import <module name>
Here’s how these statements and functions work.
Example:
FUNCTION myMarks (Mark1, Mark2, Mark3)
BEGIN FUNCTION
SET Total to (Mark1 + Mark2 + Mark3)/3
RETURN Total
END FUNCTION
Ca
Mathematical algorithms
You can also use <module name> import * to import the module and
then you can simply use a plain name to refer to things defined
In computer science, an object in the module. You can even call the module by coding from
could be a variable, a data <module name> import a, b, c. This imports the module and creates
structure or a function. Each references to the given objects in the module. In other words, you
object has a location in memory can then use a and b and ¢c in your program.
and a value. Objects are often
referenced by an identifier. In Python to import modules we use the following syntax:
import moduleName #imports a module
from moduleName import name #imports part of a module
from moduleName import *
§ Mathematical algorithms
Your knowledge of mathematical algorithms is vital as many
2 Write the pseudo-code to ask computing algorithms follow the same processes but not all are
the user to input a number the same. Let’s look at some examples and how these differ.
and output to the screen
whether it is an odd or even
number. The following instructions are the same But in computer science the meaning
in mathematics. of A = B is different.
A=B Be A In mathematics A = B is comparative,
In mathematics if both A and B = 1 you but in computer science it’s an
could write it as either A= Bor B=A. assignation, meaning you assign B as A.
This is different from B = A which
means you assign A as B.
In mathematics we work with relations. But in computer science, we work with
assignments. We can have:
In computer science signs such The relation B= A+ 1 means that it is Met S)
as = mean different things and true all the time. B=Ac &
A=3
different syntactical rules apply. The relation B = A + 1 is true only after
the second instruction and before the
third one. After the third one B = 6 and
[Ne Gh
The instruction A =A + 3 is false in But in computer science A=A+ 3
mathematics. It cannot exist. means: the new value of A is equal to
3 Use this book and other
the old value plus three.
sources such as the internet The instruction A + 6 = 3 is allowed in But A + 6 = 3 has no meaning in
to research how to use mathematics (it is an equation). computer science — the left side must
arithmetic operators. be a variable so we would have to say
three =A+ 6.
Output: 33
4 Mathematical skills in computer science
Gar (Sa2)
Brackets here are used to do the multiplication first.
Output: 21
Computers can execute instructions very quickly and reliably
without error, so algorithms and computers are a perfect match!
ee
the user inputs three numbers
and the largest number entered
is shown on the screen. > Greater than
= Equal to
I= Not equal to
34
Examples of pseudo-code mathematical algorithms
Notice how we have named the two numbers as num1 and num2 and
created a variable called multi to store the result of the calculation.
This is because these are variable as they can be any number. They
are not fixed. Notice also the comments shown after the #.
If we explore mathematical operations to find the sum of 5 entered
numbers in both simple English and a flowchart it may look like
this.
Algorithm — in simple English
1 Initialise sum = 0 and count = 0
2 Enter n (I/O)
> 4 Mathematical skills in computer science
sum = sum + 1
count = count + 1
Figure 4.1
=
Probability and randomisation
Output:
Addition: 12+7= 19
Subtraction: 12-7 =5
Multiplication: 12x 7 = 84
Division: 1 fea. 142857142857
142
Floor Division: I2=7 = 1
Remainder: 12%7=5
Exponent: 122 = 35831808
Notice how we have used a string to show the conventional
mathematics symbols such as ‘x’.
38
Probability and randomisation
40
Probability and randomisation
guess = input()
guesses = guesses + 1 #add 1 to guesses variable
if not guess.isdigit() : #checks it is not a string
print(‘Invalid! Enter only digits 1-10') #output string
#to screen
break #stop the while loop
elif int(guess) < num:
print('Too low, try again: ', end= '')
elif int(guess) > num:
print('Too high,try again: ', end ='')
else ¢
print(‘Correct... My number is ' + guess)
flag = False #makes flag False to stop
#the while loop
+ You should:
a | 1.1.1 understand what an algorithm is, what 1.1.6 understand how to code an algorithm in a ©
algorithms are used for and be able to interpret high-level language
algorithms (flowcharts, pseudo-code, written 1.1.7 understand how the choice of algorithm is
descriptions, program code) influenced by the data structures and data
/ 1.1.2 understand how to create an algorithm to values that need to be manipulated
solve a particular problem, making use of 2.2.2 be able to use sequencing, selection and
programming constructs (sequence, selection, iteration constructs in their programs
iteration) and using appropriate conventions 9.3.3 understand the need for, and how to
(flowchart, pseudo-code, written description,
manipulate, strings
draft program code)
2.4.1 understand how to write code that accepts and
-) 1.1.3 understand the purpose of a given algorithm
responds appropriately to user input
: and how an algorithm works
1.1.4 understand how to determine the correct
: output of an algorithm for a given set of data
JKey polnt We often use loops with procedures for mathematical operations.
A loop is part of a program that If we now compare a WHILE loop with a procedure in flowchart,
repeats itself (to prevent the pseudo-code and Python form they would look like this:
need for the same piece of code
to be typed out multiple times).
Teele cede
WHILE x <5 while x < 5:
DO PROCEDURE() do_procedure()
ENDWHILE :
42
: Minimum and maximum
SS
SSS SSS sls sss SSeS SS
Flowchart
do_procedure| |
- Count =
Count + 1
on,
at the beginning of the list and work through the list systematically,
4
Eee...Mathematical arrays a
<a je
§ Mathematical arrays
When we want to use loops to work out mathematics we often
store the numbers in an array. We will explore these again in more
An array is a collection of data detail later in the book, but for now we will explore the concept in
items that are given a single mathematics.
name and saved on a computer
system in a sequential form. The You may have used arrays asachild when you learnt your multiplication
data items are distinguished by tables. By progressively adding another column of three objects, you
numbers. can visualise basic number facts in a graphical way.
myArray = (3,6,9,12,15)
ear
END FOR EACH
Pe
Finding the mathematical mean Se
eee
ee
§j Variables
At the core of any program are variables. Variables are where all
the dynamic information is stored.
When you use a keyboard to add your name to a running program,
your name would almost certainly be stored as the value of a
variable. Not all variables are the same though. In fact, there are
many different types. We have used the term variables before
for letters (as used in algebra) and for the temperatures in the
first section of the book. We used F (for Fahrenheit) and C (for
Centigrade).
In this section we explore variables in more detail. The ability to
Aelseaniepookarakerne: operate on different values each time a program is executed is
sources such as the internet to | iValuable in coded solutions. This is provided by variables
. If you
research how to use variables
want a user to input somethi ng to the system like a number that
and constants.
will change due to a calculati on, this will need to be stored as a
variable. Imagine variables as boxes. On the outside of the box is
What are variables?
the variable name. Inside the box is the variable. You can change
and add to what is in the box but you can’t change the box name.
§ Variable values
Variables are assigned values by use of whatis called an assignment
operator which is usually = or <— depending on the language used.
In pseudo-code SET may be used to assign a variable.
6 Variables and constants
Examples:
SET Counter TO 0
EN
variable is intended to be a constant.
Inputs to variables
Inputs to variables :
The variable may get its value within the program, for example
Shen Meaeiaay ROA
The variable num now equals 11. But what if the program states:
SET num TO num + 1
and
SET Size to LENGTH(Word)
but there are other ways a variable can be assigned and changed,
not least through user input. When a user inputs data into the
system it is usually stored in a variable.
You will know from earlier sections in the book that two variables
! Key point can be compared using the == operator or the != operator. Strings
To compare is to examine (two have to match exactly to get a ‘True’ output. Let’s look at an
Or more strings, etc.) in orderto example in Python:
note similarities and differences. subject = ‘Computer Science is Wonderful’ — #define the
#variable subject
with a string
if subject == ‘Computer Science is Wonderful’: #compare our
#variable with a
#string
a = 'TRUE' #if they match set ‘a’ to TRUE
print (a) #now output ‘a’ to screen
String manipulation
As you now know a string is simply a list of characters in order,
where a character can be anything a user can type on the keyboard
in a single keystroke.
You will also know that an empty string is a string that has 0 characters.
Python recognises as strings everything that is delimited by
quotation marks (either ’ ’ or ‘ ’).
We can also manipulate strings using some of Python’s built-in
methods. For example we can changing upper and lower case strings:
string = 'Hello World'
print(string.upper())
Output: HELLO WORLD
string = ‘Hello World'
cap)
print(string.lower())
Output: hello world
Ce
TCT Getting inputs
§ Getting inputs
Inputs can come from a number of sources including the keyboard,
touch screens, games controllers, barcode readers etc.
Often a program will have data for the variables from both within
the code and user input.
In the example below, the user input is for the route and the
computer setting of a variable for the count.
Think back to our map in the first chapter but now imagine it as a
computer game screen with the user having to input the movement
from C10 to the finish at L15. User input will determine the route.
But at H12 there is a banana that is worth points.
The user navigates the man from C10 to L15 using pathway C. On
the way a variable called banana will increase by 1.
SET banana TO banana + 1
es
iy
Fn
te
[Const es
jsits
ote an :*
than a variable.
Sometimes you use a constant in your code rather
You would use a constant instead of a variable if you know that a
value should not be changed when the program is running.
Using a constant eliminates the risk that the value will be changed
somewhere in the program code.
You should always use constants instead of typing values into
other places in your program code as this makes the code easier
to understand and easier to update in the future.
Note: You cannot declare a constant in Python. Some programmers
use names for the variables that are all-uppercase to show that
the variable is intended to be a constant.
a
be very few things you can do later to analyse the data.
Should data be stored in a variable as character or numeric?
Chapter review
® Understand and be able to determine the correct
In this chapter we have explored variables and output of an algorithm for a given set of data (More
assignment. We also explored the importance of on this topic in Chapters 2, 3, 4,)
correctly naming your variables. ® Understand and be able to code an algorithm
Remember, before tackling any computer science task in a high-level language (More on this topic in
or examination question on this topic you must: Chapters 7, 8, 14, 5, 11, 10)
® Understand and be able to explain what an ® Understand and be able to explain how the choice
algorithm is, what algorithms are used for and be of algorithm is influenced by the data structures
able to interpret algorithms (flowcharts, pseudo- and data values that need to be manipulated
code, written descriptions, program code) (More on (More on this topic in Chapters 7, 8, 14, 5, 11,
this topic in Chapters 1, 2, 3, 7, 8, 14, 5, 11, 10) 10, 18)
® Understand and be able to create an algorithm ® Understand and be able to explain the benefit of
to solve a particular problem, making use of producing programs that are easy to read and be
programming constructs (Sequence, selection, able to use techniques (comments, descriptive
iteration) and using appropriate conventions names (variables, constants, subprograms),
(flowchart, pseudo-code, written description, draft indentation) to improve readability and to explain
program code) (More on this topic in Chapters 2, 3, how the code works (More on this topic in
Oe fe 6214 851 1°40) Chapter 3)
® Understand and be able to explain the purpose of a ® Be able to use sequencing, selection and iteration
given algorithm and how an algorithm works (More constructs in your programs (More on this topic in
on this topic in Chapters 2, 3, 4, 7, 8, 14, 5, 11, 10) Chapters 3, 4, 7, 8, 14, 5, 11, 10).
7 Programming in code
B Specification references
o You should: .1.7 understand how the choice of algorithm is
c | 1.1.1 understand what an algorithm is, what influenced by the data structures and data
algorithms are used for and be able to interpret values that need to be manipulated
algorithms (flowcharts, pseudo-code, written 2.1.1 be able to write programs in a high-level
descriptions, program code) programming language
understand how to create an algorithm to .1.2 understand the benefit of producing
solve a particular problem, making use of programs that are easy to read and be able
programming constructs (Sequence, selection, to use techniques (comments, descriptive
iteration) and using appropriate conventions names (variables, constants, subprograms),
(flowchart, pseudo-code, written description, indentation) to improve readability and to
draft program code) explain how the code works
understand the purpose of a given algorithm .2.2 be able to use Sequencing, selection and
and how an algorithm works iteration constructs in their programs
understand how to determine the correct .3.3 understand the need for, and how to
output of an algorithm for a given set of data manipulate, strings
understand how to code an algorithm in a -4.1 understand how to write code that accepts and
high-level language responds appropriately to user input
<7
Strings in Python
Start up your Python editor and save the following into a file and
save your file as HelloWorld.py
print(‘Hello, World!')
] Key points
4 All the letters, numbers, and symbols in this book could be a string.
Think of a string as a collection of letters and/or numbers which are
stored as text not numbers.
4 We create a string by putting quotes around text so that the
programming language can tell it is a string not a number or
something else.
A No matter which programming language you choose, coding takes
time and it’s really a lot of trial and error.
§ Strings in Python
Now we understand how to develop code and use variables we
need to explore aspects of code that can change as a program runs.
! Key points Let’s say we want a user to input a string. You will know from
the last chapter that a string is simply a sequence of letters and
A A string is a data type used numbers. This sentence is a string.
to store a sequence of
characters. In Python, the input function is used for this purpose:
A Often programmers get errors name = input('What is your name?’) #‘What is your name’
because they write functions #is a string
that are too big. Big functions Strings are always within quotes. This particular use of a string,
_ are hard to debug because it for requesting input from the user, is called a prompt. Not only is
is hard to understand exactly the bit between quotes a string, so is the variable it is stored into,
what they’re trying to do. name, which has no quotes.
To create string (s) in Python we can use:
s = "Hello World!" or
s = 'Hello World!’
Write a short piece of code in
The input function displays the string on the screen to prompt the
your chosen language that will
user to put in an input of their name.
store a user input as a string.
In most cases strings must be contained all on one line.
A string may contain zero or more characters, including letters,
digits, special characters and blanks. A string consisting of only a
For the examination you will pair of matching quotes (with nothing in between) is called an
need to understand how to write empty string.
code that accepts and responds
Numbers can also be stored as strings, but be careful as when
appropriately to user input.
they are strings they are NOT NUMBERS.
7 Programming
eee
es eee in code
: Ls
q
Can you spot the difference between the two rows of values
i Key points shown below?
A A string may contain zero or
BE 45 98 3
more characters, including
letters, digits, special 22 45 98 S
characters, and blanks.
This is actually a trick question because (visually) there is no
A Numbers can be stored as
difference. The difference is how the values in the bottom row
strings but then they are no
are stored. They are stored as a text string, not a number. This is
longer numbers.
a very common mistake in programming and leads to problems
if you want to carry out mathematical operations later in the
code.
ane
s1 +52
Strings in Python
Example:
myString = ‘Hello World’
print(len(myString))
will print on the screen: 11
You can also find letters in a string:
myString = 'Hello World'
print(myString.count('!’)) #count how many times | is in the
#string myString
Strings often store many pieces of data. These are often stored in
a comma-separated format, which simply means that each part is
divided with commas. A space is another common delimiter, so in
‘Hello World’ the two words in our string are delimitated by a space.
#input string
myString = ‘London ,Bristol ,Birmingham ,Liverpool'
#delimitated using commas
cityNames = myString.split(’,’)
#loop and print each city name
for city in cityNames:
print(city)
Output:
London
Bristol
Birmingham
Liverpool
In programming the best way to
learn is by doing, programming So with split we extract the parts separated by the delimiter. Often
lines must be split. This is done with readlines() and with split. The
by ‘trial and error’. So, expect to
split() method with a string argument separates strings based on
make mistakes, they will help you
the specified delimiter, but with no arguments split() separates
to become a better programmer.
strings using one or more spaces as the delimiter.
7 Programming in code
eee
! Key point
§ Variables |
Variables are a storage As you will know from the last chapter, a variable is a memory
placeholder for texts and location that is used to store a value that can be changed. Variables
numbers. A placeholder is a are identified by names.
term referring to something not
In Python, variables are storage placeholders for texts and numbers.
yet finalised. It is a section of
Variables in Python are assigned with the equals sign, followed by
computer storage reserved for
the value of the variable. But be careful as there are some reserved
information that will be provided
words for Python that cannot be used as variable names.
later.
Variable names are case sensitive but you can use any letter, the
special character _ and numbers provided you do not start names
with them.
The value of the variable can be changed later on.
To store the value 10 in a variable named myVariable we would use:
myVariable = 10
To store the value of myVariable + 10 in a variable named myExtended:
myExtended = myVariable + 10
There are many different variable types in Python including ones
Naming variables with a capital
you should now understand:
letter used for the first letter of
the second word is called camel myVariable = ‘hello’ #string
case because the uppercase myVariable = 123
characters that appear in the
and new ones we will explore later in the book:
name suggest a camel’s hump.
myVariable = 3.14 #double float
myVariable = [0,1,2] #list
myVariable = (0,1,2) #tuple
myVariable = open(‘hello.py’, 'r') #file
You can even assign a single value to several variables at the same
time using multiple assignments.
a= b= Can #variables a, b and c are assigned to the
#same memory location, with the value of 1
an
Indentation
Size of variables
We have looked at variables as being boxes that can hold
something. The variable name is the label on the box. Not all
variables take up the same amount of memory. These can vary
according to the programming language used.
a Indentation
Indenting is adding spaces/tabs in front of ‘blocks’ of code (such
as IF), so that it is easier for you and other people to see how
the code flows. It shows which parts of the code will run under
certain situations.
§ Decisions in programming |
The other thing you looked at in the last chapter was decisions.
One of the most important aspects in programming is setting up
conditions: asking the question if...? Before moving on to the next
chapter we will explore this in a little more detail.
IF statement
Python provides the IF statement as the sole selection statement.
Consider the following example of a simple IF statement in Python:
if value <Q:
orint('The value is negative.’
Python does not use parentheses to enclose the condition but as the IF
statement is a compound statement, it requires a colon (?) following the
condition, even though there is only a single statement to be executed.
The format of the simple IF statement is shown below.
if <condition>:
<statement-block>
ELSE structure
The IF statement can also contain an ELSE part to be executed when
the logical condition is false. It too is acompound statement which
is indicated by the required colon following the ELSE statement.
if value < 0:
print('The value is negative.')
value = abs( value )
else:
print(‘The value is positive.’)
gan
el...String..
evaluations
Chapter review
In this chapter we have built upon the last few chapters of the book and
explored the use of programming languages focusing upon Python.
We looked at indentation, strings and decisions in programming.
Remember, before tackling any computer science task or examination
question on this topic you must:
® Be able to write programs in a high-level programming language
® Understand and be able to explain what an algorithm is, what
algorithms are used for and be able to interpret algorithms
(flowcharts, pseudo-code, written descriptions, program code)
(More on this topic in Chapters 1, 2, 3, 6, 8, 14, 5, 11, 10)
® Understand and be able to create an algorithm to solve a particular
problem, making use of programming constructs (Sequence, selection,
iteration) and using appropriate conventions (flowchart, pSeudo-
code, written description, draft program code) (More on this topic in
Chapters 2, 3, 4, 6, 8, 14, 5, 11, 10)
® Understand and be able to explain the purpose of a given algorithm
and how an algorithm works (More on this topic in Chapters 2, 3, 4, 6,
Sela Dalian tO)
® Understand and be able to explain how to code an algorithm in a high-
level language (More on this topic in Chapters 6, 8, 14, 5, 11, 10)
® Understand and be able to explain how the choice of algorithm is
influenced by the data structures and data values that need to be
manipulated (More on this topic in Chapters 6, 8, 14, 5, 11, 10, 18)
® Be able to use sequencing, selection and iteration constructs in your
programs (More on this topic in Chapters 3, 4, 6, 8, 14, 5, 11, 10)
® Understand and be able to explain how to manipulate, strings (More
on this topic in Chapters 6, 8, 14, 5, 11, 10)
® Understand and be able to write code that accepts and responds
appropriately to user input (More on this topic in Chapters 2, 3, 6, 8,
125 Set 20).
8 Iteration and selection
! Key points In practice even a simple task like this contains a number of
actions, some of which are repeated. We explored this when we
A Functions and procedures are looked at cleaning your teeth. You had a procedure to do, cleaning
quite similar as they are bits your teeth each day, and a function to do, brushing x number of
of code that can be recalled times. But remember that a computer can only do exactly what we
at any point in your program tell it to do. So we need to explore each action in much more detail.
and used again and again but
functions can return a value. You have already learnt in the last chapter about sequencing and
selection.
A There are three fundamental
control structures: Remember:
e sequence @ A sequence control structure is simply a series of procedures
e selection that follow one another.
e iteration (looping). @ A selection (if-then-else) control structure involves a choice.
A For the examination you will
need to understand how to §§Understanding loops
create an algorithm to solve a
The last of the three basic steps in coding is the use of loops. You
particular problem, making use
may think that writing a set of instructions with a loop for a
of programming constructs
computer to repeat will be simple, but computer programming
such as sequence, selection
must be exact. The simplest loop construct is called indefinite
and iteration.
iteration. This is where the loop controls no variables, and simply
executes its body repeatedly until a condition is true. Loops can
also control variables and this type of loop is referred to as definite
iteration. So the terms definite and indefinite come from the
1 Write the pseudo-code number of iterations which is, for example, definite in a FOR loop
to create a repeat-until as it is controlled by the loop counter, but indefinite in a WHILE
iteration for 1 - 6. loop because this is a controlled condition and it is not known
how many times the loop will iterate until the condition is true.
! Key points
A A Joop is a way of repeating a statement a number of times until the
condition is met. The condition allows the user to escape from the loop.
A The three combining principles (Sequence, iteration/repetition and
selection/choice) are basic to all imperative programming languages.
You must be able to write and understand programs using these
statement types.
A In indefinite loops, the number of iterations is not known before we
start to execute the body of the loop, it all depends on when a certain
condition becomes true. For example WHILE.
A In definite loops, the number of iterations is known before we start
the execution of the body of the loop.
A A counter is a timer or variable that can be used to count.
8 Iteration and selection
h ed
§ Adding conditions
Remember that whenever you write any algorithm, it must:
@ be detailed enough to describe what needs to be done to solve the
problem
® be unambiguous enough so that anyone could perform the actions
® always give the same results with the same input
® give the correct results.
Let’s now consider the same problem using a flowchart, but add
some extra conditions to meet these requirements (see Figure 8.1).
We can also use structured English:
Wet hair
Loop While only when hair is not clean
Apply shampoo
Lather
Rinse
Figure 8.1 A flowchart End Loop
ae
Exploring different types of loops
Body of —
the loop —
START
Count =—FA6)
oun
4 Selection
We know now that in practice sequences are not a simple line,
sometimes the next action depends upon the last decision. We also
know that this is called selection. In selection one statement or a block
| Sequences are often not a of statements within a set of statements is executed depending on the
simple line; often the next action | state of the processing of the program at that instant.
depends upon the last decision.
oe We started to explore selection when we looked at IF statements
This is called selection.
in the last two chapters.
8 Iteration and selection
Process / Process
~ step(s) 2
-step65)1|
Selection is when a path through
the program is selected based on
a condition.
Figure 8.4 Selection flowchart
70
Conditional sequences
Syntax:
IF <add expression here> THEN
<add command here>
END IF
Example:
IF Answer = 20 THEN
SET Score TO Score + 1
END IF
§ Conditional sequences
To explore programming in terms of what is called a conditional
sequence and loops in more detail, we will look at the rock, paper,
scissors game.
em
Syntax:
REPEAT
<command>
UNTIL <condition>
Example:
REPEAT
SEN GoTG"Ge + |
END UNTIL Go = 10
B Elif
Sometimes you will have a function with multiple conditional
statements. In these instances you need to be careful how you use
IF statements.
4 A WHILE loop is a control flow for x in range(5,10): #do this 5 times (5 through 9)
statement that allows code
to be executed repeatedly
based on a given Boolean Chapter review (es
condition. The WHILE loop can
be thought of as a repeating In this chapter we have explored loops in more detail.
IF statement. It will be Remember, before tackling any computer science task or examination
executed continuously until the question on this topic you must:
condition is met. ® Understand and be able to explain what an algorithm is, what
algorithms are used for and be able to interpret algorithms
(flowcharts, pseudo-code, written descriptions, program code) (More
on this topic in Chapters 1, 2, 3, 6, 7, 14, 5, 11, 10)
® Understand and be able to create an algorithm to solve a particular
problem, making use of programming constructs (Sequence, selection,
iteration) and using appropriate conventions (flowchart, pseudo-
code, written description, draft program code) (More on this topic in
Chapters 2, 3, 4, 6, 7, 14, 5, 11, 10)
® Understand and be able to explain the purpose of a given algorithm
and how an algorithm works (More on this topic in Chapters 2, 3, 4, 6,
7, 14551 810)
® Understand and be able to explain and apply how to code an
algorithm in a high-level language (More on this topic in Chapters 7, 6,
145511810)
™® Understand and be able to explain how the choice of algorithm is
influenced by the data structures and data values that need to be
manipulated (More on this topic in Chapters 18, 6, 7, 14, 5, 11, 10)
® Be able to use sequencing, selection and iteration constructs in your
programs (More on this topic in Chapters 3, 4, 6, 7, 14, 5, 11, 10)
™® Understand and be able to explain the need for, and how to
manipulate, strings (More on this topic in Chapters 6, 7, 14, 5, 11, 10)
® Understand and be able to write code that accepts and responds
appropriately to user input (More on this topic in Chapters 2, 3, 6, ve
14) 5) 11)
aie)
Ea Specification references
You should:
2.5.3 understand the purpose of, and how to use, logic operators
(AND, OR, NOT)
4.3.1 be able to construct truth tables for a given logic statement
(AND, OR, NOT)
4.3.2 be able to produce logic statements for a given problem
one
| In computer science, the Boolean data type is a logical data type
that has one of two values (usually called true or false, 0 or 1).
_ A Boolean is a variable that can It represents the truth values of logic and Boolean algebra.
| hold a single true or false value. Booleans are very important in computer science.
_& A Boolean expression is an
expression that when evaluated : Boolean: AND
is either true or false. The AND operator requires that both of its inputs are true for it
to output true. In searches, you use AND to retrieve records or
pages that contain both terms.
For the examination you will The OR operator requires at least one of the specified conditions
need to: to be true. In searches you use OR to retrieve records or pages that
A understand the purpose of, contain either of two or more terms. The OR operator is generally
and how to use, logic operators used to assess similar, equivalent or synonymous conditions.
_ (AND, OR, NOT).
| & be able to construct truth
§ Boolean: NOT
tables for a given logic The NOT operator reverses the value of a Boolean expression. Thus
statement (AND, OR, NOT). if B is true X is false. If B is false X is true.
2 Questions
1 What is an AND function? 1 Use this book and other
2 What is a Boolean variable? sources such as the internet to
research data types (integer,
3 What is a NOT function?
real, Boolean, char).
9 Booleans and logic gates
s
is I key point § Understanding the concept of logic gates
In computers, transistors act as Logic gates can be understood better if you think of simple switches.
switches. The current flowing Logic functions depend on binary bits of information. You should
through can be turned on or know from Key Stage 3 that a bit can take on only two values as
off. A switch is a also the name it can be in one of two states. We will explore this in more detail
given to a device for connecting later in the book. A simple switch is either open or closed.
LTO NAS TOUT es The bits could be represented by a yes or a no or can be ON
(conducting) or OFF (not conducting).
Whatever the two states might be, we will call one of the states a
2 Use this book and other ‘1’ and the other a ‘0’. It doesn’t matter which we call ‘1’ and which
sources such as the internet we call ‘0’ if we are consistent but we will call the closed or
to research the use of logic conducting state of a switch a ‘1’ and the open or non-conducting
operators (AND, OR, NOT). state a ‘0’.
BOR circuit
A parallel system of switches would make an ‘OR’ circuit (see
Figure 9.1). That is, if any one or more of the switches A or B is in
state ‘1’, the system is in state ‘1’ (conducting).
For a 2-input OR gate, the output Q is true if EITHER input A
‘OR’ input B is true, giving the Boolean expression: (Q = A or B).
We show this in the form of what is called a truth table. The truth
table specifies the state of the system for each state of the switches:
OR GATE A 2
0 O O
wir 1 4
[7 1 0 z
if 1 a
Ov
Oo—
Two One
inputs —— aes output
0 ee OS ae! |
0 0 1 1 We
Figure 9.2 Electrical diagrams showing input and states of
an OR gate
ms
AND circuit
BAND circuit
Let’s also look at how a series of switches makes an ‘AND’ circuit.
That is, all switches must be in the ‘1’ state for the system to be in
the ‘1’ state (conducting).
AND GATE
INPUTS | OUTPUT
O O
ali O
6) O
ee
ee
re
—© a ak
Two ae One
inputs output
1 1 @) 0
You know from earlier chapters that the letters A, G and S are
called variables because we don’t know their values when we look
at the expression. We do know that they can take on the values of
FALSE and TRUE. We also know that S’s value will be determined
once we know the values for A and G.
y NOT circuit
Unlike AND and OR gates, NOT gates have only one input and
one output. The output is exactly the opposite of the input, so if
the input is a 0, the output is a 1 and vice versa. Here’s how we
represent a NOT in electronics.
One ' One
input output
1 P 0 0) P 1
| OUTPUT
;
1 aL
aL O al
O t al
O fe) 0)
Gat.)
Truth tables with more inputs
This makes sense, since it’s an ‘or’ statement, like ‘It is raining or
it is sunny’ and thus is true when either part of the statement A:
‘It is raining’ or B: ‘It is sunny’ is true.
INPUTS OUTPUT
a)
Ae
f-16-
iey
ea
ie)
ey
PES
[ay
TS eS
OQ)
oot
mo
fi)
iP i
Or
On
TO
Ey
Eon
SOn
JS
HE (o)
oO
(a)
KR
(e)
=
i
Cag
als PF
DO
FB
OF
F
Bo sSdzorees OC
BP
FP
PF
@O
FR
O OC
PB
BP
OO
RP
F RP
PrP
PR
OO
mJ ice)
9 Booleans and logic gates
A 0 il
Bl 1 ——
(Gr 1 im
7 a
Figure 9.7 Combination of logic gates to
control section of calculator display
[ Key point
Each segment of a calculator’s display is switched on and off by a
series of logic gates that are connected together. We will explore
For the examination you will the bottom segment coloured in the image.
need to be able to produce logic
statements for a given problem. We need to turn this small segment on if we want to show the
number as a decimal using the computer’s binary system. You
will learn about binary later in the book, but you may remember
it from Key Stage 3. These are the possible numbers with their
binary representation: 0 (binary 0000), 1 (0001), 3 (0011), 4 (0100),
5 (0101), 6 (0110), 7 (0111), 8 (1000) and 9 (1001) — but not if we’re
showing the number 2 (0010).
We can make the segment switch on and off correctly for the
numbers 1-9 by using a circuit of three OR gates and one NOT gate.
If we feed the patterns of binary numbers for these numbers into the
four inputs, the segment will turn on and off correctly for each one.
For example if we feed in the number 7 as the four inputs (0111)
the gates will correctly switch on the segment:
The other six segments of each digit are controlled by other
combinations of logic gates.
oe
Booleans in Python
The truth table for our calculator display for the numbers would be:
Displayed Binary |
A B Cc D
O 0000 O O O O A
1 0004 O 0 O alt iL
D 0010 O 6) 4 O O
3 OOdE 0) O 1 alt at
4 0100 O Al O O ab
6 OMLGO) O ell al O al
i Odtat O al als il 4
8 1000 Ah O O O at
§ Booleans in Python
In Python, Boolean operators are spelled out as the words and, or,
and not.
! Key points
If we want to see if a number (a) is bigger than number (b) by
4 Forgetting the colon “is a more than two we could write:
very common mistake when
def a_bigger(a, b):
first learning Python.
ce rane
=to). =.
4 NOT: A logic gate that outputs
the opposite value to the input. return True
A AND: A logic gate that outputs else:
1 if both inputs are 1. return False
A OR: A logic gate that outputs #can all be written as just
1 if either, or both, of the two #return a>b+2
inputs are 1.
Notice that the if-test does not need to be in parentheses in Boolean.
Chapter review
82
Understanding scope
Example:
PROCEDURE CalculateAverage (Mark1, Mark2, Mark3)
BEGINSPROCEDURE
SET Avg to (Mark1 + Mark2 + Mark3)/3
END PROCEDURE
§ Understanding scope
You should now understand the terms procedure and function
but you will not be able to read or write large computer programs
without understanding the concept of scope.
The scope of something (function, variable, etc.) in a program is
the range of code that it applies to. Let’s look at an analogy in
everyday life. You have people you know on a social networking
10 Structuring programs in a modular way
site. What you write on a public group or wall is global scope, but
if you have a group between just your friends, it’s local scope; only
people in the group can see what you put there — you may even
have special language that you use with your friends that no one
outside this group would understand. This is a bit like defining
a function called friends with things no one outside the group
could access or use.
Project | Project Il
Module A Module B — c
LOCA
LOCAL
5 Variable
Variable
Cannot be accessed
Figure 10.1 Local variables
! Key points
Other parts are global, these are accessible from anywhere.
A A function is a group of
statements that exist within
Project | |
a program for the purpose of
performing a specific task. A
function returns a value.
| ModuleA | ModuleB
A In most programming
languages variables are
treated as global if not GLOBAL GLOBAL
] Key point There is another term that is used to describe scope and that is
visibility. You should be aware that the two terms are the same in
Visibility is another name for the terms of programming.
scope of a variable in a program;
it is the lines of code in the §§Local scope
program where the variable can
be accessed. Unlike global scoped variables, local variables have their scope limited
to the block where they are declared. A block is the body of a control
structure, the body of a subroutine, or a place such as the file or string
] Key points with the code where the variable is declared. So the term local scope
A Different subroutines can have refers to when a variable can be read and modified only from within
local variables with the same the subroutine or place in which it is declared.
names because the functions
Let’s take a look at a ‘Visual Basic’ example:
cannot access each other’s
Sub TestRoutine()
local variables.
Dim X As Long
A A local variable is created
inside a subroutine and cannot Dim Y As Long
be accessed by statements X = 1234
that are outside the function - Y = 4321
it has local scope.
Debug.Print 'X:' & X,'Y: '& Y
A For the examination you will
End Sub
need to understand the need
for, and how to use, global In the above example, the variables (X and Y) can only be accessed
and local variables when within the TestRoutine subroutine. The variables are created when
implementing subprograms. TestRoutine is called and they are destroyed when TestRoutine ends.
It should be understood that these variables cannot be accessed or
modified from any other subroutine.
Local scope has the highest priority with regard to the other scope
levels, so if, in addition to these variables, you have variables with
2 Use this book and other the same names declared at a global scope level (see below), the
sources such as the internet code within the local TestRoutine subroutine utilises the variables
to research how to use global declared within this subroutine, not the variables with the same
and local variables. name declared at the project level.
The term local scope refers to when a variable can be read and
modified only from within the subroutine in which it is declared.
Global scope
Global scope variables are those which have the capability of
Often programmers get errors
being accessed from anywhere within the project that contains
because they declare all
their declaration as well as from other projects that refer to that
variables globally.
initial project.
10 Structuring program
10.Structuring MOC way
in aamodular
programss In Wey
Chapter review
Bs Specification references
1.1.4 understand how to determine the correct
©) You should: output of an algorithm for a given set of data
fp 1.1.1 understand what an algorithm is, what
1.1.6 understand how to code an algorithm in a
: algorithms are used for and be able to interpret
high-level language
algorithms (flowcharts, pSeudo-code, written
descriptions, program code) 1.1.7 understand how the choice of algorithm is
influenced by the data structures and data
1.1.2 understand how to create an algorithm to
values that need to be manipulated
solve a particular problem, making use of
programming constructs (sequence, selection, 2.2.2 be able to use sequencing, selection and
iteration) and using appropriate conventions iteration constructs in their programs
(flowchart, pSeudo-code, written description, 2.3.3 understand the need for, and how to
x. draft program code) manipulate, strings
1.1.3 understand the purpose of a given algorithm 2.4.1 understand how to write code that accepts and
and how an algorithm works responds appropriately to user input
] Key points Whatever the subroutines are called. in your chosen language,
they are powerful tools for abstraction and decomposition. By
A A library is a collection of
identifying a named subprogram you will be able to identify what
files, computer programs, or is being done.
subroutines.
Many subroutines come as part of the library that comes with the
A To import is to bring in from an
language. For example, mathematical problems often need to
outside source.
calculate trigonometric functions.
The import function in a programming system imports new
predefined functions.
PROCEDURE <id> (<parameter>, ...) PROCEDURE CalculateAverage (Mark1, Mark2, Mark3) ALL functions in Python return a value of
BEGIN PROCEDURE BEGIN PROCEDURE None even if there is no formal return.
<command> SET Avg to (Mark1 + Mark2 + Mark3)/3 Because of this there are no procedures. A
END PROCEDURE END PROCEDURE function with no return value is a procedure.
L Functions
Functions are structurally the same as procedures but are based on
mathematical functions. Functions are called by their names in
A function is a group of expressions, along with the required actual parameters. A function
statements that exist within can be included in an expression (e.g. print(max(3,4,6))).
a program for the purpose of
performing a specific task. A
So a function is just like a procedure except that it returns a value.
function returns a value.
In Python a function can even return more than one value. For
example a function could be used if somebody asks you to count
the number of cars in a car park. You would go to the car park,
count, and then report the number of cars to the person who first
asked you. That is a function. A function simply returns another
value back into the program, such as complex calculation results,
the position of the mouse cursor, or the number of cars that entered
the car park.
In Python a function definition MUST come BEFORE it is called.
Functions can return almost anything: numbers, strings,
characters, anything. You can even use functions to replace
procedures completely. This is the case in some languages where
there are no special implementations of procedures.
The concept of a function is vital in mathematics. Functions are
often used in computer languages to implement mathematical
functions. The function computes one or more results, which are
determined by the parameters passed to it. When the function is
called, the calling unit lists the subprogram name followed bya
list of identifiers in parentheses.
Functions
1 What are the two main roles of Parameter can consist of none or more parameters.
a function?
Parameters in functions are called arguments.
Output: Hello!
! Key point You will need to understand scope in order to effectively use
Parameters in functions are often
subroutines as local variables usually:
called arguments.
® only exist while the subroutine is executing
® are only accessible within the subroutine.
§ Optional parameters
Functions can sometimes have optional parameters. In effect these
are default parameters. Not all languages do this but where they
do default parameters are still parameters, but they don’t have to
be given as they are predefined in the programming language
used. In this case, the default values are used.
The following script greets a person. If no name is given, it will
greet everybody:
def Hello(name='everybody’):
'" Greets a person '"'
print(‘Hello '+ name + '!')
Hello('Steve')
Hello()
oe
Return values in subprograms
Chapter review ax
7
12 Testing your code
You now can produce well-documented, efficient code, all laid out
well with good use of whitespace. You may think all is well but
the chances are, however hard you tried to avoid errors, they are
inevitable in any program.
Even if you have coded your program perfectly, the users of your
program will always discover some problem in your application
that you never even dreamed possible.
Although it’s impossible to eliminate every error, this section
1 Use this book and other
describes errors and should help avoid most coding errors.
sources such as the internet
to research types of error
Types of errors in computer programming
in programs (logic, syntax, As much as we may wish to deny it, human beings are not perfect.
runtime). We make mistakes. Programmers are not exempt from this and,
Use this book and other frequently, the mistakes we make are in the programs we create.
sources such as the internet These mistakes lead to issues, defects or, as they are most
to research the use of test commonly known, bugs in the programs.
plans and test data (normal,
The process of fixing these mistakes, of removing the bugs, is
boundary, erroneous).
known as debugging.
5S. eee
12 Testing your code
! Key points
A Often programmers get errors because they use bad variable and
function names, for example a spelling mistake in a variable name. It’s
hard enough to remember variable names without having to remember
which spelling mistake you made.
A Programmers also get errors because they inconsistently use
uppercase and lowercase letters in variable and function names.
Beginner programmers often create a variable with one case, e.g.
‘myScore = 7’, then later on try to reference it with a different case,
e.g. ‘if myscore > 5:’ or even ‘if score > 5:’ and wonder why the code
doesn’t run!
<>
print(‘Hello!')
@ When you forget to declare a variable.
Types of errors in computer programming
Python will say it has a syntax error and point with * to the
exclamation point. The problem is that ! has no meaning in
Python.
The correct code would be:
print(‘Hello World!’) #correct code as in this
#instance Python would
#understand that the ! is part
#of the text
12 Testing
AN your a
code
je i nnn SS
4 “%
3
~
If you had written GCSE instead of class, there would not have
ae)
been a problem.
GCSE = 'Computer Science’ #correct code
If you are using quotes around text and you forget the second one,
or you are using parentheses and forget the second one, you will
also get syntax errors.
print(‘today) #syntax error, no ‘
print(‘today' #syntax error, no )
You may also have a name error. This happens when you have:
® misspelt a variable, function or method name
® forgotten to import a module
® forgotten to define a variable.
But if the computer gives an error message that does not contain
the word ‘SyntaxError’ it must be a runtime error.
Runtime errors
Runtime errors occur whenever the program instructs the
computer to carry out an operation that it is either not designed to
do or will not do.
Going past the last index of a list causes an error. (‘IndexError: list
index out of range’)
2 Question A typo for a method name causes a runtime error or syntax error:
myData = ‘THIS IS IN LOWERCASE:
2 What is a runtime error?
myData = myData.lowerr() #should be one r not two
Runtime errors commonly occur when programming statements
are written in the wrong order or a programmer constructs
instructions that the computer is unable to carry out.
One of the commonest runtime errors is when a program instructs
a computer to divide any number by the value zero. This operation
Types of errors in computer programming
Runtime Error ‘339’ Many runtime errors occur because the coder is using an undefined
component 'MCI32.0CX' or variable or function. This can also occur if you use capital letters
one of its dependencies is not inconsistently in a variable name:
correctly registered: a file is callMe = ‘Today or Tomorrow'
missing or invalid
print(callme) #runtime error, should be
#callMe
Logic errors
Out of the three common errors that occur in programming, logic
errors are typically the most difficult kind of errors to detect and
rectify. This is usually because there is no obvious indication of
the error within the software. The code will run successfully;
however, it will not behave in the way it was designed to. In other
words it will simply produce incorrect results.
12 Testing your code
ne
The code will run but the answer will not be what we want, we
have another example of a logic error:
Output: Result: 18
100
Testing for errors before and during the coding stages
Now we have a correct output, the logic error has been fixed:
Output: Result: 50
Sometimes logic errors remain undetected until an angry user
contacts the programmer to say that their program has performed
some calamitous operation such as paying all the employees of a
2 Questions company too much in their monthly salary!
4 What is meant by a logic So how can logic errors be prevented? Well, the following rules
error? Give an example of should prevent most of the errors occurring:
a logic error in your chosen @ Programmers should fully understand how a finished program
programming language. is meant to behave.
5 A programmer is developing @ Programmers should have thorough knowledge of the behaviour
a new program. Describe the of every operation that is written into the program.
types of errors they would @ Avoid careless programming.
check for. ® Programmers should implement a thorough and rigorous
testing strategy.
Dry-run testing
Dry-run testing is usually carried out on the algorithm which is
written in pseudo-code or as part of a flowchart. This form of
testing is usually done prior to the program code being written.
. 12 Testing your code
y 2 Question
The process involves stepping through the algorithm one
instruction at a time with purposely chosen example test data. A
6 What is dry-run testing? trace table is used by the programmer to keep track of the test
data, its purpose being to demonstrate what went wrong within
an algorithm and pin-point exactly where the problem is. It should
be understood that this form of testing is usually done on a small
scale as it is quite hard work and very repetitive.
Trace tables
A trace table is a technique used to test algorithms to see if any
logic errors are occurring whilst the algorithm is being processed.
! Key point
Within the table, each column contains a variable and each row
A trace table is a method of
displays each numerical input into the algorithm and the resultant
using data to check that a
values of the variables.
flowchart or code covers all
possibilities correctly. Trace tables are particularly popular with people who are learning
to program.
30 34
100 104
aL 2
D 2 2
4 2
102
Testing for errors before and during the coding stages 2
“<
Now we will use this in a simple WHILE loop:
number = 1 #line 1
y=2 #line 2
x=2 #line 3
while number < 4: #line 4 start of the loop
number = number + 1 #line 5 the variable called
#number increases by 1
y=y+x #line 6 the variable y increases
#by variable x
print(y) #added so we can see the
#value of y as an output
Output:
4
6
8
Trace table:
iL 1
2 1 2
3 1 2 2
4 ii 2 2
5 g 2 2
6 9) 4 2
The main advantage of dry-run
testing is it enables programmers 4 2 4 2
to spot errors even before they 5 3 4 2
start writing code. 6 3 6 2
4 3 6 2
5 4 6 2
? Question 6 4 8 2
8 What is a trace table? 4 4 8 D
104
SS
How do you document your tests?
SSS SSS SSS SSS SSS SSS
§ Types of testing
There are three types of test data:
4 Under normal conditions. The application is tested under
normal working conditions and the data that the coded solution
is supplied with is within the anticipated range.
i) Under boundary conditions. The coded solution is provided
! Key point with data that is within the operating range but at the limits of
There are three types of testing: its performance.
under NORMAL conditions, under 3 Under erroneous conditions. An application or program is
BOUNDARY conditions and under provided with data that is outside its limits of performance.
ERRONEOUS conditions. These tests try to break the application and to investigate if
things occur when they shouldn't or vice versa.
106
ee Choosing the test data
ee ne Re ERNE
Chapter review
In this chapter we have explored types of errors and how to test your
code.
We also explored test plans and how to record your tests.
Remember, before tackling any computer science task or examination
question on this topic you must:
® Be able to differentiate between types of error in programs including
logic, syntax and runtime errors
® Be able to design and use test plans and test data (normal, boundary,
erroneous)
® Be able to interpret error messages and identify, locate and fix errors
in a program
® Be able to determine what value a variable will hold at a given point in
a program (trace table)
® Be able to determine the strengths and weaknesses of a program and
suggest improvements
® Understand how to identify and correct errors in algorithms
® Be able to evaluate the fitness for purpose of algorithms in meeting
specified requirements efficiently using logical reasoning and test
data.
13 Algorithm efficiency
cs Specification reference
You should:
1.1.9 be able to evaluate the fitness for purpose of algorithms in
meeting specified requirements efficiently using logical reasoning
and test data
In the first chapter you learnt that there are many solutions to the
same problem and how algorithm efficiency becomes important.
Some algorithms are more efficient than others. It is obviously
better to have an efficient algorithm.
We explored briefly how there are two main measures of the
efficiency of an algorithm: time and space.
Sometimes it’s possible to solve a problem by using what is called a
brute force technique. Yousimplytry out all the possible combinations
of solutions. If you had to sort words with 158 characters when
combined together including spaces, and you could compute
1,000,000,000 possibilities a second, you would still be left with the
need for over 1 x 10149 seconds, which is longer than the expected
life of the universe. So to reduce the time and make the algorithm
more efficient, it is necessary to find a better approach.
Time measure is a function describing the amount of time an
Some algorithms are more algorithm takes in terms of the amount of input to the algorithm.
efficient than others. It is ‘Time’ can mean the number of memory accesses performed, the
obviously better to have an number of comparisons between integers, the number of times
efficient algorithm. some inner loop is executed, or some other natural unit related to
the amount of real time the algorithm will take.
Space measure is a function describing the amount of memory
(space) an algorithm takes in terms of the amount of input to the
algorithm. We often speak of ‘extra’ memory needed, not counting
the memory needed to store the input itself.
108
Comparison
§ Comparison
If we compare three simple algorithms for computing the sum 1
+2+... +m for an integer n > 0 you will see that even a simple
program can be programmed to work faster.
Too many nested loops in any program can make the program
take a long time to execute. Steps such as storing the length of an
array in a different variable, instead of making it read the length
at every iteration of the loop, will help to optimise the code. It also
ensures that the code runs more efficiently.
For the examination you will
Restructuring your code (called refactoring) without changing its
need to be able to determine
external behaviour can also help.
the strengths and weaknesses
of a program and suggest For example, instead of this:
improvements. TOMX Ima:
for y in b:
x= Vy:
yield (x,y)
Chapter review
RECEIVE Name
FROM (STRING)
KEYBOARD
110
Recap: pseudo-code, flowcharts and Python
SEND
<expression>
TO DISPLAY
“SEND ‘Well
done’ TO ©
DISPLAY
= : Pseudo-code_ Python 3 __
IF x < 5 THEN ifx <5:
SEND ‘Yes’ TO DISPLAY print('Yes')
ELSE else:
SEND ‘No’ TO DISPLAY print('No')
“SEND ‘Yes’ / END IF
__TO DISPLAY
112
Recap: pseudo-code, flowcharts and Python
End
Figure 14.2 A counting loop
While the count is less than 100, the program will continue to
print and add 1 to the variable called count. Once it reaches 100
it will stop. It is worth noting here that we can have a pre-
condition loop where the code checks the condition first and
Indefinite iteration is the name
only runs the loop if the condition passes. The loop will not run
given to the repetition of a
if the condition starts false. We can also have a post-condition
sequence where the number of
loop where the condition is checked at the end of the loop each
repetitions is unknown.
time it runs. A post-condition loop will always be executed once,
and if the condition is false at the end of the loop it will be
repeated again.
Comparing the WHILE loop condition in flowchart, pseudo-code
and Python form will look something like this:
4 Remember: "5
ae @ WHILE is a pre-condition loop
@ FOR is a pre-condition loop
@ DO...WHILE is a post-condition loop
@ REPEAT...UNTIL is a post-condition loop.
In pseudo-code you use the following syntax where you want a post-
condition loop. Execute <command> until <condition> is true. The loop
must execute at least once. The red brackets < > are only to show
where you add something — you don’t need to put them in your code.
Syntax:
REPEAL
<add command here>
UNTIL <add expression here>
Example:
REPEAT
Sel correo |
UNTIL Go = 10
SEND 'X' TO DISPLAY
END REPEAT
A common programming error involves infinite loops (i.e. the loop runs
forever). If your program takes an unusually long time to run and does
not stop, it may have an infinite loop. If you run the program from the
command window, press CTRL+C to stop it.
The following Python code creates a simple guess the number game.
import random #import module
guesseslaken = 0 #setting our counter to 0
print(‘Hello! What is your name?’)
114
Recap: pseudo-code, flowcharts and Python
As you can see, while loops and if statements are an essential part
of programming.
In pseudo-code:
WHILE myVar <= 60 #if value of myVar is less than
#or equal to 60
SEND myVar TO DISPLAY #prints the value of myVar on
#screen
SET myVar TO myVar + 1 #adds 1 to the value of myVar
ENDWHILE
Awhile statement is also often called an iterative/iteration (looping)
control statement as it repeatedly executes a set of statements that
are based on a Boolean expression or condition.
As long as the condition of a while statement is true, the statements
within the loop are (re-)executed. Once the condition becomes
false, the iteration terminates and control continues with the first
statement after the while loop.
In pseudo-code you use the following syntax for a count-controlled
loop. The number of times <command> is executed is determined
by the expression. The red brackets < > are only to show where
you add something — you don’t need to put them in your code.
Syntax:
REPEAT <expression> TIMES
<command>
END REREAR
Example:
REPEAT 100-Number TIMES
SENDY toqjOrDISPUAY
END REPEAT
116
Averages, highest and lowest number algorithm
We could write:
SEND ‘please enter 5 numbers' TO DISPLAY _ #string asking i
#the user to enter
#numbers
118
SSS
Nested loops
SSS SSS
Example:
FOR Index FROM 1 TO 500 STEP 25
DO SEND Index TO DISPLAY
END FOR
§ Nested loops
It is time to explore what are called nested loops. They consist of an
outer loop and one or more inner loops. Each time the outer loop is
Nested loops consist of an outer repeated, the inner loops are re-entered and started again as if new.
loop and one or more inner
loops. Each time the outer loop
is repeated, the inner loops are
re-entered and started again as
if new.
120
|
NE STE NestedMNOOPS
loops
|
We must pay particular attention to where the IFs end. The nested
IF must be completely contained in either the IF or the ELSE part of
the containing IF. Watch for and line up the matching END IF.
GET gameNumber (INTEGER) FROM KEYBOARD
IF gameNumber = 1 THEN
Car = ‘Porsche’
ELSE
IF gameNumber = 2 THEN
Car = 'Mercedes'
EOE
Car = 'Ford'
END IF
END IF
= Porsche =:
ce Car = Ford
Mercedes
As the code gets more complex you will realise how important it is
to work out what we need before starting to program. Flowchart
symbols and pseudo-code are the building blocks needed to
express any desired logic in the form of a computer program.
In Python we can use all the following list functions for our list (L):
lo= [1-2 Seas) #populates a list
Using flowcharts or pseudo- L[n] #element n (where n = 0, 1, 2, 3, ...)
code we can easily describe the L[O:n] #the first n elements
purpose of a given algorithm and
L[-n:] #the last n elements
explain how a simple algorithm
eA 7, © #substitute
works.
del L[n] #remove element with index n
L.remove('x’) #removes item x from the list
! Key points L.append(x) #appends x to end of L
4 Functions should be explainable L.remove(x) #removes first occurrence of x from L
in one sentence that doesn’t
L.pop() #returns and removes the last item in the list
contain AND or OR.
L.sort() #puts the list in order
4 You can use functions in your
L.count(x) #returns the number
programs again and again.
eile #does L contain x?
4 A function has three parts: a
name, parameters and a body. L.index(x) #returns index of the first occurrence of x
. Derived structures
e Question
As we have already seen, flowcharts and pseudo-code can be
2 Write a program in pseudo-
represented by basic structures. However, sometimes it is useful
code to take four input values
to use some additional structures, each of which can themselves
and output:
be constructed from the above structures. These are sometimes
4 the total value called derived structures, which are simply structures constructed
4 the highest value from combining other pre-existing structures. Derived structures
4 the lowest value allow a programmer to group different kinds of data or parts of
A the average. code that belong to a single entity.
Choosing the best structure is based upon a few rules:
@ Are you repeating or copying/pasting code you have already
used?
Produce a DO...UNTIL e Which way uses the fewest lines of code? Normally less is
flowchart to show how to make better.
a breakfast of tea and toast. @ There are times when using more lines of code is more efficient
but you should never repeat yourself when coding.
122
Derived structures
Chapter review
In this chapter we have explored loops in more detail and also compared
flowcharts, pseudo-code and Python to see how similar loops would be
shown using the correct syntax.
Remember, before tackling any computer science task or examination
question on this topic you must:
® Understand and be able to explain what an algorithm is, what
algorithms are used for and be able to interpret algorithms
(flowcharts, pseudo-code, written descriptions, program code)
(More on this topic in Chapters 1, 2, 3, 6, 7, 8, 5, 11, 10)
co Specification references
You should:
4.5.1 understand what is meant by high-level and low-level
programming languages and understand their suitability for a
particular task
understand what is meant by an assembler, a compiler and an
interpreter when translating programming languages and know
the advantages and disadvantages of each
] Key points
4 Acomputer’s CPU can only understand instructions that are written in
machine code.
A A compiler is a computer program that translates C, C++, BASIC,
Pascal, and similar high-level programming languages into machine
language.
A An interpreter is a program that executes a source program by reading
it one line at a time and doing the specified operations immediately.
A A high-level language is a computer programming language designed
to allow people to write programs without having to understand the
inner workings of the computer.
126
Different languages and their level of abstraction
Caras
Advantages of C++:
@ C++is best suited for general-purpose and low-level programming.
@ C++ is extremely fast —it works very well for GUI programming
on a computer.
® C++ is a good language to write operating systems, drivers and
platform dependent applications with. It is a good language to
learn to program with.
@ C++ is a good language for engineers.
15 The language computers actually use
Disadvantages of C++:
e Although it is platform independent, C++ is mostly used for
platform-specific applications.
@ C++ is overly complex for very large high-level programs.
@ C++ is difficult to debug.
Java and C# do similar things to C++, but without the opportunity
to do everything you can do in C (like pointer manipulation in
Java’s case).
C#
Advantages of C#:
® C# can be used for web applications on Microsoft computers.
@ C# works well with the Microsoft product line but can be compiled
on OSX/Linux as well.
Disadvantages of C#:
® C# was originally developed largely for the Microsoft platform.
Java
Advantages of Java:
® A Java program can run on any computer.
@ Java can also run on most cell phones.
@ Java is very robust. Robust means reliable and no programming
language can really assure reliability.
® Java is simple: Java was designed to be easy to use and is
therefore more easy to write, compile, debug and learn than
other programming languages.
® Java uses automatic memory allocation and garbage collection.
® Java is object-oriented because programming in Java is centred on
creating objects, manipulating objects and making objects work together.
This allows you to create modular programs and reusable code.
® Java can be distributed and involves several computers on a
network working together.
®@ Java is one of the first programming languages to consider security
as part of its design. The Java language, compiler, interpreter and
runtime environment were each developed with security in mind.
® Java is multi-threaded: this means Java programs have the
capability to perform several tasks simultaneously.
Disadvantages of Java:
® Java is a lot more complicated than C.
® Java is slow, not only slow to run, but also slow to develop.
@ Java works best for high-level enterprise web applications.
® An interpreter is needed to run Java programs. Programs are
compiled into Java virtual machine code called bytecode.
® Java can be significantly slower and more memory-consuming
than natively compiled languages such as C or C++.
128
Different languages and their level of abstraction
Python
Python/Ruby are higher level as they let the programmer forget
about a lot of the details they would need to specify in something
like Java or C#.
Advantages of Python:
@ Python, like the other languages mentioned, has the advantage
of being a high-level language. It is good for rapid prototyping.
® Python code has to be strictly indented but the indentation
helps to make it much easier to read.
® Python is easier to learn than Java or C.
© Python is easy to write, easy to read and easy to understand.
® Python is a little more general than other languages; it does
pretty much everything: web, stand-alone GUI, graphics,
mobile, quick scripts, etc.
@ Python does not use any syntax; instead tabbing and spacing
play an important role in program flow.
@ With the absence of syntax, developers wishing to use Python
need not learn any new rules.
® Python is very robust because of its lack of syntax. Users with
little to no experience with Python can quickly determine
program functionality and begin re-factoring code for upgrades
or bug fixes.
@ Python does not enforce a strict type on containers or variables.
® The integration of Python with languages such as Java and C/
C++ allows Python to remove some stress from the interpreter.
Disadvantages of Python:
® Python is an ‘interpreted language’ and C++ is a ‘compiled
language’. Because of this Python code is slower than C++ code.
@ Python programs also run slower than Java codes.
® Python doesn’t really do multi-processor/multi-core work very
well.
e@ Python adds the overhead of interpretation to the runtime of
the program which can lead to a slower runtime. It is estimated
that Python runs 1-5 times slower then Java or C/C++.
® Because of its easy syntax Python is an easy language to
program in; however it’s not very simple to translate a Python
program into any other language.
15 The language computers actually use
Takes less time to analyse the source Takes a large amount of time
code, but the overall program execution to analyse the source code but
time is slower. the overall execution time is
comparatively faster.
! Key point
Memory efficient. Requires comparatively more
For the examination you will need memory.
to understand what is meant by Continues translating the program until the Generates the error message
a compiler and an interpreter first error is met, in which case it stops. after searching all the errors of
and know the advantages and This makes debugging easier. a program and then listing them.
Hence debugging is comparatively
disadvantages of each. harder.
130
Assemblers, compilers and interpreters
Chapter review
132
16 Binary and hexadecimal numbers
Specification references
: You should: 3.1.3 be able to convert between binary and denary
) 3.1.1 understand that computers use binary whole numbers (0-255)
to represent data (numbers, text, sound, 3.1.4 understand how to perform binary arithmetic
= graphics) and program instructions (add, shifts (logical and arithmetic)) and
= 3.1.2 understand how computers represent and understand the concept of overflow
manipulate numbers (unsigned integers, 3.1.5 understand why hexadecimal notation is used
signed integers (sign and magnitude, two’s and be able to convert between hexadecimal
complement)) and binary
Figure 16.1 On/off symbols Binary code takes each of those combinations and assigns a
number to it, like this:
@ Both Off = 0
e First Off, Second On = 1
All data that is stored in a
@ First On, Second Off = 2
computer is converted to
@ Both On=3
sequences of Os and 1s.
16 Binary and hexadecimal numbers
Maybe you are thinking that it would take rather a lot of switches
and lights to make a computer work like this, but if we had six
lights, and they were like this:
On On Off On Off Off
On On
Figure 16.2 Bulbs on or off
and rather than just giving a light just one score, if we said that
different lights in the sequence had different scores: the first light
32, the second 16 then 8, 4, 2, 1, then the value of those six bulbs
(called a point value) would be:
32+ 16+0+4+0+0 (remember, we only give points if they’re
turned ON!)
§ Binary numbers
Even though computers are based on a binary system, they have
to convert the numbers into our 10 unit decimal system so that we
can understand them.
‘Hello World’ in binary is:
010010000110010101101100011011000110111100100000010101110
11011110 11100100110110001100100
How it is represented in machine code is shown at the top of the
next page.
134
a Converting to binary numbers
demain Mamata
C7 28 2a 2a 3c 5c 2b 00 00 00 00 00 00 6f'00 00
3c 5c 2b 5c 28 2a 2a 00 00 00 00 00 00 72 00 00
4 The word binary comes from
2a 2a 2a 3c 5c 2b 00 00 00 00 00 00 00 6c 00 00
‘bi-’ meaning two. We see
3c 2b 5c 28 2a 2a 00 00 00 00 00 00 00 64 00 00
‘bi-’ in words such as ‘bicycle’
2a 2a 3c 5c 2b 5c 01 00 00 00 00 00 00 21 00 00
(two wheels) or ‘binocular’
2b 5c 28 2a 2a 3c 00 00 00 00 00 00 00 00 00 00
‘(two eyes).
2a 3c 5c 2b 5c 28 00 00 00 00 00 00 00 00 00 00
4 When we say a binary number, 5c 28 2a 2a 3c 5c 00 00 00 00 00 00 64 00 00 00
we pronounce each digit (e.g. 3c 5c 2b 5c 28 2a 00 00 00 00 00 00 48 00 00 00
the binary number ‘101’ is said 28 2a 2a 3c 5c 2b 00 00 00 00 00 00 65 00.00 00
as ‘one zero one’). This is so 5c 2b 5c 28 2a 2a 00 00 00 00 00 00 6c 00 00 00
that we don’t get confused 2a 2a 3c 5c 2b 5c 00 00 00 00 00 00 6c 00 00 00
with the decimal number. 2b 5c 28 2a 2a 3c 00 00 00 00 00 00 6f 00 00 00
A For the examination you will 2a 3c 5c 2b 5c 28 00 00 00 00 00 00 2c 00 00 00
need to be able to convert 5c 28 2a 2a 3c 5c 00 00 00 00 00 00 20 00 00 00
between binary and decimal 3c 5c 2b 5c 28 2a 00 00 00 00 00 00 57 00 00 00
whole numbers (0-255).
§ Converting to binary numbers
Converting decimal numbers to binary numbers is relatively
simple. Let’s explore counting in binary and decimal to see how
the numbers compare.
Decimal |
number How we convert Binary number
9 And so on 00001001
16 Binary and hexadecimal numbers
64 32 16 8 4 9) 4
128
2 Questions
If we have an 8-bit binary number 01100110 and place this in our
ee iiaihe piney code (ialiewes) table it would looklike thie:
decimal number 67. Use eight
binary digits. Decimal digit value 642 32) AGQ i) Samhain
4 Give one reason why we use Binary digit value Mee Me a ce hank li42 2!|
binary to represent data in
computers.
We can now easily convert it to a decimal number as we have:
64+ 32+4+2=102
J Key points : : : :
A A single binary digit (like ‘O’
You then add the two numbers in the far right column, again
or ‘1’) is called a ‘bit’. For
as you would for decimal numbers. Add the numbers following
example 11010 is five bits
the rules of decimal addition (1 + 0 = 1, 0 + 0 = 0) unless both
long.
numbers are a 1.
A The word bit is made up from If they are, we write ‘0’ below and carry a ‘1’ to the next column.
the words ‘binary digit’. (Remember, it is not ‘ten’ but ‘one zero’). We use the rule 1 + 1 +
4 For the examination you will T= Tcarry 1.
need to understand how to 0 ‘ cf Al
perform binary arithmetic
(add, shifts (logical and 1 1 1 0
arithmetic)) and understand
the concept of overflow.
136
i
Adding binary numbers
0 it 1 1
1 il 1 0
0 a Al i}
a i) ll 0
ul i
We start on the right and move across the columns to the left. If
there are no more columns we add a new one.
0 i 1 1
il sl 1 0
ut 0 if 0 fi
1 1 1
If we want to add three binary numbers this is achieved in exactly
the same way, e.g.
Answer = i 0 1 1 0 1
1 1 1 1
Add rightmost column = 1 carry 1
Add next column = 0 carry 1
Add next column = 1 carry 1
Add next column = 0 carry 1 and another 1
The next column will be 0 carry 1
(The decimal would be 13 + 11 + 5 = 29)
” , 16 Binary and hexadecimal numbers acs DA IA
Pg easiness
ne
ons
Sign-magnitude
Sign-magnitude uses the most-significant bit as the sign bit. The
rest of the bits represent the number in the ‘binary’ format. It is a
bit like the number line used in mathematics.
138
Signed and unsigned integers
0111 : +7
0110 6 +6
0401 5 +5
0100 4 a
0011 3 +3
0010 2 +2
0001 1 +1
0000 0 +0
1.000 8 -0
1004 9 a
1010 A e
1014 B -3
1100 C -4
1101 D -5
1110 E -6
14141 F 4
Two’s complement
Two’s complement is the method computers use to represent
signed numbers.
The most-significant bit is the sign bit:
® 0 = positive value
® 1 = negative value.
Because of this a 16-bit signed integer only has 15 bits for data
whereas a 16-bit unsigned integer has all 16 bits available.
To create the negative representation of a number:
® Start with the positive number
@ Flip the bits (change ‘0’ to ‘1’ and ‘1’ to ‘0’)
@ Add the value 1.
Addition and subtraction are accomplished in the same way as in
10’s arithmetic:
— 127 10000001
+) ail 00000001
— 126 10000010
]6 Binary and hexadecimal numbers
aN
O11. uf +7
0110 6 +6
0101 5 +5
0100 a ae
0011 3 +3
0010 2 +2
0001 1 +1
0000 fo) +0
1444 F oi
1110 E =o
1104 D -3
1100 Cc -4
1044 B -5
1010 A -6
1004 9 -7
1000 8 -8
Overflow
One problem that can occur with signed binary numbers is that
of overflow. This is where the answer to an addition or subtraction
problem exceeds the magnitude which can be represented with
the allotted number of bits. Remember that the place of the sign
bit is fixed from the beginning of the problem.
When a positive number is added to a negative number there will
never be an overflow error. The reason for this is apparent when
140
SSS SSS SSS SSS sss sss
Binary shift
§ Binary shift
If we shift the decimal point in a decimal number to the left it
multiplies the number by 10. So 1.2 would become 12. If we move
the point two places it would become 120. This is because we use
a 10-digit numbering system.
Binary uses a 2-unit system and therefore a shift 1 place to the left
Binary shifts can be used to in a binary number is the same as multiplying by 2.
perform simple multiplication/
division by powers of 2. A left shift 1 place looks like this:
O bk
1 O
O Al
O O
ot
Recut | 2 Oe re ne
dl ) 0 0 0) 0 0 0 0
The leftmost 1 is an overflow number as we only have 8 bits
and our binary number is now bigger than 8 digits. When this
happens the CPU drops the overflow digit because the computer
cannot store it, so the computer thinks that 255 + 1 = 0.
4 6) 6 i 8 2) 10 eels eZ 13 14 ALS
4 3) 6 U 8 9 A B C D E F
Hexadecimal to binary
Hexadecimal to binary
Converting from hexadecimal to binary and binary to hexadecimal
is fairly simple. We simply look up each hexadecimal digit to
obtain the equivalent group of four binary digits.
Hexadecimal 0) al D 4 S 6 i 8 9 A B C D E F
O al 10 ALL 10094101 0) 11055 4445.1000 4001 10101011. 1100° 4101 A110 1114
| Decimals to hexadecimal
Converting decimal numbers to hexadecimal numbers is much
harder than converting decimals to binary numbers.
We always work backwards to convert these numbers.
2 Question
If we have a decimal number of 1128 the hex equivalent is
6 How many possible values are calculated as follows.
there in a single-digit base-16
number system? Remainder (in
What to do :—— Division | hexadecimal)
Start by dividing the number by 16, that
is (1128/16).
| Hexadecimal to decimal
What if the number 1128 was a hexadecimal number and not a
decimal number and we wanted to find its decimal equivalent?
This would be calculated as follows:
oe
4640 | vO 9
ae a
TOM a6 16
You may be wondering about the letters. They work the same way
2 Questions
as digits so FA8 working backwards would be:
10 Convert the number 188 to
Sie lhe=tce)
hexadecimal. (Remember to
write down the remainder in 10 x 16 = 160 (remember A = 10 and this has to be multiplied by
hexadecimal, not decimal.) 1600)
11 Work out the decimal
15 x 256 = 3840 (remember F = 15 and this has to be multiplied
representation of the
by 1642)
hexadecimal number D48.
The total in denary would be 4008.
Chapter review
® Be able to convert between binary and decimal
In this chapter we have explored binary and whole numbers from 0-255
hexadecimal numbers. ® Understand and be able to explain and apply binary
Remember, before tackling any computer science task arithmetic including shifts (logical and arithmetic)
or examination question on this topic you must: and demonstrate and understand the concept of
overflow
® Understand and be able to explain how computers
144
17 Computing and data
representation
Specification references
You should:
3.2.3 understand how sound, an analogue signal, is
| 3.2.1 understand how computers encode characters represented in binary
using ASCII 3.2.4 understand the limitations of binary
= 3.2.2 understand how bitmap images are representation of data (Sampling frequency,
represented in binary (pixels, resolution, colour resolution) when constrained by the number of
depth) available bits
§ Translating data
Let’s consider what happens when we put data/information into
a computer. When you enter data into your computer you use a
format that you understand, using characters and numbers that
you are able to read. But you know now that a computer cannot
use the data in this form. It has to be translated into a computer-
readable low-level format. As this is done through an input device,
we call it input. Of course once the computer has processed the
data, for us to understand it, it needs to be converted back into
a format that we understand using an output device, so this is
referred to as output. Together these are referred to as I/O.
In pseudo-code you will often see the words ‘get’, ‘input’ and
‘read’ used for inputting data. For outputting data you will see
the words ‘print’, ‘display’, ‘write’ and ‘put’.
| Character sets
You may be wondering, if computers can only work in ones and
zeros how can things like text be represented? Text is represented
A stringis a data type used by character sets. A character set is simply a list of characters such
to store a sequence of letters, as a, b, c, d, ... and the numerical codes used to represent each
symbols and/or numeric letter or character. By agreeing to use a particular character set,
characters. computer manufacturers have made the processing of text data
easier.
We will explore two character sets: ASCII and Unicode.
~ 17 Computing and data representation
“ Fi
Mb nw I ] Key points
4 Computers only recognise ASCII stands for American Standard Code for Information
binary, computers don’t Interchange. As we have seen computers can only understand
recognise the alphabet. numbers, so an ASCII code is the numerical representation of
A ASCIii (American Standard characters such as from ‘a’ to ’z’, ‘@’ or even an action of some
Code for Information sort.
Interchange) is a 7-bit system ASCH was originally developed to use one byte which is 8 bits.
to code the character set on a You will know from earlier sections of the book that a bit is a
computer. binary digit (0 or 1). You can store 2° or 256 possible values in a
single byte as it has 8 bits.
The original ASCII only uses 7-bit numbers to represent the
2 Question
letters, numerals and common punctuation used in the English
1 What will the following language. As there are 2 possibilities per bit, we have 2’ hence 128
pseudo-code do? possible values it can represent, from 0 to 127 inclusive. Remember
CHAR_TO_CODE('a’) 0 is also a reference so we have 128 possible values to store our
characters.
Each of those 128 values is assigned to a character. For example,
in ASCII the number 65 represents an uppercase letter ‘A’ and
61 represents an equals sign. So if the output sent to a display
receives an ASCII value of 65, it displays an uppercase letter A
on the screen. There is no real reason that A has to be character
number 65, that’s just the number the developers working on
telegraph systems chose when ASCII was first develuag
ee) NULL 0 @
foooa | SOH DC4 1 A Q a, =) me
SIX DC2 “ 2 B R b ;
Spc o debect # 3 c S ¢ 5
eee EDT Dc4 $ 4 D T d t
ENO NAK % 5 E uU e u
ACK SYN & 6 F V . v
BEL ETB a G Ww g Ww
es CAN ( 8 H x h x
= HT EM ) 9 | vy. y
SUB = 2 z} HL J Z.
2 Question ESC + j K [ k {
2 In the ASCII code, what is the FS ' J L \ |
relationship between the code GS , : M m }
for an uppercase letter and RS , S N A n ey
the same letter in lowercase?
US j 2 0 : @ 1) DEE
146
The Unicode character set
! Key points If we want to translate ‘Hello’ into ASCII it would look like this:
§ Writing in hexadecimal
Using this knowledge we can see how this would work if we
wanted to explore the use of hexadecimal.
When we start to program we normally start with “Hello World’.
This looks easy, but let’s explore what is happening if we write
Hello in hex.
We type Hello. This consists of separate letters ‘H’ ‘e’ ‘I’ ‘I’ ‘o”
We can use binary or hex for this. You learnt about these in other
sections of the book, but for this we use hex. First we’ll revise the
equivalents in each system.
om 0000 0
4 0004 aL
2 0010 2
3} 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 i
8 1000 8
¢) 1001 ©)
10 1010 A
tae LOMA: B
Ae 1100 C
AES} LENO D
14 1110 FE
LS dala lal lf
1 Write ASCII ‘Computer’ in So F3C2 in HEX would look like this in binary: 1111 0011 1100
binary. 0010
If we now convert each letter to ASCII we will have:
2 Question
H = Write 48 (hex)
8 What is a universal encoding
system that provides a unique e = Write 65 (hex)
number for every character,
1 = Write 6C (hex)
regardless of language,
program or platform? | = Write 6C (hex)
0 = Write 6F (hex)
148
Data standards
? Questions
9 What do we mean by image
size? Figure 17.1 Pixels on a PC screen
10 How does the resolution of
Bitmaps are always orientated horizontally and vertically. Pixels
an image affect the size of
are usually defined as being square although in practice they may
the file?
be rectangular or have other aspect ratios.
In the majority of situations bitmaps are used to represent images
on the computer.
There are a large number of pixels making up the computer’s
display. To give you some idea of what this means, a modern
monitor is 1920 x 1080 which represents a grid 1920 pixels wide
by 1080 pixels high.
If we change the display settings to 2560 x 1440 there will be many
0|0)0j)0]0j]0 000000 more pixels on the display. Because the monitor has not changed
0 010117! 0 lo1o010 Siz, the pixels will become smaller, making everything on screen
| smaller but much better defined. The advantage of using higher
0 Oric0 0 }010010 resolutions is that smaller pixels let us display images with much
0] 0}0]0}]0/0 {000000 more detail.
0 Pe RSA0 Jo11110
GaniaiAi ‘aaee
i Black and white image using binary
OF On Oc Rog iae | 0 |000000
Using what we now know we can easily describe a black and
Figure 17.2 Image in binary code white image using binary as shown in Figure 17.2.
150
Ss
Colour depth
255
Figure 17.3 Grey levels
24 bit
Moving on from 8-bit grey we have 8 bits allocated to each primary
colour: red, green and blue. In each colour the value of 0 refers to none
of that colour, 255 refers to fully saturated colour. Each component
has 256 different states so there are 16,777,216 possible colours.
If there are fewer than 256 colours in the image, the bitmap will
be the same quality as a 24-bit bitmap but will be stored with
one third the data. Colour and animation effects can be achieved
by simply modifying the palette; this immediately changes the
appearance of the bitmap.
32-bit RGB
This is the same as 24-bit colour but with an extra 8-bit bitmap
known as an alpha channel. This channel can be used to create
masked areas or represent transparency.
152
Photographic images
i Photographic images
Originally cameras used film. They were based on the first pin-
hole camera.
Lens
Film
Subject
Image
Lens
Digital sensor
Subject
———
Image
=
§iSound systems
Original sound is in analogue, it’s how our ears work. But to turn
this sound into something a computer can handle we need to
create a digital sound wave.
154
er Soundsystems
nee Ann |
Sample rate
In analogue recordings, the machine is constantly recording any
sound or noise that is coming through the microphones. In digital
A sample is a point in time where recording you don’t have a constant recording, you have a series
a measurement of an analogue of samples or snapshots which are a measure of amplitude at a
signal is taken (sampled). The given point in time and are taken from the sound being recorded.
unit of sample rate is ‘samples
per second’. This is often Each vertical line indicates a time when a sample in taken.
] ime
expressed in kiloHertz (kHz).
| |
Lower sample rates take fewer Faster sample rates take more
snapshots of the waveform... Snapshots...
156
Sound systems
Chapter review
You should:
1.1.7 understand how the choice of algorithm is influenced by the data
structures and data values that need to be manipulated
2.3.1. understand the need for, and understand how to use, data types
(integer, real, Boolean, char)
2.3.4 understand the need for, and how to use, variables and constants
! Key point
The word variable in programming describes a place to store information
that can change, such as numbers, text, lists of numbers and text.
Another way of looking at a variable is that it’s like a box with a label on
to store something.
Setting the type of a variable helps to prevent errors that might occur
when a program is executed. It also makes the program run more
efficiently. Operations such as data sorting rely on knowing what
type of values are stored. Strings need to be sorted into alphabetical
order whilst reals and integers need to be sorted into numeric order.
§ Data types
We will now explore how data is used in more detail. The most
common types of data and the ones you will be using are called
primitive data types.
Primitive data types are predefined types of data, which are
supported by the programming language.
Data can be stored in many different forms and the proper term
for these forms is data types. It is these forms that determine what
158
sl
Integer data types
but
] Key point float(16 / 8) #this will force Python to return a float
A bit is a binary digit, ‘0’ or ‘1’. #value
C and C++ the data type unsigned short can deal with whole
numbers from 0 to 65,535, whereas short can deal with whole
numbers from —32,768 to +32,767.
i Casting
Casting is when you convert a variable value from one type to
another. In Python, this is done with functions such as int() or
float() or str().
160
ene
Real data types
ee
162
Review of data types
Output:
Arrays and linked lists are both designed to store multiple elements, “%
most often of the same type. An array is an ordered arrangement of ¥
data elements that are accessed by referencing the location within the
array and a linked list is a group of elements, each of which contains
a pointer that points to the following element.
It is fair to say that data structures are used in almost all of today’s
J Key points program or software solutions as they provide a method of
managing huge amounts of data efficiently. For example, this
A For the examination you
could be in a large database or an internet indexing service. In
will need to understand the
most programming situations, efficient data structures are a key
characteristics of structured
to designing efficient algorithms. In fact some formal software
and unstructured data.
design methods and programming languages emphasise data
4 A telephone directory is structures, rather than algorithms, because they are regarded as
essentially a collection of the key organising factor in software design.
pointers called telephone
numbers which link to people. § How the data Is stored
A An integer is a whole number
value, positive or negative, To explain complex data types we will first revisit some of the
with no decimal or fractional knowledge you gained in earlier chapters. In a computer, data is
part. saved or stored in a place called memory. Whatever type of memory
this may be, memory is always divided into units. Memory units can
only contain one item at a time. The amount of data that will fit into
a memory unit varies from computer to computer; understanding this
e Question
is beyond the scope of this book. But each byte of memory is like a
1 What will the following building with its own address called a memory address.
pseudo-code do?
The address of a memory unit never changes, but obviously what
LEN(Edexcel) is stored there will change frequently. Imagine a town with people
living inside the buildings as bits of data. The small town inside
your computer is a very neighbourly place. A program refers to
buildings by name rather than by address, and puts Steve’s data
inside Steve’s building. However, if you need to come up with
hundreds of names for hundreds of buildings it would be very
An array is a data structure made | complex, unless you use what is called an array.
up of a series of variables all of Mathematically, a complex number is a number of the form
the same type, grouped under A + Bi where iis an imaginary number. Complex numbers have a
one identifier. Elements are real and an imaginary part.
accessed using an index.
A list stores a group of items one after the other. It keeps them in
order for you. You can add or remove items as you wish, sort your
list or search through it to see if it contains a specific value.
Imagine a local DVD rental shop; when you want to check if a
particular film is available you would conduct a search. If the film
is available, but has been borrowed by a user, a ‘delete from list’
option could be used to remove the film from the list of those
available. When the film is returned it will be inserted back in
the list.
. 19 Data structures
nS
ie
Tuples are a lot like lists in that they are used to store sequences
> of information. Unlike lists they can’t be altered after they have
been created. Tuples are covered in more detail in Chapter 19
when we explore records.
Dictionaries store values with keys, so you can look them up with
the key. You can use them to build complex, nested data structures
or just for storing values. Dictionaries also support operations like
inserting, deleting and searching.
In programming we need to be able to do all of these operations.
At a high level, these are often called comparison methods and
direct access methods. You may come across the term hashing
which is an example of a direct access method.
§ Arrays
An array is a way to reference a series of memory locations
] Key points (buildings) using the same name. Each memory location is
A An element is an item of an represented by an array element. An array element is similar to
array. Each element can be one variable except it is identified by an index value not a name.
accessed by referencing its An index value is a number used to identify an array element.
location in the array.
In pseudo-code you use the following syntax to assign a value to
4 A variable is a name/location an element of a one-dimensional array. The red brackets < > are
in memory/identifier, used only to show where you add something — you don’t need to put
to store a value which can them in your code.
change during execution of the
code. Syntax:
SET Array[index] TO <add value here>
Examples:
SET arrayClass[1] TO ‘Steve’
SET arrayMarks[3] TO 66
166
Ss
One-dimensional arrays
sssssssnsnsnsssssesees
Pre:
P
§ One-dimensional arrays
Look at this box of eggs, they are an example of a one-dimensional
array. Each has something in common: its ‘egginess’. But each egg
also has a difference. It will be different in weight, size, colour
or even its shape. But what is important here is that each of the
eges has a specific location in the box, an index. It has a position
relative to the other eggs. If we say we want egg 2, it is not egg 11
even though they look alike.
Figure 19.1
Example:
SET arrayValues TO [1, 2, 3, 4, 5]
Then if you needed the letter ‘e’ for example you would call it by
saying:
Item number el 2 3 4 5
Index in array (i A 2 3 4
a b @ d e
2 Question
2 Explain the term one-
The reason why this type of array is referred to as a one-
dimensional array.
dimensional array is because it only uses a single number to point
to the position of array elements.
In the carMakers example above the elements would be indexed as
follows:
It is worth noting that it is
common practice within car_name = carMakers[0] #(would return Ford)
programming for the first element
car_name = carMakers[1] #(would return Land Rover)
within an array to be given an
index of zero rather than one. car_name = carMakers[2] #(would return Vauxhall)
168
Two-dimensional arrays
! Key point
The element in the first row and
second column in an array is
element 11. Rows are the first
dimension. Columns are the
second dimension.
Figure 19.3 Two-dimensional array
Let’s give this array the name letters. Notice that we have five
rows and four columns.
If you wished to define this two-dimensional array as a data
structure, in code you would write it as follows:
letters[5][4]
170
Records and tuples
Also:
And:
172
—
SSS
Records and tuples
woman
Chapter review
In this chapter we have built upon the last chapter and explored complex
data structures.
We also explored arrays and how they can be used.
Remember, before tackling any computer science task or examination
question on this topic you must:
® Understand and be able to explain and apply data types (integer, real,
Boolean, char) (More on this topic in Chapter 18)
® Understand and be able to explain and apply data structures including
records, one-dimensional arrays, two-dimensional arrays.
20 Data and program validation
and veritication
You should:
2.4.1 understand how to write code that accepts and responds
appropriately to user input
2.4.2 understand the need for, and how to implement, validation
Validation
Verification
174
Program validation
SSeS
SSS i rss sss sss
§ Program validation
4 Often programmers get errors Program validation is about asking are you building the right
because they do not validate system? Validation is therefore concerned with checking that the
the user input. A program system will meet the customer’s actual needs.
must be very careful whenever
it accepts external input. § Program verification
4 For the examination you will
Program verification is about asking the question are you building
need to understand the need
the system right? Verification is concerned with whether the
for, and how to implement,
system is well engineered, error free and so on. Verification will
validation.
help to determine whether the software is of high quality, but it
will not ensure that the system is useful.
? Question
Verification therefore includes all the activities associated with
1 Briefly describe the term producing high-quality software: testing, inspection, design
validation testing. analysis, specification analysis.
Validation and verification of data are two ways to check that the
data entered into a computer system is what is required.
1 Use this book and other
sources such as the internet c Data validation
to research how to implement
Validation is an automatic check performed by a computer to
validation.
ensure that entered data is sensible/feasible. It does not check the
accuracy of the data entered. The most common validation checks
are shown in the table.
| Typeofcheck Explanation. —
A Input validation is commonly Length check Checks than an entered data value is no longer or shorter
done with a loop that iterates than a set number of characters.
as long as an input variable Presence check Checks that some data has been entered into a field.
references bad data.
Range check For example, a user of a computer system is likely to
A Input validation is the process be aged between 3 and 110. The computer can be
of inspecting data that has programmed only to accept numbers between 3 and 110.
However, this does not guarantee that the number typed
been input to a program, to
in is correct. For example, a user could be 5 years old but
make sure it is valid before it say that they are 16.
is used in a computation.
Type check also Checks that the data is of a particular type, e.g. check that
A Validation checks that input called a format age data is numeric.
data is sensible, it does not check
else:
print(‘Invalid input!’)
except ValueError:
print('Value error! Please try again!’)
If we want a user to enter a number greater than 18 for example,
we could use the following:
det valid_user_input():
try:
return int(input(/Maximum number: ')) > 18
except ValueError:
return False
while valid_user_input():
print('You have successfully entered a valid number’)
176
Data validation
Range checks
We can use similar code for a range check. Say we want to limit
the maximum age someone can enter:
myData = input('Please provide your age: ')
myData = int(myData)
#we must convert the user input to an
#integer
if myData > 120:
print(‘Error! You cannot be that old!')
Or the minimum age:
myData = input('Please provide your age: ')
vyData = int(myData)
if myData < 6:
print('Error! You cannot be that young!')
Data verification
Verification is performed to ensure that the data entered exactly
matches the data in the original source.
There are two main methods of verification:
© Double entry: data is entered twice and then a check is done
comparing the two copies.
© Proofreading data: this method involves someone checking
the data entered against the original document.
178
Data verification
Chapter review
180
Bits and bytes
| ! Key point Microsoft decided to use the following conventions for file size
and now the whole world uses them:
The magic numberto remember
used to be 1024 but now it’s
1000. kibibyte (KiB) kilobyte (kB) 1024 bytes
megabyte (MB) 1,000,000 bytes (or it’s easier to remember as 1000 kilobytes)
§ Data compression
Data compression is a set of steps for packing data into a smaller
‘electronic space’ (data bits), while still allowing for the original
data to be accessed and used. This is often achieved by eliminating
the repetition of identical sets of data bits (redundancy).
Compression results in much smaller storage space requirements
and often much faster communications.
182
St
Data compression
ss ss sss
Compressing images
The most straightforward way of storing a bitmap is simply to list
Lossless and lossy compression
the bitmap information, byte after byte, row by row. Files stored
are terms that describe if, in the
by this method are often called RAW files.
compression of a file, all original
data can be recovered when The following is a description of the simplest lossless compression
the file is uncompressed. With technique called run-length encoding (RLE) on a simple black
lossless compression, every bit and white image. As stated this works best for bitmaps with only
of data that was originally in the a few colours. Consider the following small, 16 x 10 pixel, 1 bit per
file remains, nothing is lost, when | pixel image of the pi sign.
ee SSS eas 3
Text
Of course long runs are rare in certain types of data. For example,
! Key point
it is unlikely that our example of 20 of the same characters would
ASCII (American Standard Code occur in a typed document. In a standard ASCII document only a
for Information Interchange) few words would even have two characters the same. To encode
is a /-bit system to code the a run in RLE requires a minimum of two characters worth of
character set on a computer. information as a run of single characters actually takes more
space. Even data consisting entirely of 2-character runs would
remain the same size after RLE encoding.
If only two of your friends go to the same restaurant, and each
person orders a different item from the menu, there is no saving
of time or space for the waitress to add how many people require
each item.
But if we compare an ASCII document with a black and white
image that is mostly white, such as a scanned page of a book, it
will encode very well, due to the large amount of contiguous data
that is all the same colour — white.
Anything with relatively few runs of the same colour will not
work as well as images with large areas of the same colour.
184
al
er
Data compression <~-g
ooo
———e———e———o——ooToosa—oo
SS
Soe Cy
LE
Encoding (4 X 4 pixel) tiles
SS ce eae
rea eae ee
ae oain Pepe
Dictionary-based compression
For an easy-to-understand example of compression with text, we
will look at a sentence:
‘Run length encoding makes files smaller; smaller files use run
length encoding.’
Now imagine this as a file. If each character and space in this
sentence made up one unit of memory, the whole thing would
have a file size of 79 bytes.
7 21 Data size, storage and compression
Lossy compression
So far we have seen how all the data in a string can be compressed
without losing anything. The name for this type of algorithm is
lossless = we lose nothing. But we also know that it will only work
where data is repeated in the string. So what can we do with data
which is not like this?
If you take a photograph of a country view, large parts of the
picture may look the same — the whole sky is blue and the grass
is green, for example — but most of the individual pixels are
a little bit different. The lossless system will not compress the
file very well; it could even make the file larger. To make this
picture smaller without compromising the resolution, you would
have to change the colour value for certain pixels to make them
the same before compression. If the picture had a lot of blue sky,
the algorithm could pick one colour of blue that could be used for
every pixel and replace all the variations with the same colour.
If the compression scheme works well, you would not notice the
difference, but the file size could then be significantly reduced.
You would simply lose, hence lossy, some of the more subtle
changes. The more you lose the better the compression.
186
Understanding bandwidth nal
Lossy compression is not just used for images. MP3 sound files
use the same system, disregarding small changes in sounds that
that a listener will not perceive. Again most listeners will never
e Question notice the difference, but to a connoisseur, MP3 could never
4 What is file compression? replace live music or uncompressed sound files, even if they do
take up a large amount of storage space.
§ Understanding bandwidth
We have looked at file size and how images, sounds and text can
be compressed using an algorithm. But most data also needs to be
communicated over wired and wireless networks. If you imagine
a road network, the data size is the size of the vehicle or vehicle
load which you wish to transport. But also important is the size of
the roads, and in computer terms this is called bandwidth as it is
the amount of traffic that can flow at the same time.
F Characteristics
Databases use a series of tables to store the data. A table simply refers to
a two-dimensional representation of data stored in rows and columns.
For example:
Steve Cushing [email protected]
188
Databases are like spreadsheets... aren't they?
We could just keep adding fields for any additional data. This
would be called a flat file database, but these can be very slow, so
most professional databases have different tables linked together.
Let’s look at how that works.
Each of the people in our table buy a product from an online shop.
The company produces a table of sales information.
Now we need to link the two tables together, to relate the data in
one table with another. This is where the relational database gets
its name.
1001 1004
1002 1002
1003 1003
So by referring to the linking table above you can see that Jess
Hadden purchased 1 copy of the product L678 Home.
You are probably wandering why the item_id and key are the same.
What happened to the unique key field? In relational databases
nothing is unique in combined tables. The second key is called a
foreign key which means that the number used in a foreign key
column is not necessarily unique to the linked table, but it must
be unique to the table it is referring to.
In addition to the comprehensive functionality of a relational
database there is aneed to not only develop but also to maintain the
database. IT personnel such as data analysts, database designers
and database administrators all need the ability to modify the
data within a database to produce useful information for both
day-to-day organisational activities and for long-term planning.
22 Databases
4
ee $$
= N
ee
capability to link table cells on one worksheet to those on another
worksheet, and can specify that data be entered in a particular
cell in a particular format. It is also a simple operation to calculate
formulae from a group of cells on the spreadsheet, create charts
and process data in other ways.
Having said this, there are many areas in which spreadsheets are
nothing like databases and the table below highlights this.
No way of making a row (record) unique Individual rows within databases have
the capability to be identified by a
unique ‘primary key’
fyRelational databases
As we have seen, a relational database is a group of data items
assembled into a set of formatted tables in which data can be
searched, accessed and interrogated in a multitude of different
ways without having to reorganise the tables.
The standard user interface to any relational database is the
structured query language (SQL). By using SQL statements,
interactive queries for information can be made for the purpose
of retrieving information from a relational database and for
gathering data for reports.
As well as being quite simple to create and access, a relational
database has the significant benefit of being relatively
straightforward to extend. After the original database is produced,
a new data category can be included without the need to modify
all the existing applications as new tables can be added and linked.
As mentioned, relational databases are a set of tables consisting of
data organised into predefined categories. The tables, which are
sometimes referred to as relations, are comprised of one or more
categories that are arranged into columns. Each row contains a
unique instance of data for the categories defined by the columns.
Databases can be designed so that different users see a bespoke
view of the database that is customised to suit the user’s needs.
For example, a sales manager might wish to view a report on all
190
ee Components
§ Components
The foundation for any relational database management system
(RDBMS) is the relational model and this has three basic
components:
® a store
® a method of creating and retrieving data
® a method of ensuring that the data is logically consistent.
Let’s look at the fundamental components of a traditional
relational database system and how it is designed.
A table in a relational database is also referred to as a ‘relation’. It
is a two-dimensional structure used to store related information.
A relational database consists of two or more related tables.
fact for the primary key to work is that the value it holds must be
unique for each of the records contained within the table.
If we take our personnel database example referred to above,
we know that it contains personal information on all our
organisation’s employees. Now, we need to choose a suitable
column of information, where each field within that column can
uniquely identify each employee’s record, which can act as our
primary key. So why don’t we choose the column containing the
employee’s surname?
Well, this would not work correctly because there may be two
or more people working within the business called Jones, Davies
or Smith. The same problem would occur if we used the column
containing first names or street names. You could use national
insurance numbers, however, their use is quite controversial as a
consequence of certain privacy issues. A better idea would be to
create a column with unique employee identifiers and, these days,
this is what most companies do.
When the primary key has been selected and built into the database,
the database management system will ensure the uniqueness of
the key, so that should you attempt to add a duplicate record with
a key that already exists within the table, the system will disallow
the addition and present you with a warning window.
§ Relationships
Database relationships work by comparing data in key fields. This
occurs between fields that have corresponding names in both
tables. In almost all cases, the fields contain the primary key for
one of the tables, which then supplies the unique identifier for
each record and the ‘foreign’ key in the other table. The foreign
key is a column identified to establish a connection between the
data in two tables.
A link is established between two tables by adding the column
that holds the primary key in the first table to the other table.
The duplicated column within the second table then becomes the
foreign key.
Although the most important responsibility of a foreign key
is to manage the data that is stored in the foreign key table, it
additionally manages changes to data in the primary key table.
The link between the two tables ensures that data integrity is
maintained between the two tables by ensuring that alterations
cannot occur to data in the primary key table, if the alterations
undermine the link to the data in the foreign key table.
If someone tries to delete the record row in a primary key table
or to alter a primary key value, an error will occur if it is linked
192
Index
SSS SSS SSS SSS sss
BiIndex
Database indexes assist database management systems to find
and sort records more quickly. It is really important that when
you produce a database, you should also create indexes for the
columns used in queries to find data.
Indexes in databases can be compared to indexes in books. If you
look at a book’s index, it enables you to find information you want
quickly without having to read through the entire book. Within
a database, the index enables the database software to search for
and find data in a table without having to scan the whole table.
Indexes can be based on a single field or on multiple fields. Indexes
that utilise a number of fields enable the user to distinguish
between records in which the first field may have the same value.
It should be realised, however, that even though indexes greatly
improve the efficiency of a database, tables that possess indexes
need more storage space within the database. Also, the commands
that insert, update or delete data within databases need more
processing time.
When choosing the fields to use for indexes, you should consider
using fields you search frequently, or fields you sort regularly, or
fields that you combine frequently with fields in other tables when
queries are created. It should be realised that if a large number of
the values within a field are identical, then an index might not
significantly improve the speed of queries.
Primary keys within tables are automatically indexed.
Chapter review
194
Open an existing file and changing it
If you already have specified variables you would use these to add
the values like this:
Write compScienceFile, 'fName','IName’','grade'
Read compScienceFile
Basically this reads an entire file into your code.
computerScience[ ] = Read compScienceFile
Or if you want to just read each line at a time you could use
something like this (assuming that the file contains that data in
the order below):
Read compScienceFile
fName = compScienceFile[1]
IName = compScienceFile[2]
grade = compScienceFile[3]
End Read
Each time the above code runs it will put one line of the file into
those variables.
In pseudo-code you use the following syntax to read in a record
from a <file> and assign to a <variable>. Each READ statement reads
a record from the file. The red brackets < > are only to show where
you add something — you don’t need to put them in your code.
Syntax:
READ <File> <record>
Example:
READ myFile.doc Record
mm > 23 Reading and writing to a text file
In Python |
Python has a built-in open() function. This takes a filename as
an argument. Let’s first create a new text file. We could name it
anything we like; in this example we will name it testdoc.txt. We
can also add a combination of a directory path and a filename.
The open() function will only take one argument but, whenever
you need a filename, you can include some or all of a directory
path. The directory path does not begin with a slash or a drive
letter as it is a relative path
#write to a file
with open(‘testdoc.txt', 'wt') as out_file:
out_file.write('This is Computer Science GCSE\nHodder
] Key point Education\nSteve Cushing\n Edexcel’)
Python has built-in methods for #now we will read our file
reading a whole file which makes with open('testdoc.txt’, 'rt') as in_file:
it easier than reading one line at text = in_file.read()
a time.
print(text)
If we only want a few characters from our text file we can use:
with open('testdoc.txt’, 'rt') as in_file:
text = in_file.read(1)
print(text)
196
SSS SSS
In Python
SSS
Output:
This is Comp
Or, to give us more flexibility we can read the lines of our text
directly into an array:
with open(‘testdoc.txt'’, 'rt') as in_file:
content = in_file.readlines()
print(content)
Output:
[This is Computer Science GCSE\n', 'Hodder Education\n’,
‘Steve Cushing\n', 'Edexcel’]
Output:
This is Computer Science GCSE
Hodder Education
Steve Cushing
Edexcel
§ Algorithms in security
If you program anything that works over the internet and needs
to handle confidential information you will have to use what are
called ‘cryptographic algorithms’ to keep the system secure.
Cryptographic algorithms are sequences of rules that are used to
encrypt and decipher code. They are algorithms that protect data
by making sure that unauthorised people can’t access it.
2 Question Most security algorithms involve the use of encryption, which
1 Briefly describe the term allows two parties to communicate but uses coded messages so
hackers. that third parties such as hackers cannot understand the
communications.
Encryption algorithms are used to transform plain text into
something that cannot be understood. The encrypted data is then
decrypted to restore it, making it understandable to the intended
party.
198
sss sss
Caesar cipher
sss
i Caesar cipher |
Caesar ciphers are symmetric. There is one shared key. In a Caesar
cipher, an algorithm replaces each letter in a message with a letter
further along in the alphabet using a number key.
e Key point The cipher simply shifts the alphabet and is therefore also called
For the examination you will need a shift cipher. You need to know what the number key is to
to understand how a Caesar decipher the message. The number key is simply the number of
cipher algorithm works. letters you shift.
The Caesar cipher is one of the oldest types of cipher. It is named
° Question after Julius Caesar, who is said to have used it to send messages
to his generals over 2000 years ago.
2 Briefly describe the term
encryption. Let’s look at a couple of examples.
With a shift key of 1:
Riddle: What is the clumsiest bee?
Answer pee Van CMJOF Ger
Each letter in the first encrypted message above is just the next
letter along in the alphabet because the key is 1.
If we look at this mathematically the encryption formula is:
E (x) =(x+n) mod 26
200
Encryption and networks
Chapter review
a Es Specification §iSearching
reference
There are two types of searches used in computing, linear search
You should:
and binary search.
=, 1.1.8 understand how standard
algorithms (bubble sort, Linear search
merge sort, linear search, A linear search is the most basic search algorithm. A linear search
binary search) work sequentially moves through your collection (or data structure)
-
looking for a matching value.
Let’s look graphically at how a linear search works. We will search
epiulestOmthe keye 25.
Start here ... go through these, to the end ... Stop
14°38 10 —2 615
to Find (eae
202
eFC
Searching
When and if the code finds the key, it stops. As you discovered in
the first example, when it can’t find the key it keeps going until
the end.
~ Unorderelist
d ' 1 — Ordered list
Unordered list:
@ If Anthony Adams was in the list?
@ If Anthony Adams was not in the list?
Ordered list:
@ If Anthony Adams was in the list?
@ If Anthony Adams was not in the list?
How about searching for Xian Xui?
Unordered list:
® If Xian Xui was in the list?
® If Xian Xui was not in the list?
Ordered list:
e If Xian Xui was in the list?
e If Xian Xui was not in the list?
The search is faster on the ordered list if the item is not in the list,
as the ordered list search can terminate sooner because it does
not have to search to the end of the list.
Binary search
If we need a faster search, we need a completely different
algorithm.
If we have an ordered list and we know how many things are in
the list (i.e. number of records in a file), we can use a different
strategy.
The binary search gets its name because the algorithm continually
divides the list into two parts.
204
Searching
Output:
True
Because of this:
@ Binary search requires the input data to be sorted but linear
search does not.
@ Binary search requires an ordering comparison; linear search
only requires equality comparisons.
@ Binary search requires random access to the data; linear search
only requires sequential access.
Print Largest
Largest
new number |
Figure 25.4
206
Sorting
SSS
SSS SSS SSS SSS
§ Sorting
Sort algorithms
There are a number of sort algorithms:
For the examination you will need @ bubble sort
to understand how standard @ heap sort
algorithms (bubble sort, merge @ selection sort
sort, linear search, binary search) | ® Merge sort
work. ® insertion sort
® quick sort.
As with searching, the faster the sorting algorithm, the more
complex it tends to be.
Bubble sort
The simplest sorting algorithm is bubble sort.
The bubble sort works by repeating (iteration). The array is sorted
e Key points
from the first element to the last by comparing each pair of
4 The simplest sorting algorithm | elements in the array and switching their positions if necessary.
is bubble sort.
This process is repeated as many times as necessary, until all of
A
eee ounce standieree | the array is correctly sorted.
sort and bubble sort.
The worst-case scenario is that the array is in reverse order, and
the first element in the sorted array is the last element in the
starting array, for example we have 8, 7, 6, 5, 4, 3, 2, 1 and we want
a sorted list in ascending order.
Let’s explore the sort with these numbers in a random order:
5 itera yi. 3
Here we can see the array
1 ) 6 2 4 3 | afterthe first iteration.
| Sern «3
Similarly, after other
| 5 y. 4 6 3 | consecutive iterations, this
array will get sorted.
ligudesatuk eee > 2
Figure 25.5
25 Search and sort algorithms
co
208
Sorting
Merge sort
Merge sort algorithms are simple and very efficient algorithms for
sorting a list.
In merge sort algorithms the idea is to take an array or list and
break the data into smaller pieces, solve the issue with each list
on each of the small pieces and then combine the pieces again.
Summarising, the main elements of a merge sort are:
@ Divide the data into halves
@ Conquer — solve each piece, by applying To eee
repeatedly (recursively) to them, and then
® Combine the pieces together into a global solution.
Let’s say we are given a sequence of n numbers which we will
first store in an array A[1 ... n]. We want the numbers in our array
sorted in increasing order. This is done by changing the order of
the elements within the array.
We simply:
@ Divide: Split ‘A’ down the middle into two subsequences, each
of size roughly n/2.
e@ Conquer: Sort each subsequence by calling mergeSort recursively
(repeating) on each.
@ Combine: Merge the two sorted subsequences back into a
single sorted list.
Input: [75241630 Output, |0 1234567
as mes
Split
: meraeer(3igs OO
ry
Figure 25.6 Merge sort
J,
25 Search and sort algorithms
Output:
Merge Sort...
Artay (6, 4.3). 5>2; 1]
SplintorlG, AAS by 2 2)
Split to [6] [4, 3]
Split to [4] [3]
Merging [4] [3]
Merging [6] [3, 4]
Split ter5] [2a]
Split to [2] [1]
Merging [2] [1]
Merging [5] [1, 2]
Merging [8, 4, 6] [1, 2, 5]
Arraycdil, 2a 3e4seG]
210
Comparison of sort methods
As you will now know, some algorithms like selection and bubble
sort work by moving elements to their final position, one item at a
time. They sort an array of size N, by putting 1 item in place, and
continue sorting an array of size N — 1. Other algorithms such
as insertion and quick-sort put items into a temporary position,
close(r) to their final position. The algorithm then re-scans the
data, moving items closer to the final position with each iteration.
One technique is to start with a ‘sorted list’ of one element, and
merge unsorted items into it, one at a time. To compare sort
systems we need to think about the complexity of the algorithm,
programming costs, memory space requirements and the number
of function calls required. We also need to compare the best- and
worst-case behaviours and to do this we must make assumptions
about the input data, caching, and the behaviour on already-
sorted or nearly-sorted data.
Chapter review
Specification references
4.2.3 understand the concept of a stored program
J : You should: and the role of components of the CPU (control
4.2.1 understand the function of the hardware unit (CU), arithmetic/logic unit (ALU), registers,
: components of a computer system (CPU, main clock, address bus, data bus, control bus)
memory, secondary storage) and how they in the fetch-decode-execute cycle (the Von
work together Neumann model)
aaa
(T aa
(a a ae
Ae ,
Input/output
214
SSS
Input/output
SSS sss ss
1 Use this book and other Nearly all software programs now have a graphical user interface
sources such as the internet (GUI). This means the program uses graphical controls, accessed
to research the input-process- via a mouse, touchpad, touchscreen or keyboard.
output model. A typical GUI includes a menu bar, toolbar, windows, buttons
2 Identify the inputs, processes and other controls.
and outputs for:
Macs and Windows PC operating systems have very different
4 a mobile phone
user interfaces, but they share many of the same elements, such
A a modern television set. as a desktop, windows, icons, pop-ups etc.
Hardware devices also include a user interface. A typical TV
remote has a numeric keypad, volume and channel buttons, mute
and power buttons. The remote is a user interface.
While user interfaces can be designed for either hardware or
software, most are a combination of both.
e Questions
2 List six input devices.
3 Briefly describe the term operating system.
3 Use this book and other sources such as the internet to research the
function of the hardware components of a computer system.
26 The computer systems
ee Aa architecture
%
4
a
lia F Output devices
Humans can also output data and information. We can do this
a
with physical pressure and movement using our hands, feet, head
and eyes. We can output noise by clapping, speech and singing.
The most popular output devices for a computer used to be the
2 Question screen/monitor, printers and speakers. Today we have a plethora
4 List six output devices. of new output devices from 3D virtual glasses and heads-up
displays to electronic paper and voice synthesisers.
Of course these components must work together. They are all
connected via the motherboard.
216
Motherboard
e Questions | Motherboard
6 What is the purpose of the The hardware within a computer system includes the CPU (central
CPU? processing unit), which is situated on a printed circuit board called
7 Define a computer system. the motherboard.
There is also the hard disk drive, the RAM (random-access
memory), optical drive and other circuit boards such as the graphics
and sound cards.
The motherboard is the central
These are all regarded as hardware because if you removed the
printed circuit board (PCB) that
case you could physically touch the devices; however, you should
| holds all the crucial components
of the system. not do that unless you know what you are doing! The hardware
refers only to the electronic and electro-mechanical parts of the
computer, not the casing.
ay
| Buses
! Key points A bus is a collection of parallel wires used for data transmission.
A bus is part of the circuit that connects one part of the
A A bus is part of the computer
motherboard to another. The more data the motherboard’s bus
architecture that transfers
can handle at any one time, the faster the system. The speed of
data and signals between
the bus is measured in megahertz (MHz), as is the speed of the
all the components of the
CPU (see below). Motherboards have buses for data, addresses
computer.
and control and each one transfers data from one computer
4 A bus is a Collection of component to another.
wires through which data
is transmitted from one i The CPU — central processing unit
component to another.
This internal device is often referred to as the ‘computer’s brain’
and it is the piece of hardware that is responsible for the compute
in computer. If you did not have the CPU, you would not have a
computer.
218
The CPU — central processing unit
Just like our brain, the CPU’s purpose is to process data and it
does this by performing functions such as searching and sorting
data, and calculating and decision making using the data.
What this means is that every task you carry out on a computer
whether it is designing a spreadsheet, writing an email, playing a
game or searching the internet, the central processing unit deals
with all of the data processing which makes those and many more
tasks possible.
! Key points The history of the CPU is very interesting. People define the CPU
in different ways; some people include the main memory in the
A Main memory is any form CPU and some just use CPU as an alternative word for processor.
of memory that is directly
accessible by the CPU, except The first CPU chip was invented in November 1971. It was basically
for caches and registers. a 4-bit processor designed for a calculator. Its instructions were 8
bits long. Program and data were separate.
A A CPU is a type of processor
that runs a computer system. Since those early days of CPUs with a single-core processor there
The name processor is a more have been many changes to the ‘brain’ in our computers.
generic term but is often used
Processor speed has doubled every few years. One big change
to mean the same thing. The
to the CPU was the addition of a second core called a dual-core
only problem with using the
processor. Each core has its own cache and controller. The benefit
term processor when referring
of this is that each core functions as efficiently as a single core.
to the CPU is that there will be
Because the two cores are linked together, they can perform
other processors in a system
operations twice as fast as a single core can.
but only one CPU.
Imagine making your breakfast which includes buttered toast and
a cup of tea. However fast you work, some tasks will need your
full attention. For example, you can’t butter the toast and pour
the tea at the same time. But if you had a second person to help
you and they made the toast and you made the tea, the process
would be much faster — providing you were each given the correct
instructions of course.
The technology has not stopped there. The next step was quad-
core processors. You may be thinking that each addition multiplies
the processing power of a single-processor machine, but it does
not always work like this. The software running on the machine
has to be designed to take full advantage of all the processors.
._
i 26 The computer systems architecture
\
Some ARM processors designed for mobile devices can even
interpret Java bytecode directly.
The CPU undertakes instructions it receives from programs
in what is called a cycle. Going back to the making breakfast
example, obviously if you worked faster you could produce it
quicker. Maybe the addition of a faster kettle would help too.
The CPU not only has a number of cores, it also has speed. The
speed of the CPU is measured in how many cycles it can perform
in a second. The name given to one cycle per second is a hertz. A
CPU that processes 1 million cycles per second is said to have a
speed of a megahertz, and a CPU that can handle 1 billion cycles
per second is said to have a clock speed of one gigahertz.
Therefore to have a very high CPU speed is a good thing, because
] Key point more instructions per second get executed. The problem is that
The clock chip is the electronic the faster it is, the hotter it gets, and the more power it needs.
device in a computer that
Most CPUs now are at least 2 GHz.
controls the timing of signals.
Most people would not notice differences between one processor
speed and the next speed higher unless they play the very latest
2 Question
computer games. If we go back to our breakfast analogy, however fast
you work and however many friends you have to help you, if the
9 What is a chip and how is it instructions are not clear and the things you need are not available,
attached to the computer? you will not be any faster. With CPUs programmers have a part to
play in maximising the speed of the cores they have.
A processor contains the following components:
@ Arithmetic and logic unit: performs arithmetic and logical
operations on data
® Control unit: fetches, decodes and executes instructions
® Internal buses: to connect the components
® Internal clock: derived directly or indirectly from the system
clock.
220
Factors affecting processor performance
Internal buses
2? Questions
An internal bus is a type of data bus that only operates inside the
10 What is an arithmetic logic computer or system. It carries data and operations like a standard
unit (ALU)? bus; however, it is only used for connecting and interacting with
11 What does the Arithmetic internal computer components.
Logic Unit (ALU) do?
The CPU bus is internal to the CPU and is used to transport data
to and from the ALU.
Internal clock
A clock is a signal used to synchronise things inside the computer.
The beginning of each clock cycle is when the clock signal goes
from ‘0’ to ‘1’; marked with an arrow in the diagram. The clock
signal is measured in a unit called hertz (Hz), which is the number
of clock cycles per second. A clock of 100 MHz means that in one
second there are 100 million clock cycles.
Number of cores
A CPU can contain one or more processing units. Each unit is
called a core. Each core contains an ALU, control unit and registers.
Today computers often have two (dual-core), four (quad-core) or
more cores. CPUs with multiple cores have more power and can
therefore run a number of programs at the same time.
26 The computer systems architecture
You may think that a dual-core processor will have double the
speed of a single core but it does not work like that because each
CPU has to communicate with the other and this uses up some of
the extra speed. Also some tasks cannot be split up effectively so
do not benefit from more cores.
Clock speed
The clock speed of a processor is stated in megahertz (MHz)
or gigahertz (GHz). Basically the faster the clock, the more
instructions the processor can complete per second, but there
are limits to how fast a CPU can run. If the clock tells the CPU
to execute instructions too quickly, the processing will not be
completed before the next instruction is carried out and it can
also overheat.
On-board cache
J Key point The on-board cache is a type of high-performance RAM built
For the examination you will need directly into the processor. Cache has both size and type. It
to understand the function of enables the CPU to access repeatedly used data directly from its
different types of main memory own on-board memory. We will explore this in more detail in
(RAM, ROM, cache). Chapter 27 when we look at memory.
Instruction sets
The user has no control over the instruction set. It is built in to
the CPU and cannot be changed or updated. But together with
processor architecture, the built-in instruction set does affect the
CPU’s performance. Some instruction sets are more efficient than
others, enabling the processor to do more processing at the same
speed as others. Processor benchmark tests can be used to measure
the speed at which the processor can carry out instructions.
Chapter review
222
2/ Memory
Es Specification reference
You should:
J Key points 4.2.2 understand the function of different types of main memory (RAM,
| 4 Just like humans, computers ROM, cache)
rely a lot on memory. They
need to process and store
A computer has to store both programs and data whilst they are
data, just like we do. However,
being used and when the computer is turned off. It does this
computers store data in digital
using a storage device which stores data and programs either
format in a reserved location
temporarily or permanently. The main storage or memory (often
and of a set location size.
~ called primary storage), is the area in a computer in which data is
me 4 Computers have two types
stored for quick access by the computer’s processor.
; of storage systems, primary
storage and secondary There are two fundamentally different types of storage:
storage. ® Primary store / main memory (often just called memory)
A Primary storage or main
® Secondary store (also known as backing store).
memory Is directly connected The main memory is where the operating system resides. The
to the motherboard and is main computer memory is divided into two types, Read-Only
the place where programs Memory (ROM) and Random-Access- Memory (RAM).
and data are kept while being
used.
Data within a computer’s main memory is actually stored in
individually addressable memory cells. Structures such as arrays,
lists and trees are simulated to make the data more accessible to
e Questions the data’s users. The computer is capable of determining what
an individual memory cell contains by a process referred to as
1 What is RAM? reading. The contents of a memory cell can also be changed (a
2 What is an array? process referred to as writing) but when something is written to a
memory cell its former contents are lost.
Main memory has the following characteristics:
1 Use this book and other
@ Its contents can be accessed directly by the CPU.
sources such as the internet
@ It has very fast access times.
to research how data is stored
@ It has a relatively small capacity.
on physical devices (magnetic, The contents of RAM are lost when the computer is turned off
optical, solid state). (volatile) but the contents of ROM are retained (non-volatile).
¥ 27 Memory
ee
224
Cache memory
SSS sss
§iCache memory
Cache memory is a special type of RAM and is part of the primary
store. The cache is almost always located on the same microchip
as the CPU. This means it can be accessed much quicker than
ordinary RAM. Processors often have separate caches for data
and instructions. By executing a program from cache memory, a
program also runs more quickly.
The basic purpose of cache memory is to store program instructions
that are frequently re-referenced by software during operation.
Fast access to these instructions increases the overall speed of the
software program. But cache memory is much more expensive
than ordinary RAM, so computers don’t have much of it.
The more cache the system contains the better, because it is faster
! Key points
and fewer memory locations within it will be forced to share the
A Volatile memory is a type of same cache line. Most programs use very few resources once they
storage whose contents are have been opened and operated for a time. This is because
erased when the system’s frequently re-referenced instructions will be cached. The more
power is turned off or cache the system has, the more likelihood that a particular
interrupted. memory fetch will find the data it requires in the cache; this leads
4 Non-volatile memory is to fewer main memory accesses and better performance.
typically used for the task Computers with slower processors but larger caches tend to be
of secondary storage, or faster than computers with faster processors but less cache.
long-term persistent storage.
Examples are ROM and hard
drives.
Chapter review daxJ
A The computer stores all In this chapter we have explored computer memory.
program data in memory
Remember, before tackling any computer science task or examination
locations. It knows these
question on this topic you must:
locations by their addresses.
® Understand and be able to explain and apply the function of different
types of main memory (RAM, ROM, cache).
28 Secondary storage
Ds Specification references
You should:
4.2.4 understand how data is stored on physical devices (magnetic,
optical, solid state)
4.2.5 understand the concept of storing data in the ‘cloud’ and other
contemporary secondary storage
There are two physical limits to magnetic hard drives: data density
! Key point
and disk speed.
In magnetic storage, magnetic @ The data density defines how much information can be written
material is given a polarity. on any given area of the disk. Higher data density would give
That polarity is then read and higher capacity drives, but this is limited by what is called the
depending on the direction is super-para-magnetic effect.
output as a binary 1 ora 0. @ The spindle speed is how fast the disk spins. Spindle speed is
another way of increasing the data store size, but this is limited
by the speed of the motor used.
Polycarbonate |
layer
Laser beam -
and sensor
Figure 28.2 The layers of an optical disk
228
Solid-state disks (SSD)
] Key points The polycarbonate disk layer contains tiny dents (pits) and flat
spots (lands), which cause light to be reflected back off them.
4 CD-R (CD-Recordable), DVD-R
(DVD-Recordable) and BR-R The reflective layer is there to reflect the laser
(Blueray-Recordable) discs A layer of lacquer covers the reflective layer to protect it from the
can, with minor exceptions, artwork.
be written to only once. Data,
once recorded, cannot be Artwork can be either screen printed or written onto this surface.
overwritten or deleted. The laser beam reads and writes to the disk and is reflected back
4 Disks with the RW(Rewritable) to a sensor, which converts it into electronic data.
suffix can be written to
repeatedly, by deleting or Advantages of optical storage devices:
overwriting old data to make @ Easy to store and carry.
room for new data. ® Optical disks are read in a number of devices such as audio and
A The introduction of DVD led TV systems.
to a five to ten times increase @ Very easy to use.
in storage capacity compared @ Long lasting if looked after properly.
to CD. Blu-ray discs increased
Capacity by five to ten times
Disadvantages of optical storage devices:
over DVD. This was achieved @ Data on write-once disks (CD-R, DVD-R and BR-R) are
mainly by using a blue laser permanent and cannot be changed.
rather than a red laser and ® Optical disks require special drives to read/write.
improved lenses. This allowed ® Optical storage is expensive per GB/TB in comparison with
for a much smaller-focus other methods.
laser beam which enabled the @ There are no standards for longevity tests.
recording of much smaller and ® Can easily be scratched and damaged by heat and light.
higher density pits on the disc. ® Easily broken.
! Key point
Disadvantages of solid-state disks:
@ They have limited storage capacity when compared with normal
“3
ae é
For the examination you will need magnetic hard Aneus
: ee ney gata: aren e Random write speeds of solid-state drives can be four times
“ Beeical mewers Unaghens: slower than for normal magnetic hard drives.
peel sere) @ The cost per MB stored is higher than for magnetic drives.
Chapter review
Es Specification references
You should:
4.2.5 understand the concept of storing data in the ‘cloud’ and other
contemporary secondary storage
4.4.3 understand how software can be used to simulate and model
aspects of the real world
§jCloud storage
‘\ « Cloud storage uses magnetic Cloud storage means ‘the storage of data online in the cloud’. In
and increasingly solid state cloud storage, data is stored and is accessible from multiple
storage at a remote location. distributed and connected resources that comprise a cloud via the
S| 4 For the examination you internet.
will need to understand the
In cloud storage, data is stored on servers and can be accessed
concept of storing data in the
across the internet. The data is stored across multiple servers that
‘cloud’ and other contemporary
can be in many locations. The physical environment where the
secondary storage.
servers are is usually owned and managed by a hosting company.
Cloud storage systems are increasing in popularity as a cost-
effective back up for businesses and individuals. Some modern
software even backs up the data to remote cloud-based servers
1 Use this book and other automatically, sometimes every few seconds.
sources such as the internet to
research the storing of data in Examples of cloud storage systems include Dropbox, Google Docs,
the ‘cloud’. Xdrive and Microsoft Cloud. Amazon Web Services even allow
the user to map a drive in the cloud and format it.
Cloud computing now lets the user access all their applications
2 Question and documents from anywhere in the world.
1 List five criteria that you would Cloud computing has led to a major change in how we backup
need to consider in developing data and store information.
a policy for backing up your
data.
Given the many advantages, Apple, Google and Microsoft have
all developed cloud-based data services.
232
Cloud storage
ee
=
234
Cloud computing systems
i
@ Universal access. You don’t carry your files and documents with
you, they stay in the cloud, and you access them whenever you
have a computer or mobile and an internet connection. All your
documents are instantly available wherever you are.
® Device independence. The user is not limited to working on
a document stored on a single computer or network. You can
change computer and even change to your mobile device, and
the documents follow you through the cloud.
2 Questions Disadvantages of cloud computing:
®@ Limited features. Many web-based applications do not have as
3 Describe the benefits and
many features as conventional computer programs but this is
drawbacks to a rural school in
changing and some new apps have enhanced features.
moving to a cloud computing
@ Given the many advantages, Apple, Google and Microsoft have
model.
all developed cloud-based software services.
4 What are the implications of
cloud computing to computer
programmers? Chapter review
Cs Specification reference
You should:
4.2.3. understand the concept of a stored program and the role of
components of the CPU (control unit (CU), arithmetic/logic unit
(ALU), registers, clock, address bus, data bus, control bus) in the
fetch-decode-execute cycle (the Von Neumann model)
236
Fetch the next instruction
Chapter review
238
You should:
4.4.1 know what an operating system is and how it 4.4.3. understand how software can be used to |
manages files, processes, hardware and the simulate and model aspects of the real world — |
user interface 6.1.3 understand the legal impact of using
4.4.2 understand the purpose and functions of utility technology (intellectual property, patents,
software (managing, repairing and converting licensing, open source and proprietary
files; compression; defragmentation; backing software, cyber-security) on society
up; anti-virus, anti-spyware)
Application Software
Word processors Datopaces
Spreadsheets
Computer Internet
Games Browsers
Hardware
CPU, disks, mouse,
printer, etc.
- 7 Shares out
ee” system memory
Loads and runs
other software
applications Handles system
==> orrors and
alerts user
a | ~~
Moves data to Manages system
? Questions and from the Allows software to security
hard disk communicate with
i State three examples of hardware
operating systems which are Figure 31.2 Tasks of the operating system
used in different computer
devices. Some of the most popular operating systems are:
@ Windows
2 What is operating system
@ Windows CE
software?
@ Macintosh OS X (Mac OS X)
@ iOS GPhoneOS)
® Linux
@ Android Phone
2 Use this book and other
® Blackberry (RIM OS)
sources such as the internet
® Solaris (SunOS)
to research the purpose and
@ AIX
functions of utility software.
@ IOS (Cisco)
®@ XOS (Extreme Networks)
® IronWare OS (Foundry).
System software
Memory management
The operating system manages the CPU, allocates memory,
accesses disk drives, controls printers and much more. All the
input/output functions of the computer are controlled by the
operating system. The operating system is totally responsible for
memory management. It keeps tracks of memory use and decides
which process will get memory, when and how much.
The operating system memory management functions include:
® controlling the location of memory, dealing with the transfer
of programs in and out of memory when the process no longer
needs it or when the process has been ended
® carrying out a process called scheduling where it manages the
CPU, organising the use of memory between programs
® organising processing time between programs and users
® keeping track of processors and the status of any process
running.
I/O management
The operating system manages all the input and output devices
including controlling the backing store and all peripherals such as
scanners and printers. It does this using what are called drivers.
31 Software
Use
Software driver Specially written program which translates the commands from
the operating system into commands that the hardware will
understand.
File management
The operating system handles the organisation and tracking of
files and directories (folders). It also saves or retrieves these from
a computer disk.
The operating system does the following file management activities:
@ allows the user to perform tasks including the creation of files
and directories
® allows the user to save files to a backing store
@ allows the user to rename, copy, move and delete files
@ keeps track of where files are located on the hard drive through
either a file allocation table (FAT) or the New Technology File
System (NTFS).
Security
Computer systems often have multiple users. These users are often
running multiple processes and these processes must be secure. The
operating system maintains security and access rights of users.
The operating system does the following security activities:
® controls the access of programs, processes and users to the
computer resources
@ ensures that all access to system resources is controlled
® ensures that external I/O devices are protected from invalid
access attempts
® provides authentication features for each user by means of a
password.
Error handling
In any computer, the operating system deals with errors and user
instructions. Errors can occur anytime and anywhere including
errors in the CPU, in I/O devices or in the memory hardware.
The operating system does the following error management
activities:
® monitors the system for any errors that occur
®@ takes appropriate actions to ensure correct operations
® closes the system if errors are terminal.
242
System software |=
: si
Be Pe
For the examination you will Virus scanner (utility) To protect the system from trojans and viruses
need to understand the purpose Disk defragmenter To speed up the hard disk. Defragmentation picks up
and functions of utility software (utility) all of the pieces of data that are spread across the
(managing, repairing and drive and puts them back together again.
converting files; compression; System monitor (utility) To look at the current system resources
defragmentation; backing up;
anti-virus, anti-spyware). Utility software is a kind of system software designed to help
analyse, configure, optimise and maintain the computer.
Application management
It is the operating system that provides information about all user
programs running on your computer. It does this by handling
everything from user programs to system programs including
everything from the printer spooler to the servers.
The application packages, such as word processors and
spreadsheets, are what most users buy a computer for. Without an
e Questions operating system they could not execute (run). The OS also provides
these applications with tools and services such as printing and
3 What is the purpose of a
fetching data from a hard disk. Without an operating system, you
device driver?
cannot use your word processing software spreadsheet software
4 What is utility software? or any other applications.
5 What is the purpose of disk
With graphical operating systems, the application also manages
organisation?
the menu facilities and windows supported and provided with the
6 What is a defrag? operating system.
The operating system does the following application management
activities:
® loading a program into memory
® executing the program
® the complete execution of code, data manipulation, register
management etc.
® provides a mechanism for processing all internal communication.
Back screen with text requires Higher chance of user making Lower chance of users Requires more electrical
less electrical energy. errors when typing in commands. making errors. energy.
Human-computer interaction
Human-Computer Interaction (HCI) is a branch of computer
science dedicated to understanding the relationship between
people and computers.
You may think that communication with the user is the least
important function of the operating system, but system users
often judge the complete system by its user interface rather than
its functionality. A poorly designed interface cannot only cause
a user to make errors, but poor user interface designs have, in
recent years, been the reason why so many operating systems
are rejected by users. Most modern operating systems use a GUI
(Graphical User Interface) so we will explore this in more detail
by looking at the main characteristics.
Gul characteristics
Characteristic Description
windows Most GUI designs have multiple windows to allow different
information to be displayed simultaneously on the user’s screen.
These windows can be anything from folders to software applications.
pointing Pointers are little arrows that you move across the screen by
directing your mouse or touch. Pointers can be used to select
and use icons, select options in menus and to reposition folders
and icons on the screen.
244
Application software
rotating This is where you use two fingers — one finger moves up while the
other finger moves down the touch screen to rotate an object.
swiping Swiping is where you swipe your finger across the touch screen
to scroll through a document or turn the page.
Translation software
We looked at translation software in earlier chapters but in
summary the purpose of translator software is to convert
program source code into machine code that can be executed on
the processor.
Translation software includes assemblers, compilers and interpreters.
Each performs a different task:
- An assembler (meaning one that assembles) is a computer
-_ program which translates assembly language to an object file or
~ machine language.
246
Application software
Chapter review
: You will often see the terms ‘client/server’ and ‘peer-to-peer’ when
e Question you read about networks, These terms describe a particular
1 What is a network? networking architecture. A peer-to-peer network has no central
server. Each workstation on the network shares its files equally
with the others. There’s no central storage or authentication of
users. We will return to these types of network later in the chapter;
1 Use this book and other for now we will focus on client/server networks.
sources such as the internet
There are a number of basic components of client/server computer
to research the different
networks and these are described below.
ways that computers can be
connected in a network.
32 Networks
ay
Server
Clients
Figure 32.1
250
Types of network ¢
Types of network
Local area network (LAN)
! Key point A LAN is characterised by high-speed transmission over a
For the examination you will
restricted geographical area. If the LAN is too large, signals need
need to understand the different
to be boosted. A networked school or home usually contains a
single LAN. Sometimes a single building will contain a few small
types of networks (LAN, WAN)
LANs. Occasionally a LAN will span a group of nearby buildings
and usage models (client-server,
but no more than this, which is why we say it has a restricted
peer-to-peer).
geographic area.
32 Networks
ye
an
? Questions
While LANs operate where distances are relatively small, wide
2 What is the geographical area
area networks (WANs) are used to link LANs that are separated by
of a LAN?
large distances that range from a few tens of metres to thousands
3 What is the geographical area of kilometres. The internet is the biggest example of aWAN. WANs
of a WAN? are often under collective or distributive ownership. The internet,
4 What is a web server? for example, is not owned by any one person or organisation, it is
distributed by all its service providers for the mutual benefit of all.
§ Network topologies
Bus topology
Bus networks, which have absolutely nothing to do with the
system bus of a computer, use a common backbone to connect all
devices.
Client 1 Printer Server Scanner Client 2
Router
gu OP peer © pepper,
Client 3 Client 4 Client 5 Client 6 Client 7
252
Network topologies
SSS
] Key point grows so there are more than a few dozen computers connected to
the backbone bus, then it is probable that performance issues will
For the examination you will need start occurring. Finally, if the backbone cable suffers a catastrophic
to understand the characteristics failure, then the entire network effectively becomes unusable.
of network topologies (bus, ring,
star, mesh). Advantages of bus topology:
@ It is easy and cheaper than other types of wired network to install
as a consequence of requiring only a small quantity of cable.
? Question ® The lack of dependency on a central device which is present in
5 Describe the term network. a star topology makes the system more flexible.
Disadvantages of bus topology:
@ It performs well only for a limited number of computers because
as more devices are connected, the performance of the network
3 Use this book and other becomes slower as a consequence of data collisions.
sources such as the internet @ The impact of a single cable failure makes this type of wired
to research how network data network more vulnerable than other wired networks.
speeds are measured.
Star topology
Nearly all wired home networks use the star topology. This
topology is, therefore, better understood than many other
A router is a device that directs networks. The star network has a central connection point referred
messages between computers in to as a ‘hub node’ that could be a device such as network hub,
a network. switch or router. The router on its own cannot be the hub node of a
network. It needs to be linked to a switch although in practice they
are usually in the same box. Devices usually connect to the hub
with network cable that is referred to as an ‘Unshielded Twisted
Pair’ (UTP) Ethernet.
Computer Printer
Figure 32.3
e Question | Star networks generally require more cable than bus topologies;
however, a failure in any star network cable will only restrict
6 Describe a star network.
access to the computer that is connected via that cable and not the
entire network. It should be realised, however, that if the hub
fails, the entire network also goes down.
& 32 Networks
4,
Ring topology
When every device has exactly two neighbours for communication
purposes, the network layout is referred to as a ring topology.
Client 4
Client 3
Client 1
gS
aa
Client 2
Peer-to-peer network
Figure 32.5
Mesh network
The latest network arrangement is mesh networking. In a mesh
network each node connects to at least two other nodes and
can connect to every other network node. If this happens, the
arrangement is referred to as being ‘fully connected’.
2 Question
10 Briefly describe the term web
server.
Figure 32.6
256
Network topologies
Wireless network
Router
Chapter review
Electrical signal communication via the Electrical signal communication via the Optical signal communication via the
wires inner conductor of the wires glass fibres
Noise contamination high Medium noise contamination Very low noise contamination
Can be affected by external magnetic Less affected by external magnetic Not affected by magnetic interference
interference interference
Lowest cost of the three communication Moderately expensive compared with Most expensive of the three
media coaxial cable communication media due to the cost
of the electronic components needed
Bandwidth
Bandwidth affects the amount of data that can be transferred in a
given amount of time. The quantity of information a channel can
convey over a given period is determined by its ability to handle
the rate of change of the signal called its frequency. An analogue
signal varies between a minimum and maximum frequency and
the difference between those frequencies is the bandwidth of that
signal. So the bandwidth of an analogue channel is the difference
between the highest and lowest frequencies that can be reliably
received over the channel.
Digital signals are made up of a large number of frequency
components. Only those within the bandwidth of the channel
can be received. It follows that the larger the bandwidth of the
channel, the higher the data transfer rate can be and the more
accurate the transmitted signal can be.
260
SY
Network protocols
Noise
All transmission media generate some noise. As the signals pass
through a communications channel the atomic particles and
molecules in the transmission medium vibrate and emit random
electromagnetic signals as noise. When the wanted signal is
not significantly higher than the background noise, the receiver
cannot separate the data from the noise and communication errors
occur. Fibre optic cable has the least noise of all the transmission
media used in networks.
TCRAR
When we meet someone in business we shake their hand as a
ereeting. This is true in computing too, when two computers
connect in a network they first use a handshake.
For computers to work together they have to use what are called
protocols. A protocol is a set of rules which governs the transfer
2 Use this book and other of data between computers.
sources such as the internet
to research validation and
Protocols are essential for any communication between computers
and networks. They determine the speed of transmission, size of
authentication techniques.
bytes, error checking methods, and even whether communication
3 Use this book and other
will be asynchronous or synchronous.
sources such as the internet
to research how to protect Like any delivery system, in networks we need a delivery model.
software systems from When you use the postal system you can ask for guaranteed
cyberattacks. delivery. On the internet TCP/IP (Transmission Control Protocol/
Internet Protocol) is the most common delivery model. TCP is in
charge of the reliable delivery of information, while IP is in charge
of routing, using the IP addressing mechanism.
TCP/IP (Transmission Control
Protocol/Internet Protocol) is a
All networked computers communicate through what are called
transmission control protocol /
protocol suites. The most widely used and most widely available
internet protocol consisting of
protocol suite is the TCP/IP protocol suite. TCP/IP is a 4-layer
a set of standards that control
system as shown in the diagram.
how data is sent across networks
The application layer
including the internet.
The application layer provides applications for file transfer, remote
control and internet activities.
Webserver
Your laptop
Some of the most common application layer protocols are:
e FTP (File Transfer Protocol): a standard network protocol that
is used to transfer computer files from one host to another host
over a TCP-based network, including the internet.
e HTTP (Hypertext Transfer Protocol): HTTP is the underlying
protocol used by the world wide web. HTTP controls how
messages are formatted and transmitted. It also controls the
actions of web servers and browsers in response to received
commands. When you enter a URL in your browser it sends an
HTTP command to the web server instructing it to fetch and
transmit the requested web page.
e IMAP (Internet Message Access Protocol): IMAP is an internet
standard protocol used by email clients to retrieve email
messages from a mail server over a TCP/IP connection.
@ HTTPS (HTTP Secure): a protocol for secure communication
Over a computer network. It is widely used on the internet.
HTTPS consists of communication over Hypertext Transfer
Protocol (HTTP) within a connection encrypted by Transport
Layer Security.
Figure 33.1 Layers of TCP/IP
ce
eee
Ne twiorkeproionos
® Simple Mail Transfer Protocol (SMTP) is a TCP/IP protocol used
in sending and receiving email. SMTP can only send data to a
computer that is turned on, so it is only used to send data from
the sender to mail servers and then on to other mail servers.
POP3 and IMAP are used to fetch email/manage a mailbox
when the receiving computer is turned on.
@ SNMP (Simple Network Management Protocol): created as a
way of gathering information from different networked systems
in a consistent way. It can be used in connection to a wide array
of systems. The method of querying information and the paths
to the relevant information are standardised. There are many
versions of the SNMP protocol, and most networked hardware
devices implement some form of SNMP access.
@ IMAP, POP and SMTP protocols are discussed more fully later
in this chapter.
TCP is suited for applications that UDP is suitable for applications that
require high reliability, and transmission need fast, efficient transmission, such
time is relatively less critical. as games. UDP is also useful for
servers that answer small queries from
huge numbers of clients.
If two messages are sent along a Messages are not ordered. When
connection, one after the other, the two messages are sent out they may
first message arrives first. Data cannot arrive in a different order, If ordering is
arrive in the wrong order. required, it has to be managed by the
application layer.
264
Data packets ( ~
§ Data packets |
Anything sent between computers has to be divided up into what
are called packets. Packets are small data units. Even a PowerPoint
or spreadsheet has to be divided into packets to be transmitted.
Imagine an object built of Lego where each brick is a packet.
Of course once transmitted the packets have to be put back together
in the correct order. These protocols wrap each data packet with
a set of instructions. The name for this is encapsulation. Once all
the packets have been received, the client needs to know they have
all arrived so the very last packet is a special one called a frame.
Packet 1 Packet 2
Message
tobe | mmmt Menace. Xl mam |Receved
sent ge
Packet 3 Packet 1
° Question Checksum
A simple error-detection scheme is used in which each transmitted
5 What is a packet?
package is accompanied by a numerical value based on the number
of set bits in the message. The receiving station then applies
the same formula to the message and checks to make sure the
accompanying numerical value (the checksum) is the same. If not,
the receiver can assume that the message has been corrupted.
§ Email protocols
When you send and receive an email there are three different
2 Questions
protocols that can be used to handle the email:
7 What is a mail server? e IMAP
e POP
e SMTP.
IMAP and POP are used to receive mail. SMTP is used to send mail.
SMTP
Client
Mail Server
Figure 33.3 Sending email using SMTP
Receiving emails
The software you use on your local machine is called a client and
this is connected to what is called a mail server. When someone
sends you an email it travels from the sender’s email client
to
their mail server using SMTP. Their mail server then uses
the
recipient’s email address to determine where the mail should
be
sent and then delivers it to the receiver’s mail server.
266
SS
Email protocols
Sending emails
When you send an email you will always use some form of SMTP,
which is a totally different protocol to IMAP and POP.
When you click on Send for an email message, your mail client
7 Use this book and other
contacts the SMTP server. The server authenticates who the user
sources such as the internet
is using the login id and password, then it receives the email
to research the importance of
message from your client. The mail client then places the sent
email in either the local sent mail folder or in the case of IMAP,
network security.
the sent email folder on the server.
Chapter review
In this chapter we have explored different ways that ® Understand wired and wireless connectivity (More
data is transferred over networks. ,_on this topic in Chapter 32)
Remember, before tackling any computer science task Understand that network data speeds are
or examination question on this topic you must: measured in bits per second (Mbps, Gbps)
® Understand that data can be transmitted in ® Understand the role of and need for network protocols
packets using layered protocol stacks (TCP/IP) including the terms Ethernet, Wi-Fi, TCP/IP, HTTP.
® Understand what is meant by the world wide web HTTPS, FTP and email (POP3, SMTP, IMAP)
(WWW) ® Understand the need for embedded systems and
® Understand the components of the WWW including their functions (More on this topic in Chapter 37).
the terms web server, URLs, ISP, HTTP, HTTPS, HTML
(More on this topic in Chapter 32)
ee
Spree
an
oa
=
Specification references
:You should:
5.2.1 understand the importance of network security 5.2.4 understand methods of identifying
and be able to use appropriate validation and vulnerabilities including penetration testing,
authentication techniques (access control, ethical hacking, commercial analysis tools and
physical security and firewalls) review of network and user policies
5.2.2 understand security issues associated with the 5.2.5 understand how to protect software systems
fi Issues
With all the benefits technology brings it also brings issues. The
J Key points
only time anything is private in computing is when the computer is
A HTTPS provides an encrypted off-line. We all put private information onto the internet but only
version of HTTP for more in the hands of people who we believe will look after it. Never put
secure web transactions. any private information on the open public internet. When using
4 For the examination you will online banking, make sure the connection is encrypted (HTPPS).
need to understand what is
meant by the world wide web File sharing
(WWW) and components of The illegal sharing of music and films over the internet has
the WWW (web server, URLs, become more and more of a problem as internet speed has grown
ISP, HTTP, HTTPS, HTML). faster. Famous court cases based upon intellectual property rights
and privileges have hit the news.
34 Personal vulnerabilities
Software piracy |
! Key points
With the growth of the use of the internet more and more people
are using illegal, sometimes borrowed, software. Billions of pounds
A Copyright and patent laws
benefit society because
are lost as a result of pirated software.
they encourage creators of
new products to make them Hacking
available to the public.
Hacking refers to accessing data without authority. It has become
A Quarantine is a separate area more and more of a problem over the years. Sometimes the hackers
of a hard disk that holds an unlawfully access the data, but do not damage it. But often hackers
infected file until a virus can hack into data to either steal from it, or to cause malicious damage.
be removed. Either way it is illegal to hack into someone else’s data.
A Content filtering is a process
of restricting access to certain Web content
material on the web. The world wide web has revolutionised communication. It is a
4 Spam is unwanted, unsolicited wonderful place for information exchange and self-expression.
email. Anyone can gain an extensive global audience. But in recent
A A domain name is a human
years this has led to a rapid growth in negative materials such as
readable name for a resource
pornographic material, instructions for making bombs, and hate
location on a network. It is propaganda.
changed to a numerical IP
Invasion of privacy
address by a DNS server.
The chances are that the more you use the internet the easier it is
A Authentication is any process
for someone to invade your privacy. Your data is probably stored
by which someone Is verified
around the world in a wide range of databases. Your activity and life
to actually be who they claim
are probably being monitored. And it is not just the internet where
to be.
this is a problem; when someone goes shopping with a loyalty card
A Authorisation is any process
their details and what they have purchased are recorded. Critics of
in which someone is allowed,
the system argue that these loyalty cards compromise the privacy
after being authenticated, to
of customers, but the retailers who use them argue that they are
access data or information
a way of generating special offers targeted to the right customers.
that they requested.
Computer viruses
It is estimated a single computer virus can result in over £10
million of damage. With so many viruses about, even in email
attachments or in downloadable files and screen-savers, the issue
of computer viruses is a growing problem.
270
Issues
? Question Encryption
1 Explain the term encryption. When we are using networks for example ordering something on-
line or completing forms, we often have to send others our personal
information. A typical transaction might include our names, e-mail
! Key points | addresses, physical address, phone numbers, passwords and even
A Bugs are errors in software, our credit card details. Information security is provided on computers
Causing the program to and over the networks by a variety of methods but many of these
function in a manner that was methods use encryption. Encryption is a way to enhance the security
not intended. of a message or file by scrambling the contents so that only someone
A A hyperlink is an item ona with a secret code or key can read it.
web page that directs the There are two main types of encryption but the most common is
user to another location when what is called symmetric encryption. Basically this just means that
clicked. the same key, or secret, is used to encrypt and decrypt the data. The
A The term backdoor refers to an second main type of encryption is called asymmetric encryption
undocumented, unauthorised and this uses two interdependent keys, one to encrypt the data, and
method of gaining remote the other to decrypt it.
access to a system, bypassing
normal authentication methods. Deep linking
A For the examination you will Users of the world wide web often move from page to page following
need to understand different hyperlinks, which can appear as images or text. Originally hyperlinks
forms of cyberattack (based were at the heart of the world wide web. Sometimes the hyperlink takes
on technical weaknesses a user away from the website they are on to another website. Deep
and behaviour) including linking occurs when one web page includes a hyperlink to a web page
social engineering (phishing, that is buried deep within another site. This can give the appearance that
shoulder surfing), unpatched the hyperlinked pages are part of the original website. A growing number
software, USB devices, digital of companies are concerned that their data will be stolen.
devices and eavesdropping.
Cookies
A A worm is self-contained
Internet cookies are very small text files. They are downloaded
malware.
from the web server to a web browser. They record the activities
Bluetooth is a wireless on the browser, and then send them back to the server. Whilst
protocol/service allowing cookies can be very useful for autocompleting forms, they can
enabled devices to also be used by advertisers and less scrupulous users.
communicate and transfer
data. Unlicensed computer professionals
A Discovery mode is a Bluetooth Plumbers and electricians, doctors and most other people who
scheme that allows devices provide aservice to the public are usually licensed by law. Computer
to automatically detect and professionals are not. This makes it almost impossible to know
connect with other devices. whether the person who is fixing your computer is competent and
A Bluesnarfing is unauthorised reliable. Remember that people accessing your computer have full
access of information using a access to all of the data on it.
Bluetooth device in discovery
mode. Downloadable components
There are a growing number of cases in the news of children
starting to play a free game, and downloading extra characters
and plug-ins, not realising that these are all charged for. The use
of a free game followed by purchasable components is a growing
34 Personal vulnerabilities
issue, particularly with mobile phone use. Free games also provide
a good method of delivering worms and malware.
For the examination you will need
to understand: Bluetooth vulnerability
A methods of identifying The use of Bluetooth on mobile phones and tablets has led to
vulnerabilities including security vulnerabilities.
penetration testing, ethical
Like many other secure channel protocols, Bluetooth works using
hacking, commercial analysis
an initial phase called pairing where two devices establish short
tools and review of network
shared keys of a few numbers, followed by a data protection phase
and user policies
where data is encrypted and authenticated with those shared keys.
4 how to protect software
systems from cyberattacks, The problem is that eavesdroppers were sometimes able to obtain
including considerations enough information to guess the pairing PIN, which opened up
at the design stage, audit the data on the paired device. New protocols have now been put
trails, securing operating in place to attempt to stop this.
systems, code reviews to
remove code vulnerabilities in
programming languages and
HTTPS
bad programming practices, Hypertext Transfer Protocol Secure (HTTPS) is a secure version of
modular testing and effective HTTP. It is HTTP that is used for the data that is sent between
network security provision. your browser and the website that you are connected to. The ’S’ at
A Security is the process of the end of HTTPS stands for secure. It means all communications
protecting systems and data between your browser and the website will be encrypted.
from unauthorised access.
HTTPS uses one of two secure protocols to encrypt the data
A An open network is one whose communications: SSL (Secure Sockets Layer) or TLS (Transport
specifications and protocols Layer Security). Both the TLS and SSL protocols use an
are public, allowing different ‘asymmetric’ Public Key Infrastructure (PKI) system.
companies to produce
compatible products. When your browser requests a HTTPS connection, the website
will first send its SSL certificate to your browser. This certificate
contains the public key needed to begin a secure data session.
Based on this initial exchange, your browser and the website then
initiate the ‘SSL handshake’.
i Security measures
272
Security measures
Firewalls
A firewall is a network security system that monitors and controls all
incoming and outgoing network data transfer based on a set of what
are called security rules. Firewalls can be either hardware or software.
® Hardware firewalls can be purchased as stand-alone hardware
but they are also often found in broadband routers.
@ Software firewalls are software based and must be installed
on the computer. The software can then be customised.
There are a number of techniques firewalls use to prevent harmful
information from getting through the security wall and these include:
® Packet filtering: looking at the data in each packet entering or
leaving the network
© Application gateway filtering: applying security mechanisms
or blocking services such as FTP
@ Proxy server filtering: intercepting all messages entering and
leaving the network and hiding the true network address.
In addition to limiting access to computers and the networks they
are connected to, firewalls can be used to allow remote access to
a private network using secure authentication.
Chapter review
In this chapter we have explored system security. (phishing, shoulder surfing), unpatched software,
Remember, before tackling any computer science task USB devices, digital devices and eavesdropping
or examination question on this topic you must: (More on this topic in Chapter 35)
® Understand and be able to explain the importance = ™ Understand and be able to explain methods of
of network security (More on this topic in Chapter identifying vulnerabilities including penetration
35) testing, ethical hacking, commercial analysis tools
and review of network and user policies (More on
® Be able to use appropriate validation and
this topic in Chapter 35)
authentication techniques (access control, physical
security and firewalls) (More on this topic in ® Understand how to protect software systems
Chapter 35) from cyberattacks, including considerations
at the design stage, audit trails, securing
® Understand and be able to explain security issues
operating systems, code reviews to remove code
associated with the ‘cloud’ and other contemporary
vulnerabilities in programming languages and
storage (More on this topic in Chapters 35 and 36)
bad programming practices, modular testing and
® Understand and be able to explain different forms effective network security provision (More on this
of cyberattack (based on technical weaknesses topic in Chapter 35).
and behaviour) including social engineering
35 Social engineering and cyber-security
Specification references
You should:
5.2.1 understand the importance of network security 5.2.4 understand methods of identifying
and be able to use appropriate validation and vulnerabilities including penetration testing,
authentication techniques (access control, ethical hacking, commercial analysis tools and
physical security and firewalls) review of network and user policies
5.2.2 understand security issues associated 5.2.5 understand how to protect software systems
with the ‘cloud’ and other contemporary from cyberattacks, including considerations
storage at the design stage, audit trails, securing
< 5.2.3 understand different forms of cyberattack operating systems, code reviewstoremove
: (based on technical weaknesses and behaviour) code vulnerabilities in programming languages
including social engineering (phishing, shoulder and bad programming practices, modular
surfing), unpatched software, USB devices, testing and effective network security
digital devices and eavesdropping provision
] Key points
4 A stealth virus is a virus that attempts to avoid 4 A file infector virus is malware that copies itself into
detection by masking itself from applications, other program files (exe, dil, bin, sys, com, drv); when
redirecting commands around itself. the infected file is executed it loads into memory
4 A retrovirus is malware that attacks or bypasses the and tries to infect other files. It is also known as a
anti-virus software and can potentially destroy the parasitic virus.
virus definition file. 4 A polymorphic virus is malware that changes its
form each time it is executed, avoiding detection/
removal by anti-virus software.
274
Examples of social engineering
! Key points
? Question A Anti-virus software is an application designed to detect and remove
malware and viruses.
1 Describe three main security
measures required when A A trojan horse is non-replicating, malicious code contained inside
using an internet-connected what appears to be a useful program.
computer. A Spyware is a non-replicating program used to track user activities,
monitor their machines and relay personal information to attackers.
user’s bank.
Blogging = Blagging is the act of creating and using an invented scenario
_ to engage a targeted victim in a manner that increases the
~ chance the victim will divulge information or perform actions
that would be unlikely in ordinary circumstances.
§ Cyber-security
Cyber-security relates to the protection of information systems from
theft or damage. There are many cyber-security threats including
those listed in the table below.
Also known as advertising-supported software. This is any software package that automatically
shows adverts, such as a pop-up. It may also occur in the user interface of a software package or on
an installation screen. The main object of adware is to generate revenue for its author. Adware, by
itself, is harmless. However, some adware may include spyware such as keyloggers.
| Computer viruses A computer virus is a self-replicating program that attaches itself to existing programs and can
then easily spread from one computer to another. Viruses can increase their chancesof spreading
to other computers by linking to files on a network system. A virus attempts to make a computer
system or data files unreliable.
| Denial of service This is an attempt to make a computer or network system unavailable to its users. A DoS attack
(DoS) attacks is usually focused on preventing an internet site or service from functioning efficiently or at all,
temporarily or indefinitely. The attacks usually target sites or services hosted on high-profile web
_ servers such as banks and payment websites (for example, PayPal).
Hacking means finding weaknesses in an established system and exploiting them. A computer
hacker is a person who finds weaknesses in a computer system to gain unauthorised access. A
hacker may be motivated by a multitude of reasons, such as profit, protest or challenge.
| Keyloggers A type of spyware that logs the keys used when someone types on a keyboard and can collect data
from an infected computer, including personal information such as websites visited, user logins and
financial information.
Physical threats (for Computer systems consist of physical items such as keyboards, monitors, memory sticks/remov
able
example, loss/ theft storage devices, base units and servers. These can be lost or stolen very easily — especially memory
of devices) — sticks and portable storage devices.
276
Cyber-security
Spyware A type of malware (malicious software) installed on a computer system that collects information
_ about users without their knowledge. Spyware is usually hidden from a user and can be difficult to
detect. Spyware is often secretly installed on a user’s personal computer without their knowledge.
Spyware can also install additional software or redirect web browsers to different websites. Some
Spyware can change computer settings, which could lead to slow internet connection speeds or
changes in web browser settings.
Trojans A Trojan often appears to be something which is wanted or needed by the user of a PC but is actually
a stand-alone malicious program designed to give full control of the infected PC to another PC.
They can be hidden in valid programs and software. Trojans can make copies of themselves, steal
information, or harm their host computer systems.
A worm is a stand-alone computer program that replicates itself so it can spread to other computers.
Like a computer virus a worm can use a computer network to spread. But unlike a computer virus, it
does not need to attach itself to an existing program. Worms almost always cause some harm to a
network, even if only by consuming bandwidth.
2? Question
2 Briefly describe the terms 4 Adware is software that displays advertising and gathers information
on browsing habits.
a) adware.
A A worm is a Self-replicating program that does not alter files, but
b) phishing
resides in active memory and propagates itself by means of computer
c) pharming networks to consume resources.
d) spyware. A Pharming is a cyberattack intended to redirect a website’s traffic to
another, fake site.
Malicious code
Viruses, keyloggers, worms and many of the items in the table
above are different types of malicious code. They are often
confused and thought of as being the same thing. Both are pieces
of code that is able to replicate itself. However, they are distinctly
] : different with respect to the techniques they use and their host
e Key points system requirements. This distinction is due to the way they
4 A bot is a type of program that | attack the host systems.
runs automatically, performing Malicious code is also known as malware and includes: computer
tasks directed by an attacker. viruses, trojans, adware and spyware.
A A virus hoax is an email
message that warns users of Protecting your personal data from cyberattacks
a non-existent virus or other The following preventative measures can help a user protect
malware. themselves from cyberattacks.
A A secure site is a website that ® Do not give out personal information over the phone, on the web
uses encryption techniques to or in an email unless completely sure of the recipient. Always
secure its data. verify the authenticity of requests for any personal information.
A A personal identification
@ Encrypt your data.
number (PIN) is a numeric
® Keep your operating system, browser, anti-virus and other
password, either assigned by
critical software up to date.
@ Never click on links in emails. Even if you do think the email is
a company or selected by a
legitimate, go to the website and log on directly. Be suspicious of any
user.
unknown links or requests sent through email or text messages.
277
35 Social
ee
nn eee engineering and oem
cyber-security
278
ene
Cyber-security
enrvercenenneee
279
ah
i 35 Social engineering and cyber-security
a7
! Key points implications. The companies that sell software are aware of these
security vulnerabilities and regularly release security updates to
A Shouldering is observing a address these flaws. Microsoft, Adobe, Oracle, Firefox and Apple
person’s private information are just some software companies that regularly release security
over their shoulder, e.g. updates. Some software companies like Google Chrome and
cashpoint machine PINs. Flash even release updates automatically and many of these are
A Malware is an umbrella term invisible to users.
used to refer to a variety of
Outdated and unpatched devices present a major security risk as
forms of hostile or intrusive
the unpatched software remains weak, leaving the user open to
software.
cyber-crime attacks. Updating systems with the latest security
patches protects against attacks that exploit vulnerabilities.
Applying security updates often also addresses technical issues
with the software and improves the software’s performance.
280
Ce Te—*e Cyber-security
CAPTCHA
CAPTCHA stands for Completely Automated Public Turing test
to tell Computers and Humans Apart. It is a program used by
some websites to provide further protection for a user’s password
by verifying that user input is not computer generated. There are
now a wide number of different CAPTCHA systems using images,
numbers and even simple calculations but basically the idea is
to create something humans can read but that current computer
programs can’t. In this example distorted text is used.
Email verification
Figure 35.1 Human readable
Email confirmation and CAPTCHA are used to solve different
(distorted) security text
problems. Email verification is used to check that users are
using their real email address in the registration process. Email
verification is where an email is sent to the user’s email address and
they have to click on a link in it to confirm that the email address
is theirs. Email confirmation also protects from identity theft. For
example, the user cannot register a government email address and
pretend they are someone from the Cabinet Office as they will not
be able to click on the confirmation link sent by the email because
they are not the owner of this address. Email confirmation allows
the system to link each user to a specific email address.
Email verification proves that the email address is valid but
automating a response to an email is fairly easy, and thus cannot
be taken as assurance that the client is not a bot, so email
confirmation doesn’t protect from the bots (as CAPTCHA does).
e Question
Mobile phone verification
6 Briefly describe the term
With mobile phone verification you ask the user to enter their mobile
social engineering.
phone number, then you send them an SMS (text message) with a
code and they must enter this code into a web form on the website.
Removable media
For many years one of the most common ways to deliver a virus
has been through removable media. This has become even more
of an issue now with AutoRun. This is similar to AutoPlay, which
automatically starts playing video when you put a DVD or Blue-
ray disk into a media player. But unlike AutoPlay, which only plays
the media file, AutoRun starts automatically and can then start
installers of malware. The best option is not to use any removable
media unless it has been verified as being clean, but it is also
possible to disable AutoRun.
35 Social engineering and cyber-security
Penetration tests
A penetration test is an authorised attempt to evaluate the security
Penetration testing is the
of an IT infrastructure by safely attempting to hack into the system
process of attempting to gain
to find vulnerabilities. These tests also explore how effective
access to resources without
defence systems are. Penetration tests can be performed using
knowledge of usernames,
manual or automated technologies.
passwords and other normal
means of access. They are carried out on a wide range of systems including servers,
web applications, wireless networks, network devices, mobile
devices and other potential points of risk. Once vulnerabilities
2 Question
have been successfully exploited on a particular system, testers
7 Briefly describe the term unit may attempt to achieve the same unauthorised access.
testing.
There are two types of penetration test called black-box testing
and white-box testing.
Chapter review
i Ethical use
If you access, view or collect confidential material and/or personal
information, it is your responsibility to maintain confidentiality.
Do not share this information with unauthorised individuals. But
ethics and the law are not the same thing.
Computer users are free to follow or Computers users must follow the
ignore a code of ethics. regulations and law for the country they
live in.
Ethical rules are universal and can Whether or not a crime has been
be applied anywhere, all over the committed depends on the country or
world. state where it took place. There are many
examples of laws in one country allowing
things that are illegal in others. This is a
4 Computer ethics are moral big issue with the internet.
guidelines that govern the use
Ethics aim to create ethical Laws aim to prevent misuse of computers.
of computers and information computers users.
systems.
oe a. If you don’t follow ethical rules you Not obeying laws is referred to as a crime.
4 Computer addiction is a are deemed to be immoral.
growing health problem that
occurs when the Con Ethics relates to the rules and standards governing the conduct of
consumes someones entire an individual with others. As technology and computers became
social life. more and more a part of our everyday lives, the definition of
284
Ethical use
, It has even found its way into social media sites. But many people
are concerned about the lack of privacy, and how captured data
could be used by unscrupulous companies and individuals.
pyc see rss Anything created by inventors, authors and artists that
is their own ideas or work becomes known as their
intellectual property.
2 i j ; ;
intentionally erases programs Is any law relating to protecting the internet and other
3 illegally copies a program, or online communication technologies.
4 illegally registers and/or
activates a program. The law relates to copyright and intellectual property.
@ Intellectual property is about creations of the intellect (hence,
the name): inventions, artistic works, names, images and
designs. Intellectual property also relates to industrial property
such as inventions, trademarks etc. The word property means a
Product activation is a process
possession, something in which the owner has legal rights.
that attempts to prevent software
Unlike intellectual property, copyright law only protects the
piracy by requiring users to
form of expressions of ideas, not the ideas themselves. So the
provide a software product’s
copyright laws do not protect ideas or systems only how they
25-character identification
are expressed. This means that nothing in the copyright laws
number in order to receive an
prevents others from developing another work based on the
installation identification number.
same idea.
286
Ieee
Legal use
Software cracking
Software cracking is the modification of software to remove or
disable features which are considered undesirable by the person
cracking the software. Crackers often illegally remove or overwrite
copy protection features, nag screens and adware.
The term crack refers to the means of achieving software cracking.
This can include stolen serial numbers or a tool that performs the
act of cracking such as keygens used to generate an activation
key, patching which involves adding a patch so that the software
cannot conduct security checks and loaders to load the software
without these security checks.
A cracker (also known as a black hat hacker) is an individual who
breaches or bypasses security to gain access to software without
paying royalties. A cracker is anyone who reverse engineers
software or illegally modifies software.
2 Questions
Software and source code theft
Computer source code is the most important asset of a software
1 Briefly explain the term
company. The term source code refers to the programming
copyright.
instructions that are compiled into the executable files that are
2 Briefly describe the term sold by the software development company.
intellectual property.
Most people would agree that a company or individual should
be allowed to receive a return from the investment needed to
develop quality software. To allow for this, software developers
need a level of protection for the ownership over the software
they produce. In legal terms this is in the form of intellectual
property law which comes under the principles of copyright and
patent law.
The rights of the developer are formally agreed in legal terms ina
software licence. When you buy a piece of software you normally
have to agree to a software licence by clicking ‘I Agree’ or by
2 Use this book and other opening the package. This is a legal agreement between the
sources such as the internet owner and user of the software. It gives the user permission to
to research the legal impact use the software but does not transfer ownership rights to the
of using technology. intellectual property. Any act of reverse engineering or cracking
the software is illegal.
Plagiarism
Whilst plagiarism is not a recent problem, the internet has led to an
explosion in the copying of other people’s work. In schools, colleges
and universities tutors now have a real problem in identifying and
discriminating between original work and plagiarised work.
Plagiarism is also theft.
Material
processing
Use
Product
manufacturing
Distribution
Figure 36.1 The technology cycle
Energy use
You may think that your computer-based technology uses the
most energy when you use it and that by switching devices off
and using power-saving modes you can reduce this. Whilst this
is true, eighty-one percent of the energy a computer device uses
is used when it is made. It actually takes more energy to create
the device than it takes to run it for its entire working lifetime.
This makes computer devices different to all other household
appliances, most of which use the most energy during their
lifetime. So however good the user is at turning off their systems,
they will be involved in using large amounts of energy just owning
the device, especially if they are updating the hardware regularly.
End-of-life management
Consumer electronics are increasingly treated as disposable
items. We throw away televisions, computers and mobile phones.
Globally we throw away over 40 million metric tons of electronic
waste (e-waste) every year, and only about 13% of that weight
is recycled. Most e-waste recycling occurs in China, India,
Pakistan, Vietnam and the Philippines where they shred, burn,
and dismantle the products in ‘backyards’. Emissions from these
activities damage human health and the environment due to
exposure to toxic metals, such as lead.
Manufacturers are starting to take responsibility for changing
the way they manufacture electronics. This involves using fewer
natural resources during production. Users can make a difference
too by buying products that use recycled materials or that can
be updated rather than thrown away. Donating or recycling used
electronics helps too.
The disposal of computer devices is unlike most other consumer
goods because they are usually disposed of before they become
useless. The main reason for purchasing new computer devices is
not to replace a non-functioning system, but to keep up to date
with rapidly changing technologies. One way of reducing the
amount of computer waste would be to reuse systems that may be
out of date, but remain fully functional.
Waste disposal
Disposal of IT equipment comes under the WEEE directive (Waste
Electrical and Electronic Equipment).
The main objectives of the WEEE directive are:
® to increase reuse, recycling and other forms of recovery, leading
to a reduction in the amount of waste going to landfill or
Incineration
© to improve the environmental performance of all operators
involved in the life cycle of electrical and electronic equipment
The environmental impacts of technology ie
‘s
Ae
Chapter review
You should:
4.2.6 understand the need for embedded systems and their functions
292
Programming micro-controllers =
§ Programming micro-controllers
Often you can program a micro-controller using the BASIC
programming language.
Standard basic instructions include:
@ for...next (the normal iteration (looping) statement)
® go sub (go to a subroutine)
® goto (goto a label in the program)
@ if...then (the normal if/then decision statement)
@ end (end the program and sleep)
BASIC logic statements include:
@® =
@ <>
@<
@ <=
®>
® >=
@ AND
@ OR
—
Mechanical System
e system model e dynamic response
Input signal
conditioning
and interfacing
e discrete circuits
e amplifiers
e filters
e A/D, D/D
294
nnn Wearable technology
NORSIRUROINS
§|Wearable technology
Wearable technology, also called wearables, is clothing and
accessories incorporating computer and advanced electronic
embedded technologies. Wearables contain sensors, and also
often make use of web connection and Bluetooth networking to
connect wirelessly to other devices and the connected world. They
also use their inbuilt sensors to connect to your body and can be
used to help to achieve goals such as fitness, weight loss or better
organisation.
Most of the early generation wearables were wrist worn, but now
an increasing number are clipped to the body, hung around the
neck, built into things such as glasses or implanted into the body.
The main types of wearable include:
@ Smartwatches are wrist-worn devices that connect to things
like mobile phones and PDAs to tell the user about:
— call notifications, email and social media messages
— fitness tracking by keeping track of the activity the user
does such as the number of steps taken or distance travelled,
calorie count etc.
— GPS to track where the user is, sometimes with maps or
breadcrumb trails to help them find their way.
’ 37 Embedded systems
a
Chapter review
You will be set a task in the form of a single project which can be
undertaken in a period totalling 20 hours. When completing the
task, you will be expected to work independently and produce a
unique piece of work that you have designed, implemented, tested
and evaluated.
at Ne at aaa
Your project must use one programming language from the following:
@ Python
® Java
@ Pascal/ObjectPascal
® VisualBasic. NET
@ C-derived (C, C++, C#).
§ Analysis
You will be expected to clearly identify the requirements of the
problem including what the proposed solution will need to do
to meet these requirements. You should write an introduction to
the problem, in prose. Remember that this must demonstrate a
comprehensive understanding of abstraction and decomposition.
Decomposition requires you to make choices by breaking the
given problem down into sub-problems which you will later
design and implement.
You will need to:
@ decompose the problem into manageable sub-problems, with
an explanation of each.
Your analysis must include an explanation for any judgements
you make on the selection of the most appropriate sub-problems.
Remember that the examiner needs to see comprehensive links to
evidence so that your lines of reasoning are well supported, clear
and concise. eth
ati
I
fe
et
298
y} a
“.
>
bins e
«ata-
TOON Design
§ Design
You will be expected to design a solution to a problem including:
@ full decomposition into subprograms with clear abstraction
@ planning data structures
@ designing the algorithms
@ designing an appropriate modular structure for the solution
@ showing that all the requirements of the problem are fully
addressed
@ designing the user interface.
Your algorithms must be well designed and there should be no
errors in logic and in the use of programming constructs. The aim
is to produce an overall solution which is fully functional.
You will need to articulate your designs in a manner appropriate
to the task and with sufficient clarity for a third-party examiner
to understand. You must show how all the key aspects of your
solution are structured. You should also show that you have
clearly identified the requirements of the problem and made valid
judgements for decomposing the problem into sub-problems that
show good application of key concepts to the problem.
You can communicate your design using many of the tools covered
in this book including:
@ prose and diagrams
@ flowcharts
@ pseudo-code
@ descriptions of algorithms
@ data structures
@ text file/database structures.
You may also want to provide screen shots of actual screens.
4 You will need to show:
@ a comprehensive design which could be used as the basis of an
effective implementation of a complete solution
@ a good understanding of variables, data types and structures
@ all of the main blocks of the proposed solution including data
validation
@ that your design choices are justified with reference to user
requirements.
Your algorithm(s) should:
e show detailed decomposition into sub-problems and how they
link together (if appropriate)
e demonstrate clear abstraction (for example by including
parameterisation, links between components)
@ include inputs, processes and outputs
® use all the basic programming constructs in this textbook:
sequence, selection and iteration.
Remember to include:
@ the algorithm(s)
® comments on any refinements to the design identified during
implementation, with reasons.
300
bad
Implementation $
§ Implementation | |
At this stage you will implement your designs. But remember that
you will be testing and refining your code as you go, and this
must also be clearly shown. Your program must fully address the
requirements of the problem and should include:
@ a full solution with no logic errors, showing your effective use
of debugging skills
® subprograms, programming constructs, data validation, showing
that your choice of data types and structures lead to an overall
program which is fully functional
® evidence that your program has been fully decomposed into
subprograms and computing techniques are used to make the
program unequivocally clear and easy to understand.
You will be expected to implement your designs including:
® implementing the data structures and code so that a computer
can understand your solution.
Again drawing upon the contents of the book you will need to
use your coding skills to work at an appropriate level. You will
be expected to provide program listing(s) that demonstrate your
technical skill. You will also be expected to use appropriate
annotation. Your code should be well structured. It may be that
you need to amend your original design solution during this stage
and these refinements should be implemented and documented
as additions to the design and in the program code by using
comments as descriptors.
You should:
@ include explanations of particularly difficult-to-understand
sections of your code
@ provide a carefully divided presentation of the code
® provide appropriately labelled sections, to make navigation as
easy as possible for a third party reading the code listings
@ show how your program fully addresses all the requirements of
the problem set
@ show that your program runs with few or no logic errors
@ show how your program has been fully decomposed into
subprograms.
38 Project
] e es
302
eS. Evaluation/refining
Your test plan should show how each component will be tested to
meet the requirements of the problem.
Testing is asking the questions ‘Does the solution work?’ and
‘How well does it work?’ You will need to plan a series of tests to
show that the different sections and elements within your solution
work as intended, so that your solution is successful. It is best to
test your designs both after the system has been fully coded and
during the coding process. When carrying out tests it is important
that normal (typical), boundary (extreme) and erroneous data as
covered in this book should be used as appropriate.
You will need to present your results in a structured way, for
example in tabular form, showing clear evidence of testing. You
should also explain the reasons for the tests carried out alongside
the evidence for them.
This could take the form of:
® the test performed
® its purpose if not self-evident
® the test data
@ the expected test outcome
® the actual outcome with a sample of the evidence.
You will need to demonstrate that:
® a thorough representative range of tests has been planned and
carried out
® all the requirements of the problem have been achieved
® your test data includes normal (typical), boundary (extreme)
and erroneous data and shows that you have included:
— a comprehensive application of programming concepts and
principles, including debugging
— constructs, data validation and a choice of data types and
structures and how these have led to an overall solution
which is fully functional
® you have produced a test plan which is clear and unambiguous.
Evaluation/refining
You should evaluate your solution to the task through the design
process including:
® refining your solution as a result of testing
® assessing how well the solution meets the requirements of the
problem
® suggesting how your solution could be improved if the problem
were to be revisited.
Evaluation is considered to be answering the question ‘How well
does the solution work, and how could it be better?’
»PSO 38 Project
Te EEE eee
r You will need to consider and assess how well your solution meets
the requirements of the problem and how your solution could be
improved.
Remember to show:
@ how well the solution meets all the requirements of the problem
® if errors have been identified, how your program has been
corrected to overcome these errors
@ that all components and the requirements have been fully
tested using normal, boundary and erroneous data
@ that your testing includes how any subprograms interact
@ how you have considered the efficiency of execution and
robustness have been carried out
@ how you have made improvements to the solution
@ how any refinements have been identified, implemented and
tested.
Tests for any refinements completed in the design and/or
implementation stages should be added to the end of the test
plan and carried out. The evaluation must include a thorough and
critical evaluation of your program stating how successfully the
program meets each of the original requirements and the reason
for adding refinements to the final solution.
For the testing stage, your report will include:
@ the updated and complete test plan (labelled ‘Final Test Plan’)
@ the evaluation.
304
Key points index
».
Key points
Rey
Ck OTS index
——_—
Cloud computing Any software, hardware or storage running on servers connected to the
internet can be called cloud computing. In cloud computing you use the
software on machines ‘in the cloud’ instead of using your own personal
computer to carry out or store your work.
Cloud storage Cloud storage uses magnetic and increasingly solid-state storage at a remote
location.
Colour depth Colour depth (or bit depth) refers to the number of bits used for each pixel or
dot. The more bits the more colours that can be represented.
Companion virus A companion is a virus that creates a program with the same name as an
existing, legitimate program and tricks the OS into running it to deliver the
virus.
Compare To compare is to examine (two or more strings, etc.) in order to note 52
similarities and differences.
Compiler A compiler is a computer program that translates C, C++, BASIC, Pascal and 125-6, 130-1, 246
similar high-level programming languages into machine language.
To compile refers to converting (a program) into machine code or a lower-level
form in which the program can be executed.
Compression Data compression is a reduction in file size to reduce download times and ASML dey 1/
storage requirements.
Computational Computational thinking involves learning how to use a set of problem-solving 2-13
thinking skills and techniques that are used by computer programmers to write
programs.
Computer crime Computer crime is any illegal act involving a computer.
Condition- A condition-controlled loop causes a statement or set of statements to repeat 67
controlled loop as long as a condition is false. In Python you use the WHILE statement to
write a condition-controlled loop.
Content filtering Content filtering is a process of restricting access to certain material 270
on the web.
Control unit (CU) The control unit (CU) is inside the CPU and is used to control the flow of data 220-1237
within the system.
Copyright Copyright is exclusive rights given to authors and artists to duplicate, publish 270, 286
and sell their materials.
Copyright and patent laws benefit society because they encourage creators of
new products to make them available to the public.
Count-controlled A count-controlled loop iterates a specific number of times. In Python you use SLLTi
loop the FOR statement to write a count-controlled loop.
Counter A counter is a timer or variable that can be used to count. 65
CPU The central processing unit (CPU) is the electronic circuitry within a computer AWAXG}, ae ¥3), Bala’, Dalie-
that carries out the instructions of a computer program. It is a type of 218-21, 236
processor that runs a computer system. The name processor is a more
generic term but is often used to mean the same thing. The only problem
with using the term processor when referring to the CPU is that there will be
other processors in a system but only one CPU.
Cyber-security Cyber-security is a term used to describe the protection of information 276-82
systems from theft or damage to the hardware, the software and to the
information on them. It consists of the processes, practices and technologies
designed to protect networks, computers, programs and data from attack,
damage or unauthorised access.
Data Data is information, such as text, symbols and numerical values. Data are the 125
facts or details from which information is derived. Data itself has no meaning,
but becomes information when it is interpreted.
Data integrity Data integrity is the state of data being exactly as it should be. 259
Data standards Data standards are the rules by which data are described and recorded. 149
Debugger A debugger is a piece of software that helps a programmer track down faults 104-5
in a program.
Key points index
Debugging The process of testing a program for errors during its execution is a cyclic 104-5
activity cailed debugging.
Decomposition Decomposition means breaking a problem into a number of sub-problems, so 2, S610-12
that each sub-problem accomplishes an identifiable task, which might itself
be further subdivided.
Definite loop In definite loops, the number of iterations is known before we start the 65
execution of the body of the loop.
Discovery mode Discovery mode is a Bluetooth scheme that allows devices to automatically mp oh
detect and connect with other devices.
Domain name A domain name is a human readable name for a resource location on a 270
network. It is changed to a numerical IP address by a DNS server.
Element An element in computer science is an essential or characteristic part of 38, 120, 166
something; other terms often used outside computer science are part,
section, portion, piece and segment. An element can be an item of an array.
Each element can be accessed by referencing its location in the array.
Embedded Embedded systems frequently have more limited resources than PCs. 292-6
systems Embedded systems usually focus on dedicated tasks, but PCs are general-
purpose computers. Embedded systems usually require minimal human
intervention.
Encrypted A programmer at any computer or other device connected to a network could 198, 275
easily modify the software at that host. This is why sensitive data should be
encrypted.
Equality The assignment operator (=) and the equality operator (==) appear to be 50, 206
similar, but are used for completely different reasons. The assignment
operator (=) is used to assign a value to a variable, element or array; the
equality operator (==) is used to compare two values or expressions. The
result is TRUE if the expressions are equal or FALSE if they are not.
Equivalency Equivalency is to look for equality (are they the same?) in value, etc. 62
Erroneous data Erroneous data is data that would not normally be expected such as the 106
wrong data type.
Error There are different types of errors, or bugs, that prevent computer programs 49, 96-101
from working correctly. Three of the key error types are runtime, syntax and
semantic.
Ethics Computer ethics are moral guidelines that govern the use of computers and
information systems.
Execute In computer science to execute is the process of carrying out an instruction
by a computer.
Extreme data Extreme data is data that is at the extreme limit of valid or invalid to check
boundary conditions.
File infector virus A file infector virus is malware that copies itself into other program files (exe, 274
dil, bin, sys, com, drv); when the infected file is executed it loads into memory
and tries to infect other files. It is also known as a parasitic virus.
Firmware Firmware is programming that’s written to the read-only memory (ROM) of a 224
computing device. It is added at the time of manufacturing and is used to run
user programs on the device.
Flowchart A flowchart is a diagram of the sequence of movements or actions of the 14-21, 71
program involved in a complex system or activity.
Function A function is a group of statements that exist within a program for the 84, 91,122
purpose of performing a specific task. In computer programming a function
is a subprogram; given a particular set of argument values, the function
returns a unique result. A function returns a value. Functions return a value
and procedures do not. Functions should be explainable in one sentence that
doesn’t contain AND or OR. You can use functions in your programs again and
again. A function has three parts: a name, parameters and a body.
Key points index
Generalisation Generalisation means adapting a solution that solved one problerh to solve oe
another. It also means replacing many things with one. First decide what
similar problems have in common, then write code that by using variables and
functions can be called when you need these similar features.
Hexadecimal The word hexadecimal means ‘based on 16’ (from Greek hexa: ‘six’ and Latin 142-4
decima: ‘a tenth part’).
High-level language A high-level language is a computer programming language designed to allow 126
people to write programs without having to understand the inner workings of
the computer.
HTTPS HTTPS provides an encrypted version of HTTP for more secure web XCD, ASS), 2UE
transactions.
Hyperlink A hyperlink is an item on a web page that directs the user to another location aifAl
when clicked.
Image size If you want to calculate the size of an image you need to use colour depth ARSE: soyaS
and the number of pixels in your calculations.
Size in bits = WxHxD
Size in bytes = (W x H x D)/8
where W = image width, H = image height and D = colour depth in bits.
immutable An immutable object is an object whose state cannot be modified after it is XG), ALTAAL
created.
Import To import is to bring in from an outside source. 89
Indefinite iteration Indefinite iteration is the name given to the repetition of a sequence where 65
the number of repetitions is unknown.
Indefinite loop In indefinite loops, the number of iterations is not known before we start 65
to execute the body of the loop, it all depends on when a certain condition
becomes true. For example WHILE.
Information Information is a collection of facts or data that is communicated. ALS
Information privacy Information privacy is the right of individuals and companies to deny or 288
restrict the collection and use of information about them.
Input validation Input validation is the process of inspecting data that has been input to a ALTE)
program, to make sure it is valid before it is used in a computation.
Input validation is commonly done with a loop that iterates as long as an
input variable references bad data.
Integer An integer is a whole number value, positive or negative, with no decimal or 34, 159, 165
fractional part.
Interactive device Every interactive device has to have an input, process and output. 214, 215
Interpreter An interpreter is a program that executes a source program by reading it one 126, 130-1, 246
line at a time and doing the specified operations immediately.
IP address The IP address is a number that identifies a device on a TCP/IP network. 261, 286
Iteration Iteration (looping) is repeating parts of a sequence over and over again, like 65
eating breakfast every day at 7.30 a.m.
Iteration is the name given to the repetition of a sequence of computer
instructions a specified number of times or until a condition is met.
Library A library is a collection of files, computer programs, or subroutines. 89
Local variable A local variable is created inside a subroutine and cannot be accessed by 85
statements that are outside the function — it has local scope.
Logic bomb A logic bomb is malware designed to execute and do damage after a certain 270
condition is met.
Logic error A logic error is something that stops the program doing what it is meant to 96, 99-101
do, or causes a runtime error (such as ‘division by zero’).
Logic errors are when a program works but does not give the answer you
require. For example using ‘<’ instead of ‘>’, adding when you should be
subtracting, etc.
1 ee
4 Key points index
7
4
Logical reasoning Logic programming is a method of writing computer programs based on the 2,3
mathematical study of logical reasoning.
Loop A loop is part of a program that repeats itself (to prevent the need for the 42-5
same piece of code to be typed out multiple times). It is a way of repeating a
statement a number of times until the condition is met. The condition allows
the user to escape from the loop.
Lossless Lossless and lossy compression are terms that describe if, in the 183
compression of a file, all original data can be recovered when the file is
uncompressed. With lossless compression, every bit of data that was
originally in the file remains, nothing is lost, when the file is uncompressed.
MAC address MAC address filtering allows devices to access, or be blocked from PPD, PXSSO—AL
filtering accessing, a network based on their physical address embedded within the
device's network adapter.
Machine code Machine code is a set of instructions that a computer can execute directly. 125-6, 127, 130-1, 133,
Machine code is written in a binary code, and each statement corresponds to 134-5, 237
one machine action. A computer's CPU can only understand instructions that
are written in machine code. Machine code and assembly code are low level.
Everything else is high level.
Magnetic storage In magnetic storage, magnetic material is given a polarity. That polarity is 221-8
then read and depending on the direction is output as a binary 1 ora O.
Main memory Main memory (also called primary storage) is any form of memory that is 217, 219, 223-4, 236-7
directly accessible by the CPU, except for caches and registers. It is directly
connected to the motherboard and is the place where programs and data are
kept while being used.
Malware Malware is malicious software designed by attackers to compromise security 210; 2022
and do damage. It is an umbrella term used to refer to a variety of forms of
hostile or intrusive software.
Memory Just like humans, computers rely a lot on memory. They need to process and 223-6
store data, just like we do. However, computers store data in digital format in
a reserved location and of a set location size.
Memory location The computer memory is made up of partitions (much like a set of drawers). 54, 60, 166, 226
The memory location is the address which uniquely identifies every location in
the memory.
Menu A menu is an element displayed on the screen that gives the user a choice of 120, 244
options.
Motherboard The motherboard is the central printed circuit board (PCB) that holds all the 217-18
crucial components of the system.
Nested loop Nested loops consist of an outer loop and one or more inner loops. Each 119-22
time the outer loop is repeated, the inner loops are re-entered and started
again as if new.
Network layer The network layer is sometimes referred to as the internet layer. 264
Non-volatile Non-volatile memory is typically used for the task of secondary storage, or 226; 229,230,
232
memory long-term persistent storage. Examples are ROM and hard drives.
NOT A logic gate that outputs the opposite value to the input. Ooo
Object In computer science, an object could be variable, a data structure or a Shit
function. Each object has a location in memory and a value. Objects are often
referenced by an identifier.
One-dimensional A one-dimensional array is a single variable that can store a list of values. To 166, 167-8
array create an array, you first must define an array variable of the desired type.
Open network An open network is one whose specifications and protocols are public, 272
allowing different companies to produce compatible products.
Operand The operand is the part of the instruction that tells the CPU what to apply the 236
operation to.
310
SSS
Key points index
SSS isc st isc Soe sss
Operating system An operating system is the software that controls all the hardware. It acts 239, 240, 241-2
as an interface between the user and the hardware and also between
applications and the hardware. The operating system is a program that allows
application software to communicate with the hardware.
Operator An operator is a symbol or instruction that performs a specific function: for 236
example, ‘NOT’ or ‘AND’. The operator is the part of the instruction that tells
the CPU what to do.
Optical storage In optical storage, pits and grooves in a flat surface provide a reflection for 227, 228-9
a laser; a light sensor then assigns a binary 1 or a O depending on the light
intensity.
CD, DVD and Blu-ray disks use optical storage.
CD, DVD and Blu-ray disks are all the same physical size and use the same
spiral track layout for placing data on the platter.
OR A logic gate that outputs 1 if either, or both, of the two inputs are 1. US), TAS; olll
Overflow When a number becomes too large to fit into the number of bits allocated it is 140-1
said to ‘overflow’ and some bits are ‘lost’ leaving an incorrect value.
Parameter A parameter is a variable that receives an argument that is passed into a SORLoO
function. A parameter is information explicitly passed to a subroutine as part
of the subroutine call. Parameters in functions are often called arguments.
Penetration testing Penetration testing is the process of attempting to gain access to resources 282
without knowledge of usernames, passwords and other normal means of
access.
Pharming Pharming is a cyberattack intended to redirect a website’s traffic to another, 216-211
fake site.
Phishing Phishing is a technique for obtaining sensitive information by asking users LUO 2
for their passwords, credit card numbers, etc. This is achieved by sending
an email while masquerading as a legitimate entity such as the user’s bank.
Computers are not secured against phishing; each user must rely on good
judgement when revealing sensitive data to others without proper verification
of who they are.
PIN A personal identification number (PIN) is a numeric password, either assigned 2
by a company or selected by a user.
Pixel Pixels are the dots that make the graphical image on screen. They are the 150
smallest element of an image.
Placeholder Variables are a storage placeholder for texts and numbers. A placeholder is 60
a term referring to something not yet finalised. It is a section of computer
storage reserved for information that will be provided later.
Polymorphic virus A polymorphic virus is malware that changes its form each time it is 274
executed, avoiding detection/removal by anti-virus software.
Power-on password A power-on password is a password entered on computer startup, before the 278
OS loads.
Procedure Procedures are collections of statements that define what happens to the 12, 88, 89-90
parameters. It is a Subroutine that does not return values.
Process A process is a series of actions or steps taken in order to achieve a
particular end.
Product activation Product activation is a process that attempts to prevent software piracy by
requiring users to provide a software product’s 25-character identification
number in order to receive an installation identification number.
Program A program is a sequence of instructions to perform a task.
Program counter The program counter is simply a register in the CPU that keeps the address
of the next instruction.
Protocol A protocol is a set of rules or standards that control communication between 250, 261-4
devices.
Quarantine Quarantine is a separate area of a hard disk that holds an infected file until a 270
virus can be removed.
Key oe
ey points eee
index ———E——————
312
Key points index
Solid state Solid-state disks do not require physical motion so they have shorter 227, 229-30
response times. They also do not suffer from physical wear.
Solid-state storage uses electrical signals to change the state of a transistor.
This transistor can either be changed to binary 1 or to O.
Source code Source code is the original program code of software; it is the part most 287-8
computer users don’t ever see.
Spam Spam is unwanted, unsolicited email. 270
Spyware Spyware is a non-replicating program used to track user activities, monitor BS
their machines and relay personal information to attackers.
Stealth virus A stealth virus is a virus that attempts to avoid detection by masking itself 274
from applications, redirecting commands around itself.
String A string is a data type used to store a sequence of letters, symbols and/or 5-9
numeric characters.
Subroutine A subroutine is a sequence of instructions that is set up to perform a 82, 88-94
frequently performed task. It is a computer program contained within another
program. It operates semi-independently of the main program. A subroutine
is a named ‘out of line’ block of code that may be executed (called) by simply
writing its name in a program statement.
Switch In computers, transistors act as switches. The current flowing through can be 76, 133-4
turned on or off. A switch is also the name given to a device for connecting
multiple network devices.
Syntax error A syntax error is a mistake in the program’s words or symbols, such as 96-8
misspelled keywords, missing brackets or incorrect indents. These types of
errors are the easiest to find.
A syntax error is something that stops the interpreter from understanding the
code (it cannot run).
TCP/IP TCP/IP (Transmission Control Protocol / Internet Protocol) is a transmission 262
control protocol / internet protocol consisting of a set of standards that
control how data is sent across networks including the internet.
Time-out A time-out is where the server is set to think that there has been too long an 278
interval of time between (1) the establishment of a connection, and (2) the
receipt of any data, so the server drops the connection.
Top-down design Programmers commonly use a technique known as top-down design to break 30
down an algorithm into functions and modules.
Trace table A trace table is a method of using data to check that a flowchart or code 102-3
covers all possibilities correctly.
Translator A translator is a program to convert high-level or assembly-level commands 130, 246
into machine code.
Trojan horse A trojan horse is non-replicating, malicious code contained inside what 275
appears to be a useful program.
Truth table A truth table is a diagram used to show the value of a Boolean expression for Om S— 9
all possible variable combinations.
Truth value The truth value of a statement is always either true or false. 34,75
Unauthorised Unauthorised access is the use of a computer or network without permission, PAYS)
access unauthorised use is the use of a computer or its data for unapproved or
possibly illegal activities.
Unicode Unicode is a universal code used by computers to represent thousands of 145, 147
symbols and text characters. It is a system of up to 32 bits to code the
character set of a computer (usually 16-bit or 32-bit versions).
User interface A user interface is the access point and the boundary between the computer 214-15
and the user.
Valid data Valid data is data used in testing that represents normal data that could be 106
expected.
Key points index
ee
Validation Validation is the process of checking data as it is input to ensure that it is 106, 174-8
sensible; it does not check that it is correct.
Variable A variable is a name/location in memory/identifier, used to store a value 60-1, 166
which can change during execution of the code. The word variable in
programming describes a place to store information that can change, such as
numbers, text, lists of numbers and text. Another way of looking at a variable
is that it’s like a box with a label on to store something.
Virus A virus is a computer program that is spread when its payload is executed, 270, 274-5
interfering with the hardware, software or OS. It is malware that needs a host
application to transport itself.
Virus hoax A virus hoax is an email message that warns users of a non-existent virus or 277
other malware.
Visibility Visibility is another name for the scope of a variable in a program; it is the 85
lines of code in the program where the variable can be accessed.
Volatile memory Volatile memory is a type of storage whose contents are erased when the 266
system’s power is turned off or interrupted.
While While statements are efficient loops that will continue to loop until the 68, 74
condition is false.
A WHILE loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The WHILE loop canbe
thought of as a repeating IF statement. It will be executed continuously until
the condition is met.
White-box testing The aim of a white-box penetration test is to simulate a malicious insider who 282
has knowledge of and possibly basic credentials for the target system.
Whitespace Whitespace is any section that is unused, for example the space around an 61
item in the code. Whitespace is a useful tool in any coded solution as it helps
to separate the blocks of code.
Wi-Fi Wi-Fi is a family of related protocols rather than a single protocol. Wi-Fi is a PASYTl
trademark; the generic term for networks of this nature is WLAN.
Worm A worm is self-replicating malware that does not alter files, but resides in PATA, PAUPX, PTET
active memory and propagates itself by means of computer networks to
consume resources.
314 oe
INI
O
D
=
>
a
sweipyieg
O
Z
o
m
zs)
Ss 8AdVaal]
HIOSYON
O
m
on
20LS1220
CUSHING STEVE.
| Edexcel computer science for G
427035/00003 - 2 of 2
This student book has been endorsed for use with the Edexcel GCSE (9-1) specification for Computer Science.
Build student confidence and ensure successful progress through GCSE Computer Science. Our expert
author provides insight and guidance for students to meet the challenges of the new Edexcel
specification, with tasks and activities to test the computational skills and knowledge required for
success in the assessment, and advice for successful completion of the non-examined assessment.
Builds students’ knowledge and confidence through detailed topic coverage and explanation of
key terms.
Develops computational thinking skills with practice exercises and problem-solving tasks.
Instils a deeper understanding and awareness of computer science, and its applications and
implications in the wider world.
Helps monitor progression through GCSE with regular assessment questions, that can be further
developed with supporting Dynamic Learning digital resources.
Author:
Steve Cushing is a well-respected and widely published author for secondary Computing, with examining
experience.
ISBN 978-1-4718-6622-7
| |
81471 866227
www.hoddereducation.co.uk .