Вы находитесь на странице: 1из 214

Copyright

Copyright 2013. Computing Academy


All rights reserved. No part of this 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 author or under license from the Copyright holder. Reproduction, distribution and
licensing requests should be made via email to info@computingacademy.org.uk

Terms
This publication may only be used in accordance with the terms set out at:
http://www.computingacademy.org.uk/terms. By continuing to access this publication you
agree to be bound by these terms.
Computing Academy makes every reasonable eort to ensure the quality and accuracy of
this publication, however errors and omissions do occur. Computing Academy does not
guarantee that this publication is accurate, suitable or relevant for a particular syllabus or
examination board. You are responsible for ensuring that this resources meets your needs
and the requirements of the syllabus you are following; we will accept no responsibility or
liability for any mistakes, errors or omissions in this publication but we will endeavour to
correct any errors brought to our attention within a reasonable amount of time.

ii

Acknowledgements
All images, photographs, diagrams and text are the original works of the author, with the
exception of those acknowledgments made below.
Every eort has been made to trace all copyright holders, but if any have been
inadvertently overlooked please do contact us.
Photo Credits
p6 http://en.wikipedia.org/wiki/File:Charles_Babbage_-_1860.jpg; p10 The University of
M a n c h e s t e r - u s e d w i t h p e r m i s s i o n ; p 2 7 P a u l Wo o t t o n G r a p h i c s
(www.graphicnet.co.uk); p43 Gnome 3.8 CC BY-SA 3.0; p46 Google Inc; p51 Google
Inc; p123-138 Apache OpenOce Screenshots used with permission from Apache.
Apache, Apache Foo, Foo, and the Foo logo are trademarks of The Apache Software
Foundation. No endorsement by The Apache Software Foundation is implied by the use of
these marks; p140-145 Josh Tynjala, Logicly - used with permission; p150 London Eye:
http://www.sxc.hu/photo/616616;

iii

Foreword
Computer Science isnt a new subject.
The science of sequencing instructions
and developing algorithms has been
around since the 17th Century with
Gottfried Wilhelm Leibnizs Stepped
Reckoner; a mechanical counting machine

science, get you thinking about how to use


computers to solve problems and get you
excited about creating and running your
own computer programs and games rather
than just using existing programs and
playing games.

built in 1672, Johann Helfrich von Mllers

Students and teachers can use this book

Dierence Engine built in 1786 and the first

as a companion for any Computer Science

programmable computer built by Charles

course: although we do not endorse any

Baggage in 1812.

particular examination board, we have paid

Much has changed since then. Computers


no longer fill entire buildings; indeed it is
often the case today that we dont even

close attention to the examination board


specifications and believe that this text will
prove to be an invaluable resource.

notice computers at work.


Computers have become so embedded in
our everyday lives and so easy to use that
weve stopped thinking about how they
actually work; what goes on inside that
box?
This book aims to guide you through the
fundamental principals of computer

iv

Charles Babbage
The father of the computer. An English mathematician, philosopher, inventor and
mechanical engineer who invented the concept of a programmable computer.

Contents

1. Computer Systems

2. Hardware

3. Software

4. Data Representation

............................................................................

What Are Computer Systems

Input, Process, Output

11

Using Computer Systems

13

Standards

18

Further Considerations

21

............................................................................

24

Permanent Storage

26

Random Access Memory

31

ROM and Virtual Memory

33

Central Processing Unit

35

............................................................................

41

What Is Software?

42

Operating Systems

43

Drivers

49

Applications

50

Utilities

53

............................................................................

54

Binary

55

Hexadecimal

71

ASCII

81

Images

85

Sound

90
vi

5. Networking

6. Databases

7. Algorithms

8. Programming

............................................................................

95

What Are Networks?

96

Network Classification

101

Network Infrastructure

103

Network Types

107

Network Topologies

111

Network Protocols

114

The Internet

117

............................................................................

128

Thinking About Data

129

Database Management Systems

133

Relational Databases

138

Queries

145

............................................................................

148

Logic

149

Sequencing

156

............................................................................

163

Programming Languages

164

The Basics

174

Variables

176

Data Types

182

Operators

186

IF Statements

199

Loops

206

Arrays

208

Documenting Code

211

vii

1
Computer Systems

Computer systems take a set


of inputs, process them and
create a set of outputs

What Are Computer Systems?

Computers today are all around us in one form or another. Take a quick look around a
typical home and youre sure to find many dierent types of computers.
There are obvious examples such as desktop computers, laptop computers, tablet
computers and mobile phones. There are also computer systems which we take for
granted and probably dont even think of as being computers such as alarm clocks,
watches, washing machines and microwaves.
The first electronic programmable computer, built in 1943 was called Colossus, but as
Colossus could not store programs the operators had to enter the program from scratch
each time they turned the machine on.

The first computer able to store a program was built at Manchester University in 1948; it
was called the Small Scale Experimental Machine, or Manchester Baby.
The first program Baby
ran took 52 minutes to
complete; a moder n
computer would take
less than a second to
complete the same
calculation.
Computers can be
dedicated which means
that they have been
designed for a specific
purpose such as a satellite or terrestrial television recorder, or a burglar alarm. These
dedicated computer systems are designed to perform a specific function and nothing else.
Computers may also be general purpose which means they do not have one main
function, for example desktop computers and laptop computers.
Although computers come in all shapes and sizes they share a common principle:

Key Point
Computers consist of a set of parts which work together to achieve a
common purpose. All computer systems take a set of inputs, process them
and create a set of outputs. This is done through a combination of
hardware and software.

10

Input, Process, Output

The following diagram shows a computer system in its most basic form.

Computer systems have one or more inputs which sense, detect and collect data. This
data is then processed, which can include sorting, searching and calculating. The result

11

of this processing is then output or stored for outputting later. Outputs may include
displaying data to a screen, printing a hard copy (paper copy), or playing a sound.
In order to be clear about whether a device is an input or an output device consider:

Is data flowing INTO the computer from the outside world...?

...or is data flowing OUT from the computer to the outside world?

Here a few examples of computer hardware that you will be familiar with, separated into
input and output devices.
Input

Output

Keyboard

Monitor / Screen

Mouse

Printer

Cashless Reader / NFC

Projector

Keypad

Speakers

Task
Write down 3 more input and 3 more output devices that might be used as
part of a computer system.

12

Using Computer Systems

Why are Computer Systems Important?


Think about how many computer systems you might interact with during a typical day:
checking text messages or email in the morning; microwaving a bowl of porridge; setting a
burglar alarm; using a swipe card to enter a building; being observed by a CCTV security
system...........and thats all before you even arrive at work or school.
All day, every day, computer systems are at work; here are just a few examples.

13

Description

Input

Process

Cash Machine

User inputs their pin


number

System checks that the


pin number is valid

Online Cinema Booking

Contactless Payment

Voice-activated
Smartphone

User selects film

System checks
availability

Output
Options (such as check
balance and withdraw
cash) output to user via
the screen
Available seats output to
user in a diagrammatic
representation of the
cinema

System looks up the


users account and
User touches contactless
checks to see whether
card or chip to the card
they have sucient funds
reader
- if so, the account is
charged

A message is displayed
to the user stating that
either the transaction
was successful or that
the transaction was
declined

The system determines


what has been said using
speech recognition
algorithms

Depending on the
command input, the
phone may dial a
number, perform a
Google search, speak a
response etc.

User speaks into the


microphone (recognised
instructions)

Here are some further examples of where computer systems can be found.

Retail
Ecommerce / online shopping websites, automatic stock ordering systems, logistics /
delivery tracking

Communication
Email, social networks, video calling, telephone calls, text messages

Education
Virtual Learning Environments (VLEs), interactive learning activities, quizzes and
educational games

Science
Simulations and data processing / number-crunching

Travel
Flight booking and tracking, mobile app bus timetables, GPS navigation, train signalling,
aircraft guidance
14

Reliability
We rely on computer systems an awful lot. Air trac control systems and hospital life
support systems are just two examples of where we quite literally put our lives in the
hands of computer systems. We therefore need to know that they are going to be reliable.
System designers, and the companies and individuals buying computer systems talk
about reliability using two main measures.
Availability
Ideally, a computer system will be available all the time, 24 hours each day, 365 days per
year. In reality that might not be the case due to system failure and the need to temporarily
take a system oine for maintenance. Availability is one measure used to judge the
reliability of a system. Over a period of 30 days, if the system was available without issue
for 30 days the system availability would be 100% for this period. If the system had a fault
and as such was out of action for 1 out of the 30 days, the system availability would be
97% for this period ([29 / 30] * 100).
MTBF
Another measure of reliability is the Mean Time Between Failure (MTBF) which is a figure
provided by hardware manufacturers who test their products and generate a MTBF value
before they are sold. The MTBF will be the average length of time, usually in hours, that a
particular hardware component is predicted to operate for without failure.

Testing
Software engineers will write millions of lines of programming code, and whilst they are
often highly skilled, even the most experienced programmers sometimes make mistakes.
A program to control the operation of a washing machine may seem simple when
compared with the program used to manage and track aircraft, but even the software
controlling that washing machine will consist of thousands of lines of code.
Software engineers need to test their code in order to catch any errors they may have
made. Testing is a time consuming and therefore expensive process that requires testers
15

to think about every possible way a system could be used; in the case of the washing
machine this could mean testing every possible combination of buttons that a user could
press, testing what happens if the door isnt shut when the start button is pressed, testing
how the system recovers if the power is cut during a wash cycle etc.
Extensive testing should take place before software is released, whether that software is
an air trac control program or just a new app for a smartphone.
Once the software engineers are happy with the software they may first release this to a
limited group of beta testers who may find errors also known as bugs that were missed
by the developers.
After a piece of software is released and put to use it will need maintenance and
software updates. This is necessary to fix further bugs found after release or to ensure
the software continues to function correctly if the systems around it change. When
smartphone operating systems receive updates, app developers sometimes need to
perform updates of their own app in order to ensure that it will continue to run correctly on
the updated smartphone operating system.

Failure
System failure could have catastrophic consequences so its important for organisations to
be prepared, and protect against or prepare for system failure. In the context of computing
Redundancy means spare, excess or additional; if a computer system has redundant
storage it means that rather than just one hard drive, it has two or three.
High profile ecommerce and social networking websites would lose millions of pounds if
their systems failed, so they use redundancy. If one hard drive fails, a redundant hard drive
will take over. If an entire server fails, a redundant backup server will automatically take
over.
In addition to using redundant hardware, organisations who rely on hardware and data for
their very survival will have prepared a disaster recovery plan. A disaster recover plan is
just what it sounds like - a plan of what to do in case of a disaster such as fire, theft, flood,
power loss, terrorist attack etc. Disaster recovery plans set out which individuals need to
16

do what and when in the event of a disaster. Some individuals may need to make a
telephone call to a dierent city or country asking them to bring a redundant server online;
others might need to unplug backup drives and get these to a safe location.

Task
Think about a computer system that would be used in each of the
following categories:

Retail, Communication, Education, Science, Travel


For each computer system, write down the inputs, processes and outputs
taking place.

17

Standards

Standards
In order to reduce system failure and make systems more reliable, developers adhere to
standards.
Heres an example of two systems trying to work together that dont use the same set of
standards.

18

Example
Imagine that System A has been designed so that code #105 means yes,
everything is fine. System A sends out this code to System B to let it know.
The problem is, System B is using a dierent set of standards. In System B
code #105 means please send me some data. System B now starts
sending lots of data to System A.
System A wasnt expecting this data so sends code #993 to System B.
The set of standards used by System A say that code #993 means stop, but
the set of standards used by System B say that code #993 means can you
send the data faster please.

Systems need to operate using an agreed, common set of standards otherwise they just
wont work very well (or at all) together.
Proprietary Standards
Proprietary standards are owned and controlled by companies. The .doc and .docx file
formats are owned by Microsoft and these file formats use a particular standard way of
saving and presenting word processed documents. Every computer which has Microsoft
Word installed will be able to follow this standard in order to open a .doc or .docx file
properly.
Similarly, Pages, the word processor created by Apple uses a dierent standard. Microsoft
Word does not use the same standard as Apple Pages, so you cannot open Apple Pages
documents using Microsoft Word.

19

Industry Standards
The computing industry do have some common agreed standards that they all follow.
Universal Serial Bus (USB) is a standard way of connecting devices such as digital
cameras and printers to computer systems. The USB standard states the size and shape
of USB connectors and sockets and how data should be transmitted.
De Facto Standards
Have you noticed that every keyboard you use has the same standard configuration of
keys, with QWERTY making up the first 6 letters of the first row of letters. Nobody owns
this standard it has just evolved as the common, conventional way of setting out a
keyboard. Although De facto standards are not owned or controlled by one person, they
have been accepted as the best way of doing something. Should you wish to, you could
design a new keyboard with the letters in completely dierent positions.
De Jure Standard
If you wish to create a webpage youre going to need to write some Hypertext Markup
Language (HTML). There is no option here as HTML is a de jure standard - its the only
acceptable way and you must use it if you wish to create a webpage.
Open Standards
Open standards are publicly available. Anyone who wishes to can look at, use and even
change the standard. HTML is an open standard which means that you can make changes
to it and suggest your changes to other users of HTML. If others see the benefit of your
changes, they could be incorporated into the standard. Other examples of open standards
include TCP/IP (the method through which computer networks send and receive data),
Android (the smartphone operating system) and Python (the programming language).

20

Further Considerations

Environmental Considerations
Each year the computer systems we use consume millions of Gigawatt Hours (GWh) of
energy, and millions more GWh of energy are used on air conditioning in order to ensure
that those systems stay cool.
The average lifespan of a computer system - whether that be a smartphone, laptop, tablet
or desktop - is 3 years. These computer systems contain lots of toxic materials such as
mercury and radioactive isotopes, all of which ends up in landfill.
Power consumption and waste due to computer systems is a big problem for which we do
not yet have a solution

21

Ethical Considerations
While legalities refer to what you can or cant do under law, ethics is concerned with
fairness; what it right and wrong. Doing something that is ethically wrong does not
necessarily mean that it is against the law.
Should you wish to, you could setup a business oering to design websites for customers
even though you dont really know how to create websites. Ethically, you should not do
this as its wrong and you wont be able to produce good quality websites for your
customers; yet while ethically wrong, this would not be illegal.
Legal Considerations
As our use of computer systems increases, so does the range of laws and legislation to
control and govern our use of these systems. The Data Protection Act (1998) is a law in
place to protect peoples privacy and state what can and cannot be done with data
collected about individuals. The Computer Misuse Act (1990) concerns unauthorised
access to and improper use of computer systems.

Task 1
Think about 3 more activities or actions involving the use of computer
systems that could be considered ethically wrong.

22

Task 2
Find out more about the Data Protection Act and the Computer Misuse
Act.
What can and cant organisations do with data they collect under the Data
Protection Act?
What exactly is and isnt allowed under the Computer Misuse Act?

23

2
Hardware

Hardware describes the


physical components of a
computer system

Hardware

Hardware vs Software
Computer systems consist of both hardware and software working together.

Software
describes the sequences of instruction, code and programs that computers execute.
While software may be stored on a CD, DVD or USB drive these devices themselves are
not software. Software cannot be physically touched.

Hardware
describes the physical components of a computer system anything that can be seen
or touched which can include input, output, storage and processing devices.

25

Permanent Storage

Computers need to be able to remember lots of dierent things.


Each time you login to your computer, you expect your documents, music and photos to
be ready and waiting for you - the computer needs to remember them all.
Each time you advance to the next level in a computer game, you expect to earn points or
additional lives - the computer needs to be able to remember this data both during the
game, and next time you play the game.
When using computers today, we seem to be performing lots of dierent tasks at the
same time: we check our emails while having a video call with family, while browsing on
the Internet for a new pair of shoes, while streaming a new album.

26

Computers use several dierent types of memory to ensure that they dont forget all of this
data.

Permanent Storage / Secondary Storage


Hard Disk Drives (HDDs) and Solid State Drives (SSDs) are used in modern computers as
permanent, secondary or persistent storage. When you save a piece of work or copy
photos from your digital camera to
your computer they will be stored on
a HDD or SSD.

HDD
A HDD is a stacked set of magnetic
platters or plates. These platters spin
up to 10,000 revolutions per minute
(rpm), and mechanical arms seek
backward and forwards across the
spinning platter in order to read or
write data to a particular sector of
the disk.
D a t a i s s t o re d t o a H D D b y
manipulating and adjusting the
magnetic charge into one of two
directions. Each direction represents
0 (o) or 1 (on).

HDDs are a type of secondary or permanent storage. They are persistent which means
that the data will remain intact even when the power is turned o.
In 1956 when IBM invented the first HDD it cost around $65,000 and stored about 5MB.
Today, 100 will buy you a 5TB HDD (which is 5,242,880MB).

27

As well as making it very aordable to store large amount of data, HDDs are fairly reliable.
Often, when HDDs fail it is either because the disk has been corrupted due to interference from
other magnetic sources (such as speakers), or because the mechanical parts have failed.

Advantages

Disadvantages

Large Capacity

Relies on moving parts

Faster than optical disks e.g. DVDs

Disk surface can become damaged

Persistent storage

Heavy power consumption

Easily replaced / upgraded

Noisy
Slower read / write speed than RAM

SSD
A SSD can be used as an alternative to a HDD.
Rather than using spinning platters and mechanical arms there are no moving parts in
SSDs. SSDs use microchips to store data using electricity rather than magnetism. Special
transistors are used which can retain their 1 (on) or 0 (o) state even when there is no
power.
SSDs have very fast read / write speeds as there is no need to wait for a mechanical disk
to spin and an arm to move into position.
As there are no moving parts SSDs use much less power than HDDs so they are often
used in laptop computers in order to extend battery life.
As of 2013, SSDs are still a relatively new technology and as with all new technologies,
when they first emerge the price is extremely high. Due to the high costs involved, the size
of a SSD in a laptop is usually only around 300GB, compared with laptops which use
HDDs which can be over 2TB.

28

Advantages

Disadvantages

Fast read / write access

Small capacity

Robust as no moving parts

Very expensive

Low power consumption

Limited life (100,000 writes)

Silent operation
Persistent (not volatile)

Cloud Storage
People like to be able to access their files, music, photos and more from anywhere at any
time. Rather than using secondary storage such as HDDs or SSDs to store these types of
files, people are increasingly turning to cloud storage.
Cloud storage may sound very science fiction, but all this means is that rather than storing
your data on your own HDD or SSD, you instead upload it to the Internet where it is stored
on a HDD or SSD in another computer or server.
In order to access your files you can now simply login to your cloud storage system from
any computer or device as long as you have an Internet connection. At the time of writing
popular cloud storage solutions include: Google Drive, Dropbox and iCloud.

Task
Investigate the dierent types of permanent storage available. What is the
typical size and cost for a HDD or SSD in a computer today?

29

30

Random Access Memory (RAM)

The brain of the computer, the CPU, works very quickly. It constantly asks for the next
piece of data to process. The problem is, the CPU processes data much faster than
permanent storage can deliver it. Computer systems therefore make use of RAM.
RAM operates much faster than permanent storage. There are no moving parts in RAM just a set of microchips, so reading data from RAM and writing new data to RAM is very
fast.
Data is loaded from the permanent storage into RAM. Then, as and when the CPU needs
it, data is loaded from RAM into the CPU.
When a computer system is powered up, RAM is the main type of memory at work. RAM
stores the number of lives you have left in a computer game; it remembers which

31

webpage you were on when you switch to your email and then back to the web browser; it
remembers what you have written in a word processed document, even though it hasnt
been saved yet. Think of RAM as short term memory.
The more RAM a computer has, the better it can perform, especially when multitasking.
Lets say that you open up a music player, a photo editing program, a web browser, a
social networking website and a word processor - all of the data to make the programs
work needs to be loaded from permanent storage into RAM.
RAM is known as volatile memory; when you shut down your computer and turn the
power o, the contents of RAM is wiped clean. All of the data is lost.
Advantages

Disadvantages

Fast read / write access

Small capacity

Robust as no moving parts

Very expensive

Low power consumption

Volatile

Silent operation

32

ROM and Virtual Memory

Read Only Memory (ROM)


Every time you switch on your computer it performs a sequence of tasks such as checking
that all of the hardware is present, checking that a keyboard and mouse is connected and
checking to ensure that the HDD or SSD contains the operating system; this is known as a
boot sequence.
We know that RAM is volatile, so once the computer is turned o, everything in RAM is
wiped. Part of the boot sequence involves checking the HDD or SSD and we know that
these storage systems are too slow, so the instructions necessary to perform the boot
sequence cant be stored here.

33

This is where Read Only Memory (ROM) comes in. ROM is non-volatile so it stores data
even when the power is turned o. ROM is also very quick which is important when were
trying to boot up a computer and dont want to be kept waiting.
Most computers have a ROM chip built into the motherboard which stores this boot
sequence. When you turn on a computer the ROM chip gets to work, performs the
necessary checks and begins to boot the operating system.

Virtual Memory
Computers load data and instructions into RAM before passing them to the CPU for
processing. RAM is used as HDDs and SSDs are too slow. Sometimes, however,
computers do not have enough RAM to cope with all of the jobs we are trying to do. When
this happens, RAM needs to dump some of the data it has stored that isnt currently being
used into Virtual Memory in order to free up space in RAM for more urgent jobs.
When necessary the operating system designates part of the HDD or SSD as Virtual
Memory that can be used by RAM as a temporary extension.
HDDs and SSDs are slow in comparison to RAM, so computers using Virtual Memory will
suer from a significant reduction in performance. Users will notice this as they try and
switch between windows and applications.

34

Central Processing Unit (CPU)

The CPU is the brain of the computer where the sorting, calculating and searching takes
place. Although it only looks like one chip, the CPU consists of several components:
Arithmetic and Logic Unit (ALU)
Program Counter (PC)
Control Unit
Cache
Buses

35

ALU
The ALU conducts the arithmetical and logical
operations such as comparing values,
addition, subtraction, multiplication etc.

Program Counter
The PC keeps count of which instructions
have been executed and which one is next.
The PC passes this information to the control
unit.

Control Unit
The control unit keeps things ticking over
nicely within the CPU. It uses electrical signals
to ensure that the correct instructions are
executed at the correct time in the correct
order.

Cache
Cache is another type of volatile memory that is very quick (and very expensive).
Instructions and data are loaded into cache from RAM before being passed to the CPU

Buses
A bus is a pathway between dierent components of the CPU. Instructions, data and
control signals travel through buses within the CPU to the dierent components.

Fetch-Decode-Execute Cycle
Programs and data need to be fetched and loaded into RAM before they can be
executed by the CPU. Once loaded into RAM, the processor needs to decode the
string of binary digits being fed to it and determine whether it is receiving an
instruction such as ADD or a data value. The CPU can then execute the instructions
and perform the necessary calculations on the data it has been given.

36

Fetch
Get location of next instruction from Program Counter (PC), Get instruction and data by
going to specified location in register, Update (+1) to Program Counter (so the CPU knows
the address of the next instruction it needs to fetch)

Decode
The CPU now identifies the
operation code (op-code), part
of the instruction that has
been fetched so it knows
which operation to perform.
The second part of the
instruction will contain the
data to be operated upon.

Execute
The instructions and the data
are fed to the Arithmetic and
Logic Unit (ALU) which then
performs the calculation. The
result is saved back to a
register and then back to RAM
to be output to the user.

Executing Instructions
Whether its playing the latest computer game, editing an image or simply browsing the
Internet, all of those complicated tasks are broken down into a series of simple
mathematical calculations to be processed by the CPU.
The CPU runs incredibly quickly but it doesnt store data, it simply crunches numbers. We
know that data is stored using secondary storage such as a HDD or a SSD, but these
devices are not quick enough to keep supplying data to the CPU at the rate at which it can

37

process this data. Computer Systems therefore make use of RAM, and an even quicker
type of memory called cache.

This constant stream of data from the HDD (or SSD) into RAM and then into Cache means
that there will always be data ready to pass to the CPU for executing.
As cache is so fast and so expensive, computer systems do not have very much cache.
There are multiple levels of cache (depending on the brand and type of CPU).
Level 1 (L1) cache is always built into the CPU.
Level 2 (L2) cache is usually either built into the CPU or on the motherboard between the
CPU and main memory (RAM)
Level 3 (L3) cache is usually built into the motherboard
Each level of cache is increasingly quicker (L1 being the quickest) but with a smaller
capacity

38

Registers
Each CPU core executes just one instruction at a time. A typical instruction for a CPU to
execute might be:
ADD 8, 4
Right before these values are passed to the ALU, they are moved from L1 cache into the
CPU registers. Registers are very fast, very small segments of memory. Registers are
used to temporarily store the very next instruction and data to be processed. Once the
ALU has performed a calculation, the result of that calculation is then stored back to a
register, before moving back through memory into cache, then into RAM.

Hit or Miss
If everything goes to plan, the CPU will always have enough data to process. When the
CPU can find the next instructions in cache and load these into the registers ready to
execute this is known as a cache hit; the data and instructions are ready and the CPU
does not have to wait around.
If the instructions are not ready as they are still being loaded into cache from RAM (or even
from the HDD or SSD) the CPU will have to wait, this is known as a cache miss.

Clock Speed
In the human body, the beating of a heart is controlled by the Sinoatrial Node (SAN); some
individuals with heart conditions need to have a pacemaker fitted in order to replicate the
functionality of the SAN. The SAN (or pacemaker) causes the heart to beat and at that
moment oxygenated blood is pumped out of the heart and around the body, and
deoxygenated blood is pumped out of the heart into the capillaries surrounding the lungs
39

in order to collect more oxygen. In between beats the heart and the blood vessels are at
rest.
The operation of a CPU within a computer system has some remarkable similarities to this
system. Rather than a Sinoatrial node, a CPU has an electronic clock chip which keeps
time and regulates how frequently the CPU executes instructions. With each signal from
the clock chip data flows through the CPUs buses, calculations are performed by the ALU,
data is exchanged with RAM and data is read and written to the HDD or SSD.
If a computer system had a clock speed of 500Hz, this would mean 500 cycles per
second. Modern single core CPUs running at 3GHz execute around 3 billion instructions
per second. Most computer systems today have multi-core CPUs which feature 2, 4 or
even 8 cores. This means that the CPU might have up to 8 ALUs each executing several
billion instructions per second.
While a CPU might be clocked at 3GHz, the fastest RAM available today runs at
1066MHz; RAM is operating much slower than the CPU. This is why cache is so
important. L1 cache operates the same clock speed as the CPU and L2 cache operates at
a clock speed between RAM and L1 cache.
The whole operation of the computer system is timed to the clock chip and within the CPU
itself the clock chip controls the fetch-decode-execute cycle.

40

3
Software

Software describes the


sequences of instruction,
code and programs that
computers execute

What Is Software?

We know that Computer systems consist of both hardware and software working together
and weve explored hardware (the physical components of a computer system anything
that can be seen or touched which can include input, output, storage and processing
devices). So what is software?
Software describes the sequences of instruction, code and programs that computers
execute; the computer games, smartphone apps, operating systems and applications that
run on hardware.
There are several types or categories of software.

42

Operating Systems

An operating system (OS) is a collection of programs that control the system hardware
resources. The OS manages the flow of data between permanent storage (HDDs and
SSDs), main memory (RAM) and the CPU. The OS also controls communication with
peripherals connected to the computer system such as the keyboard and mouse.
An OS can be found running on almost all computer systems from digital television
recorders and smartphones to games consoles and web servers. Other software such as
word processors and web browsers rely on the OS and could not function without it.

43

Security
Part of managing the system involves protecting users, system resources and files. There
is a danger when passing data between permanent storage, main memory and the CPU
that data could be lost, corrupted or overwritten - it is the job of the OS to ensure that this
does not happen and prevent conflicts.
One computer is not necessarily used by just one person. In schools, businesses and
even at home, computers need to manage several user accounts and ensure that the
correct files and access permissions are granted to the correct users.

Graphical User Interface (GUI)


When we use computer systems we manipulate windows, click on buttons, and scroll
through menus.

We use a mouse to control a cursor on the screen and navigate this cursor to the icon we
wish to click on. This type of interface is called a Graphical User Interface (GUI). GUIs

44

allow users to interact with the system using graphical icons and visual indicators; today
this is the most common way for home users to interact with computer systems.
The way we interact with computer systems continues to change and develop. We are
increasingly using touch, voice and even gesture commands to control our computer
systems.

Command-Line Interface
Before GUIs were developed, computer users had to type in each command they wanted
to give to the computer using a command-line interface. While today home users find
using a GUI easier, many systems administrators, programmers and expert users still
prefer to use the command-line as it can allow greater control and speed up certain
processes.

Windows
Developed by Microsoft, the Windows series is still the most popular operating system for
personal computers. The first version of this proprietary commercial OS was released in
1985 and called Windows 1.0. The latest version, Windows 8, was released in 2012.

45

Mac OS
The first version of Mac OS was released in 1984 and was simply known as the system.
It was not until 1996 when the software became known as Mac OS. The latest version is
known as OS X Mountain Lion and was released in 2012.

Linux
Although not as popular as an OS for home PCs, most of the websites that we visit and
the online services that we use are hosted on computers that run a Linux OS. As Linux is
open source, any developer can freely access the source code and modify it as they
wish; this has led to the development of many dierent versions or distributions of Linux
including Debian, Ubuntu, Fedora and Red hat.
Linux is a popular choice for embedded systems and can be found controlling many
modem routers, digital and satellite television recorders and smartphones. In fact, almost
30% of smartphones in use today run a version of Linux. Did you know that Android is a
modified version of Linux?

Mobile Operating Systems


Mobile devices are designed to be used dierently to home
PCs. They need to consume less power as they run on a
battery, the screen is smaller so information needs to be
laid out appropriately, and today, most smartphones accept
touch or voice commands rather than input from a
keyboard. As such, standard operating systems were not
suitable to be used on mobile devices and developers had
to build specialist platforms suitable for this type of device.
Palm developed Palm OS and Windows developed
Windows CE in 1996, Nokia launched S40 OS (Java ME) in
1999 and Symbian brought out their OS in 2000.
Blackberry brought out their OS in 2002 and this provided
extremely popular with business users before Apple
launched iOS on the first iPhone in 2007. Google released
46

Android in 2008 and Windows unveiled Windows Phone OS in 2010.


Despite all of the available operating systems for desktop and mobile devices, some
remain dominant as depicted in the following charts .
Desktop Operating System Market Share 2013
50

37.5

25

12.5

Windows 7

Windows XP

OS X

Windows 8

Windows Vista

Linux

Other

Mobile Operating System Market Share 2013


60

45

30

15

iOS

Android

Java ME

Symbian

Blackberry

Windows Phone

Other
47

Task
Conduct some research using the Internet to find an example of a
computer system controlled by touch, voice and gesture.

48

Drivers

While the OS takes on much of the responsibility for controlling and managing peripherals
such as the mouse, keyboard and printer, it needs a little help. There are thousands of
manufacturers, producing thousands of dierent products that you might wish to connect
to your computer system; many of these peripherals may have been designed after the OS
was released - so there is no way that an OS can possibly be prepared to communicate
with and control peripherals without some additional help.
Device Drivers are small programs written by the hardware designers specifically for a
piece of hardware. When you purchase a new printer or webcam it normally comes
packaged with the drivers, or instructions about where on the Internet you can download
the drivers. A driver recognises signals sent from a piece of hardware and translates these
so that the OS understands.

49

Applications

Off the Shelf


If you need to word process an essay or report youll use a word processor application; if
you need to conduct some research on the Internet youll use a web browser application;
if you want to enhance your holiday photos youll use a photo editing application.
These applications already exist and you can purchase them from both high street and
online shops. They are called o the shelf applications as the user has no input into the
design or features of the software; the user simply buys the application as it is o the
shelf.

50

Custom
Sometimes, o the shelf software is too generic and doesnt quite work in the way youd
like it to. Some companies have very specific requirements and need software to work in a
very specific way, look a certain way or integrate with existing computer systems in a
certain way. If o the shelf software does not give businesses the control they need over
the software, they can commission a developer to build a new, custom written application.
There is often a significant cost involved in this, and as the software needs to be designed,
built and tested - it is not available immediately.

Software as a Service (SaaS)


Traditionally, if you wanted an application to perform a certain job you would go to a high
street or online store and buy it. Once installed on your computer it was yours to use. After
a period of time a new version of the software with new features might have been released
and you could choose to go and
buy the latest version, or
continue to use the (slightly out
of date) version you already
owned.
Increasingly, users are now
turning to Software as a Service
(SaaS) as an alternative. SaaS
involves users accessing
applications via the Internet
(usually using a web browser).
The software is not installed on
the users computer but is
instead hosted centrally on a
server in the cloud.
Unlike traditional software where
the user purchases the
application once, SaaS is usually sold on a subscription basis with users paying a monthly
51

fee to access this on-demand software. Although some users may prefer to own
software rather than rent it, SaaS does mean that users always have access to the latest
version of the software and can access it from any computer with an Internet connection.
Some SaaS is actually free; examples include Google Drive and Apple iCloud which allow
users to access word processing, spreadsheet and presentation applications over the
Internet which are not installed on their home computers.
SaaS does rely on a stable, reasonably fast Internet connection and as such has only
become a possibility in recent years as higher bandwidth broadband services have
become available.

Proprietary vs Open Source


Proprietary software is developed commercially to be sold in order to make money. The
developer owns the software and they allow customers to use it by selling them a license.
Only the owner of the software - the intellectual property - has the right to sell it and
modify it.
As proprietary software is sold, customers can expect a reasonable level of service and
support; there is usually a help website, telephone number or email address.
Open source software is not owned by anyone. Developers write the software either
individually or as part of a community and make it freely available. Anyone can then use
the software as it is, or edit and the source code to make new versions of the software.

52

Utilities

We know that the operating system (supported by device drivers) take care of the
hardware in a computer system and provide a platform on which applications can run. In
addition to application software, computer systems often run small maintenance programs
or utilities.
Anti-virus software, firewall software, disk management software and backup software are
examples of utilities. Often these programs run in the background and perform their jobs
without us even knowing that they are there.

53

4
Data Representation

Representing data within


computer systems is done by
turning switches on and o

Binary

What is Binary?
We need to be able to store data within a computer system and transfer it from one
computer to another, for example when sending emails, storing images, and playing
sound.
Electronic devices such as computers consist of thousands of tiny electronic switches.
The basics of any electronic device means either electricity is flowing or it is not i.e. a
switch is either on or o. Representing data within a computer system is done by turning
switches on and o.
How on earth can we represent letters, reports and essays, videos and sounds with just 1
and 0? Thats exactly what computers do and its called Binary.

55

Example
So, data is passed through and stored in computers by turning on and o
lots of tiny switches.

Switches are either ON (1) or OFF (0) therefore data in a computer can
only be represented by two numbers...1 and 0.

The normal number system that we use everyday and is very familiar to us has 10 dierent
symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. We use these symbols to write numbers, so 629
means 6 lots of 100, 2 lots of 10 and 9 1s. In primary school we may have seen this
written in a table:
Hundreds (100)

Tens (10)

Units (1)

When learning basic maths at school, decimal tables are sometimes used like this one
(below). If we had one unit and we multiply it by 10 we get one ten. If we multiplied one ten
by 10 wed end up with one hundred and so on.
Thousands

Hundreds

Tens

Units

56

The column values are 10 times the value in the previous column moving from right to left.
This is called the base 10 system, or the denary or decimal system.
Computers do not use the decimal system. They use a system based on just two
numbers: 1 and 0. This is called the binary or base 2 system.
In the same way that we multiply by 10 in the denary system to move across from right to
left, when using the binary system, multiplying by 2 moves across to the left.
See how we move across from right to left with 1, 2, 4, 8, 16, 32, 64, 128.
128

64

32

16

Binary Units
When using the denary (base 10) system we assign certain numbers special names, for
example 10 10 10 is 1000 which we call a thousand. 1 thousand multiplied by 1
thousand is called 1 million etc.
Binary also has some special names to refer to certain values.
The basic unit is 0 or 1 this is a binary digit or bit.
When talking about storing and transferring data within a computer system we talk about
bits and bytes. Bit is short for Binary Digit and a byte contains 8 bits. A nibble is
half of one byte (4 bits).

57

Binary to Denary
128

64

32

16

In the above example, we can say that we have no 128s, no 64s, 1 lot of 32, no 16s, 1 lot
of 8, no 4s, no 2s and 1 lot of 1.
So we have 32 + 8 + 1 = 41.
00101001 is therefore the binary representation or equivalent of the decimal number 41.
Here are some more numbers represented using the binary system.
128

64

32

16

The first number has a 1 for 32 and everything else has a 0, so 00100000 is binary for
32.
0

The second number has a 1 for 64 and a 1 for 16 and a 1 for 1, so we have
64 + 16 + 1 = 81, so 01010001 is binary for 81.
0

The third binary number is 00101101 so there is a 1 for 32, 8, 4 and 1.


32 + 8 + 4 + 1 = 45, so 00101101 is binary for 45!

58

Denary to Binary
Performing conversation from denary to binary is also really simple.
Lets say wed like to convert the denary number 37 into binary. First well need our binary
column headers.
128

64

32

16

Now, looking at our target number of 37 we can ask ourselves, do we need 128 to get to
37?
The answer is of course, no. 128 is too big. We can put a 0 down in the 128 column.
128

64

32

16

We can then ask, do we need 64 to get to 37? The answer is again no as 64 is bigger than
36. We put down another 0 in the 64 column.
128

64

32

16

Next, we have 32. Can we use 32 to get to 37? Yes! 32 is smaller than our target of 37 so
we can use it. Well put a 1 in the 32 column to show that were using it.
128

64

32

16

We wanted 37, so far we have 32, so were still in need of 5. Can we use 16 to get 5? No:
too big. Can we use 8 to get 5? No: too big. We can put 0 down in the 16 and the 8
column.

59

128

64

32

16

Can we use 4 to get 5? Yes! So we can put down a 1 in the 4 column. Now all we ned is
a 1, so we put down a 0 in the 2 column and a 1 in the 1 column.
128

64

32

16

Lets check our answer by adding together those values represented by a 1:


32 + 4 + 1 = 37

So we are correct!

The denary number 37 is represented as 00100101 in binary.

60

Task
Work out what numbers are being represented here as binary and write
down the decimal equivalent. The first one has been done for you.
128

64

32

16

34

61

Task
Here are some more binary numbers for you to convert to decimal but its
a little more tricky as you dont have the headings to show you what each
bit represents. The first one has been done for you.
Binary

Decimal

10000000

128

00101001

10101010

1000011

11111111

Task
Work out what numbers are being represented here in decimal and write
down the binary equivalent. The first one has been done for you.
Decimal

Binary

00000001

24

131

62

Binary Addition
When using the decimal system to add two numbers together such as 26 plus 36 we
would do:

Tens

Units

1. To add these two numbers, we first consider the units column and calculate 6 plus 6,
which results in 12.
2. Since 12 is greater than 9 (remembering that base 10 operates with digits 0-9), we
carry the 1 from the units column to the tens column and leave the 2 in the units
column.

Tens

Units

3. Considering the "tens" column, we calculate 1 + (2 + 3), which results in 6. Since 6 is


less than 9, there is nothing to "carry" and we leave 6 in the "tens" column.

Tens

Units

Binary addition works in the same way, except that only 0's and 1's can be used. This
actually makes binary addition much simpler than decimal addition. Heres an example.

63

1. To add these two numbers, we first consider the 1 column and calculate 1 + 1 which
equals 2. In binary 2 is written as 10. We carry the 1 to the 2 column and leave the 0
in the 1 column.

2. Moving on to the 2 column, we calculate 1 + (0 + 1), which again in binary is 10. We


carry the 1 to the 4 column and leave the 0 in the 2 column.

3. We now look at the 4 column and calculate 1 + (1 + 1). This equals 3 which in binary is
written as 11. We carry 1 to the 8 column and leave 1 in the 4 column.

64

4. Looking at the 8 column we see that there are no further 1s to add together which
leaves us with an answer of 1100, or 1 lot of 8, 1 lot of 4, 0 lot of 2 and 0 lot of 1. 1100 is
the binary equivalent of 12.

Here is another example, this time adding together the binary numbers:
0110101 plus 0001101.

64

32

16

1 + 1 = 10 (carry the 1)

1 + (0 + 0) = 1

1 + 1 = 10 (carry the 1)

1 + (0 + 1) = 10 (carry the 1)

1 + (1 + 0) = 10 (carry the 1)

1 + (1 + 0) = 10 (carry the 1)

1 + (0 + 0) = 1

So the answer is 1000010 (the binary equivalent of 66).

65

Task
Work out the answers to the following binary additions. Remember, your
answer should also be written in binary.
10001101 + 00101010 = ____________________________________
10100011 + 00101100 = ____________________________________
00110111 + 01011001 = ____________________________________
01010110 + 00001111 = ____________________________________

66

Twos Complement
Two's complement is a methodology used by computers to represent and process
negative integers, and its a simple way of performing binary subtraction.
To get the two's complement notation of an integer:
1.

Write out the number in binary

2.

Invert the digits

3.

Add one to the result

Twos Complement Example


Lets turn the decimal integer 59 into twos complement negative notation.
1. First we write out the binary equivalent of 59.
128

64

32

16

2. Next, we invert the digits so we turn 1s into 0s and 0s into 1s


128

64

32

16

3. Finally, we add one to the result


128

64

32

16

So, 59 is represented as 00111011 in binary and 11000101 in twos complement notation.

67

Binary Subtraction
Now were comfortable with twos complement we can use it to perform binary
subtraction. Lets say we want to subtract 9 from 49.
1. First, we write out these numbers in binary

128

64

32

16

We now convert the number to be subtracted (the 9 or 00001001) into twos complement.
2. We invert the second number
128

64

32

16

3. We then add one to the second number


128

64

32

16

68

We wanted to subtract 9 from 49.


Weve converted the 9 into twos complement
Now in order to perform the subtraction we actually add together the numbers.
256

128

64

32

16

This addition results in an overflow (e.g. the result has an extra bit on the left hand side
we started with 128, 64, 32, 16, 8, 4, 2, 1 but wed now need to have 256, 128, 64, 32,
16, 8, 4, 2, 1 in order to fit the result of this addition.)
We dont add an extra bit, we ignore and discard the overflow.
So...
256

128

64

32

16

128

64

32

16

becomes..

69

If we convert the result back to decimal form....


128

64

32

16

we have 1 lot of 32 and one lot of 8 which is 40.


Our original problem was 49 - 9 which is 40. So it worked!

70

Hexadecimal

Large binary numbers are dicult for programmers to remember and work with, and the
conversion process between decimal and binary is time consuming. We can therefore
convert these into smaller, hexadecimal (or hex) numbers.
The base 10, or denary number system uses 10 symbols: 0-9; the hexadecimal system
uses 16 symbols:
0

10

11

12

13

14

15

Hex values are represented using two numbers and / or digits, for example: 3D = 61, F7 =
247 and BB = 187.

71

Binary to Hexadecimal
The binary number for 143 is: 10001111.
128

64

32

16

This uses 8 bits or 1 byte of data. In order to covert this binary number into hex, we first
split the 1 byte into 2 nibbles (each of 4 bits).
8

Notice that we also change the column headers so that each nibble uses. 8, 4, 2, 1. We
can now work out the value of each nibble.
8

=8

8 + 4 + 2 + 1 = 15

The symbols used in hexadecimal are 0-9 and then A-F. So, any number larger than 9 will
be represented by a letter. 15, is therefore represented by F.
8

10001111 in binary is 8F in hex. Here is another example.

72

The binary number for 111 is: 01101111


128

64

32

16

4+2=6

8 + 4 + 2 + 1 = 15 (F)

01101111 in binary is 6F in hex

Task
Convert the following binary numbers to hexadecimal. The first one has
been done for you.
Decimal

Binary

54

00110110

195

11000011

99

01100011

101

01100101

200

11001000

Working Out...
0011
3

0110
6

Hex
36

73

Hexadecimal to Binary
To convert a hexadecimal number back to binary we reverse the process. Lets convert the
hex number C9 into binary.
First we can write out the number and include the nibble headers:
C
8

9
2

C represents the number 12 and we can represent 12 in binary using 8 + 4, so C = 1100


C

9 is represented in binary as 8 + 1 = 1001


C

So, C9 in hex is 11001001 in binary. Here are a couple more examples:


F

F represents 15 which in binary is 8 + 4 + 2 + 1 or 1111. FF in hex is therefore 11111111 in


binary.

74

2 + 1 = 3 which gives is 0011. In hex, A represents 10 which we get from 8 + 2. 3A in hex


is therefore 00111010 in binary.

Task
Convert the following hexadecimal numbers to binary. The first one has
been done for you.
Hex

9D

Working Out...
9
9
1001

Binary
D
13
1101

10011101

77
F2
A0
13

75

Hexadecimal to Denary
Rather than using the column headers for denary:
1000

100

10

...or for binary:


128

64

32

16

...we use just:


16

If we then wish to convert the hex number 9F into denary we can note this down below the
column headers.
16

We now need to multiply each value by the column header as follows


16

9 x 16 = 144

F x 1 = 15

9 x 16 = 144, and F (which represents 15) x 1 = 15. We then add together the two values:
144 + 15 = 159. So, 9F in hex is the equivalent of the denary number 159.

76

Here are some more examples:


16

5 x 16 = 80

D x 1 = 13

5D in hex = 93 in denary
16

7 x 16 = 112

6x1=6

76 in hex = 118 in denary


16

12 x 16 = 192

3x1=3

C3 in hex = 195 in denary

77

Task
Convert the following hexadecimal numbers to denary. The first one has
been done for you.

16

15 x 16 = 240

7x1=7
247

16

16

16

78

Denary to Hexadecimal
Should we wish to convert a denary number such as 235 into hexadecimal we divide by
16 and record the remainder.
235

16

14

r11

In hex 14 = E and 11 = B. So, 235 in denary is EB in hex.


Note that you need to use long division here, not just use the divide function on a
calculator as this will give a decimal number rather than a remainder.
Here are a couple more examples:
110

16

r14

16

r9

16

r0

110 in denary = 6E in hex.


25

25 in denary = 19 in hex.
80

80 in denary = 50 in hex.

79

Task
Convert the following denary numbers to hexadecimal. The first one has
been done for you.

15
15

16

r15

15 in denary = 0F in hex.

101
101

16

101 in denary = _______ in hex.

64
64

16

64 in denary = _______ in hex.

205
205

16

205 in denary = _______ in hex.

80

ASCII

In 1960 the American Standards Association developed a standard set of codes to be


used in telegraph systems to represent the main characters used in communications; this
set of codes is known as ASCII (American Standard Code for Information Interchange).
ASCII allows us to represent all alphabetic upper and lower case characters, all numeric
characters, 32 punctuation and other symbols including space and 32 reserved nonprintable codes.

81

ASCII Table
ASCII

Char

ASCII

NULL

32

SOH

33

STX

Char

ASCII

Char

ASCII

Char

65

97

66

98

34

67

99

ETX

35

68

100

EOT

36

69

101

ENQ

37

70

102

ACK

38

&

71

103

BEL

39

72

104

BS

40

73

105

HT

41

74

106

10

LF

42

75

107

11

VT

43

76

108

12

FF

44

77

109

13

CR

45

78

110

14

SO

46

79

111

15

SI

47

80

112

16

DLE

48

81

113

17

DC1

49

82

114

18

DC2

50

83

115

19

DC3

51

84

116

20

DC4

52

85

117

21

NAK

53

86

118

22

SYN

54

87

119

23

ETB

55

88

120

24

CAN

56

89

121

25

EM

57

90

122

26

SUB

58

91

123

27

ESC

59

92

124

28

FS

60

<

93

125

29

GS

61

94

126

30

RS

62

>

95

127

DEL

31

US

63

96

128

64

82

While ASCII was useful for textual messages, it did not allow non-English language
characters or mathematical symbols to be represented. Today we use the Unicode system
which allows us to encode all characters. ASCII is now a subset of Unicode, so 78
represents the letter N in ASCII and in Unicode.
When typing the words Sheeld Wednesday into a computer, the following sequence of
ASCII codes is generated.
S
83

104 101 102 102 105 101 108 100

W
32

87

101 100 110 101 115 100

97

121

Remember, that computers cannot deal with decimal numbers, so these ASCII codes then
need to be converted into binary to be processed by the CPU or stored.

83

Character

ASCII

Binary

Character

ASCII

Binary

83

01010011

87

01010111

104

01101000

101

01100101

101

01100101

100

01100100

102

01100110

110

01101110

102

01100110

101

01100101

105

01101001

115

01110011

101

01100101

100

01100100

108

01101100

97

01100001

100

01100100

121

01111001

Space

32

00100000

Task
Write a phrase or short sentence and convert this into ASCII codes. Pass
your code (without the original) to a friend and ask them to convert this
back into English.
You could even convert the phrase or sentence into ASCII codes and then
into binary and ask a friend to work out what the original message said.

84

Images

We know that in order to represent numbers computers use binary, or hexadecimal; to


represent letters they use ASCII which is converted into binary. Images are the same.

85

This image of a cat is made up of an arrangement of pixels which can be seen when we
enlarge the image. The second enlargement focuses on the cats eye and here we can
clearly see the pixels.
The eye consists of 10 x 10 pixels or dots. Each pixel is signalled to be on (black) (1) or o
(white) (0) using binary bits. The table below shows how the data used to represent the
cats eye would look.
0

The image of a cat uses one bit per pixel (bpp); this allows the computer to store either a 1
or 0 (black or white) for each pixel. In order for us to store more data about each pixel (e.g.
colour) well need more bits. Using 2 bits per pixel allows us to represent up to 4 colours,
3 bits gives us 8 colours, 8 bits gives us 256 colours.
1 bit

2^1 colours

2 colours

2 bits

2^2 colours

4 colours

3 bits

2^3 colours

8 colours

8 bits

2^8 colours

256 colours

16 bits

2^16 colours

65536 colours

High Colour

24 bits

2^24 colours

16777216 colours

True Colour

86

This photograph of the Sacr-Cur Basilica de Montmartre in Paris originally used 293KB
of space to store. The colour depth of the image has been reduced below. Notice what
happens to the image and the amount of memory used to store the image.
1 bit colour (2 colours) [12KB]

2 bit colour (4 colours) [18KB]

3 bit colour (8 colours) [28KB]

8 bit colour (256 colours) [95KB]

The more colours used, the greater the colour depth, and the more space required to store
the data.

87

In addition to colour depth, the resolution of an image will also aect file size.
Resolution does not mean the size (height and width) of an image.
Resolution is measured in dots (pixels) per inch (dpi). The more pixels per inch, the higher
resolution the image.
By looking at the image size properties of
our 2 bit Sacr-Cur Basilica de
Montmartre image we can see that the
dimensions are 17.64 cm (width) x 11.75 cm
(height); the resolution is 500 x 333 at 72
pixels per inch (dpi).

We can increase the dimensions of the


image (to make it appear bigger) but this
will not increase the resolution (the number
of pixels per inch). The resolution remains at
500 x 333 but as the canvas or page is
larger, there will now only be a dpi of
18.143.
When increasing the dimensions (enlarging)
an image, each pixel is simply stretched
which will look blotchy or pixelated.

88

If we zoom in on the 2 bit (4 colour) version of the Sacr-Cur Basilica de Montmartre


image we can clearly see the 4 colours used.

The computer uses 2 bits to store the four colours; each colour is assigned a binary value.

00

01

10

11

As images are stored as 1s and 0s, the computer needs to know how to interpret these
binary numbers and display the image. Metadata means data about the data and is
included with each image. The metadata specifies the colour depth (e.g. 2 colours, 4
colours, 256 colours etc.) and the height and width of the image in pixels

89

Sound

As with numbers, text and images, sound is also stored and processed by computers as
binary. If you open any sound file using an audio editor youll see something that looks like
the waveform below.

Sound waves are analogue; this means that they change continuously and do not have a
specific, measurable value. Unfortunately, specific, measurable values are exactly what
computers need as they deal with digital, not analogue information. In order to store or

90

process analogue sound waves we need to sample them and store a digital
representation of the original sound.
If we zoom in and take a closer look at the previous waveform, we can see the peaks and
troughs more clearly; these represent the high and low tones within the piece of music. In
order to sample the waveform, the computer takes measurements at various intervals
during the wave.

Sampling the waveform creates a representation of the original sound but using
measurable, specific value.
In the following sample waveform, at 1 second in, the value of the curve is 30, at 2
seconds the value is 20 and so on.

91

X (Time)

Y (Frequency)

25

30

20

15

30

10

25

10

10

Once a sound wave has been sampled and the tone recorded as a sequence of number
values, it is easy to convert these values into binary for processing and storage.
If we increase the sample frequency and record the values of the curve more often the
digital representation of the audio will sound much closer to the original analogue version
as more tones (high and low sounds) can be recorded as illustrated in the following chart.

92

A higher sample rate produces better quality sound, but takes more storage space as
more data is being recorded.
48 kHz is the recommended sample rate for most purposes, which means audio is
sampled 48,000 times per second. Human ears cannot benefit from sampling rates higher
than about 50 kHz; audio could be sampled at a higher rate than this but we (humans)
would not be able to tell the dierence.
So, sample rate is important as it determines how many dierent tones can be
represented; the higher the sample rate, the larger the range of tones. A piece of music
with lots of high frequency and low frequency notes needs a high sample rate, otherwise
those high and low parts of the music may be lost.
Bit rate is also important when thinking about digital audio. Bit rate refers to the number of
bits you have available to capture audio (remember how when talking about images, more
bits allows us to record more colours). With sounds, more bits allows us to record more
pressure levels (volume). 16 bit audio has 2^16 (65,536) dierent pressure levels that can
be recorded, 24 bit audio records 16.7 million dierent pressure levels. The more pressure
levels that can be recorded, the greater the resolution of the audio and the more accurate
the sound will be.

93

Recording 16 bit audio sampled at 44,100Hz means that the audio will play at
1,411.2kbps; this is standard CD quality sound
300kbps MP3s are compressed audio files with a reduced bit rate and reduced sample
frequency. MP3s will have a reduced range of tones due to the lower sample rate, and a
reduced range of pressures due to the reduced bit rate.

94

5
Networking

Networks allow us to pass


information between
computer systems in
dierent locations

What Are Networks?

Stand-alone computers are devices that are not connected to any other computer
system. A user can interact with a stand-alone computer and input data; the computer
may then process the data and output information back to the user, but no data is
exchanged with any other systems.
While stand-alone computers were once extremely useful, computer scientists wanted to
coordinate and pass information between computer systems in dierent locations and so
built networks; today we could not live without them.

96

Key Point
A network is a collection of two or more computers connected to one
another in order to exchange information and share resources.

The earliest example of communication between two computer systems is in 1940 when
computer scientist, George Stibitz sent instructions from one computer in New
Hampshire to another, 270 miles away, in New York.
Joseph Carl Robnett Licklider is also considered one of the most important figures in
computing history for his early vision of a world-wide computer network in 1962, long
before it was built.
Originally, computer networks were developed for military purposes. In 1969 the Advanced
Research Projects Agency deployed ARPANET (Advanced Research Projects Agency
Network).

97

The network was designed to allow communications between military installations around
the the United States; data on the network did not have to travel one particular route from
source to destination; it could instead travel via any other nodes on the network. This was
important, as ARPANET was designed to still function even if large portions of it were
destroyed.
It is said that ARPANET was designed to ensure messages could be sent even if some
areas of the country were destroyed due to nuclear war. Considering the previous map, if,
for example, HARVARD needed to send a message to UTAH, this could go from HARVARD
-> BBN -> MIT -> ILLINOIS -> UTAH. In the event that ILLINOIS was destroyed, however,
the message could instead take the route: HARVARD -> BBN -> RAND -> SDC -> UTAH.
Although originally conceived for military purposes, computer scientists quickly
recognised non-military application for computer networks. Today, we use networks on a
daily basis; examples include mobile phone networks, home computer networks and of
course, the Internet.

98

Advantages of Networks
Backup

Backing up data is much easier when all files are stored centrally on a
networked file server.

Communications

Whether its email, video conferencing, instant messaging or file sharing it wouldnt be possible without networks. The physical infrastructure
(cables and hardware) allow us to communicate instantly with people
around the world. Without networks communications would have to take
place face-to-face which would be much more costly and time consuming.

Device Sharing

Businesses often need to print and scan documents, but not every single
computer in the office needs a printer and a scanner. These peripherals
can be connected to the network so that any computer on the network can
access them.

Distributed Systems

When connected via a network it is possible to use several computers to


process the same data in order to speed up the process. The Search for
Extraterrestrial Intelligence (SETI) project distributes massive amounts of
data collected by radio telescopes via the Internet to the computers of 3
million volunteers for processing.

File / Database Sharing

Networks allow files and databases to be shared and accessed by more


than one person in more than one location. All users access the same,
up-to-date / live version of the data which makes collaboration possible.

Security

Networks usually have a central server which is responsible for managing


permissions and access rights. The network administrator can allow and
revoke access to files and resources and easily review server logs should
a problem or security breach occur. It is much easier to investigate a
problem when this can be done from the central server without needing to
visit several stand alone computers.

Software Sharing

When several computers require the same software (such as word


processing software and an email client), networks make it possible to
remotely install this software from the server. It is not necessary to go to
each computer individually to install the software, Maintaining the
software and installing updates is also far easier over the network.

99

Disadvantages of Networks

Cost

The cost of buying and installing the equipment necessary for a computer
network can be very high.

File Access

There are many advantages to files being stored in a central location on a


file server. If, however, the file server was to fail no users would be able to
access their data.

Security

One of the main advantages of networks is the fact that resources are
easy to access from any computer on the network. This is also one of the
main disadvantages. Unauthorised people may try to hack in and gain
access to information held on a computer network. Security measures
such as firewalls are necessary.

Staffing

It will usually be necessary to have specialist staff to install and manage a


computer network. Depending on the size and complexity of the network,
it may be necessary to have several full time members of staff responsible
for maintenance to ensure the network runs without issue.

Viruses

Computer viruses are usually designed to spread to other computers. An


infected stand-alone computer cannot pass this virus on, but a virus that
has infected a computer on a network could easily spread

100

Network Classification

Local Area Network (LAN)


A LAN is a collection of computer systems (and peripherals such as printers) connected
together. A LAN will link computer systems within a building and even across several
buildings on the same site (within the same geographical region), for example, the
computer systems within a university campus (that has several buildings) will be
connected together using a LAN. The organisation, in this case the university, is
responsible for installing and managing the network and the network infrastructure
(including all of the cabling).

Wide Area Network (WAN)


While a LAN is a collection of computer systems connected together on a single site, a
wide area network (WAN) is a collection of computer systems connected using additional,
101

rented infrastructure, usually spread across a wide geographical area. If a business


wanted to connect their LAN in Manchester to their LAN in London they would need to
rent cable infrastructure from telecoms companies between the two sites as they are not
able to install their own cable running the length of the country! Networks connected using
infrastructure rented from a third party are known as Wide Area Networks (WAN).

Metropolitan Area Network (MAN)


A MAN is a large computer network that spans a campus (such as a large university) or
even a metropolitan area (such as a town or city). In terms of geographical scope, a MAN
will be larger than a LAN, but smaller than a WAN. A MAN may be owned and operated by
a single organisation, but will usually be owned by more than one organisation and use the
telecoms network infrastructure.

Wireless Personal Area Network (WPAN)


Short range wireless networks are a relatively new technology but are incredibly useful.
Using a mobile device to create a personal hotspot that then allows other computer
systems to take advantage of the devices Internet connectivity is one example of a
WPAN. Sending documents to print, or connecting a smartphone to a car stereo system
via bluetooth are also examples of WPANs.

Virtual Private Network (VPN)


Installing network infrastructure can be extremely costly, especially when a WAN is
required for communication between geographically remote sites. VPNs oer an
alternative.
Rather than connecting to a private LAN or private WAN, computer systems simply
connect to the Internet. Special software than creates a tunnel between authorised
computer systems (via the Internet) creating a simulated or virtual network.

102

Network Infrastructure

In order to build computer networks, we need infrastructure including servers, clients,


network interfaces and cables.

Servers
Servers are powerful computers that serve smaller client computers on the network. They
provide and manage services which may include printing (print servers), access to files (file
servers), websites (web servers) etc. One server may provide services to thousands of
client computers.

Clients
The computers most of us use on a daily basis are clients. These are less powerful than
servers and rely on servers to provide certain services. If, for example, you wanted to print

103

a document to a networked printer, your computer (client) would send the request to a
print server; the print server would be receiving lots of requests from other clients too and
would need to manage these in a print queue. When you wish to view a webpage, the web
browser application on your computer (client) would connect to the web server and
request a webpage; the web server would be receiving lots of requests from other clients
too and would need to manage these.

Network Adapter / Network Interface Card


In order to be able to connect to a network, your computer must have a network
interface card (NIC) or adapter. A NIC is a special piece of hardware built into most
modern portable computer systems and can be a wired NIC or a wireless NIC. NICs can
be purchased and added to desktop computer systems if they do not already have one.

Hubs
If you have several computer systems that youd like to connect to a network, you can
connect them all to a hub. When a packet of data arrives into a hub it is sent out to all
connected clients.

104

Switches
Often, you dont want to send data to every client on a network. A switch is an intelligent
hub that can filter the data it receives and only send it on to the intended recipient(s).
Switches manage the flow of packets of data sent across networks and ensure that data
gets to the right place.

Modems
A modulator-demodulator (Modem) is used to convert the digital information used by
computer systems into analog signals that can be transmitted across the telephone
network.

Routers
Routers are used when connecting together more than one network; they ensure that
network trac is transmitted and received properly from one network to the next. Routers
may be used when connecting together two local area networks (LAN), a LAN to a wide
area network (WAN), or a LAN to the Internet.

IP Addresses
In order to successfully send a message from one computer to another, we need to know
where to send it. When computers connect to a network they are assigned an Internet
Protocol (IP) address; this is a unique address which is dierent to every other address
on the network.
IP addresses consist of 4 groups of decimal numbers such as: 74.125.224.72
Each decimal number represents a binary byte and computer systems will communicate
using binary - we however, write IP addresses in decimal form as its easier for us to
understand.
The IP address: 74.125.224.72 would be transmitted and read by computer systems as:
01001010 01111101 11100000 01001000

105

IP addresses can be static, so that a computer will always have the same address, or
dynamic, so that a computer may be allocated a dierent address each time it connects
to the network.

MAC Addresses
Unique Media Access Control (MAC) addresses are allocated to every Network Interface
Card (NIC) by the manufacturer. Every network interface has a dierent MAC address, so a
laptop with a wired network connection and a wireless network connection will have 2
dierent MAC addresses.
MAC addresses consist of six pairs of hexadecimal numbers such as: C1:B3:57:12:C1:F2

Bandwidth
Bandwidth describes how much data can be transmitted through a medium - which could
be wired or wireless - at one time. If a network is being used by several users at the same
time - all of whom are transmitting or receiving data - the network may slow down as there
is not sucient bandwidth.
Bandwidth is measured in bits per second (bps).

106

Network Types

Peer-to-peer
In a peer-to-peer network there is no central control or administration; all computers
connected to the network are equal. Files, software, email and printers are managed by
each user individually on their own computer.
While a peer-to-peer network is easy to configure (you just need to connect each
computer to a hub), they do have limited use because there is no central control so each
user is responsible for installing their own software updates, managing their own security,
performing their own backups etc.

107

Client-server
Most of the networks that we use regularly work on a client-server basis, or client-server
architecture. In this setup, files and software are usually stored on the server and
requested by the client as needed. Printers are connected to the server and print jobs are
sent to the printer from the client via the server.
While it can be a lengthy job to configure a client-server network, and specialist
knowledge is required, this approach makes it easier to control security, perform
maintenance and upgrades, and backup data.
Each time we connect to the Internet we join a network and become a client; each time we
use a mobile phone we connect to the
cellular network and become a client.
Each time a client sends a request, this is
sent across the network (which may
include the Internet) to the server. The
server will then collate the requested data
and respond to the client.
The client-server model is used both in the
configuration of computer and network
hardware and the applications that run on
that hardware.
A request to print a document is sent from
a client program (such as a word
processor) on a client computer to the
print server software on the print server
computer. The server software processes
the print request and responds to the
client to confirm what action has been
taken.

108

When typing a web address into a browser, the browser software is client software,
running on a client computer. The client computer sends the request across the Internet to
a server machine where the web server software processes the request and responds with
the requested webpage.

Packets and Packet Switching


Data sent between computers across a network - including the Internet needs to be
broken down into small chunks called packets. Whether its a word processed document,
a single photograph or an entire movie - it will be split into packets before transmission
and reassembled on arrival at the destination.
The early analogue telephone network used a system known as circuit switching to secure
a dedicated link between the person making the call and the person receiving the call. The
call could not take place until this dedicated connection was made.
When attempting to transmit
data from one side of the
world to the other, it is not
possible to establish a
dedicated continuous
connection between the
client and the server as this
would tie up routers,
switches and cables all over
the world.
Packet switching allows
data to be sent without
planning a dedicated route
first. At each node along the
journey - which might be a
router or a switch - each
packet of data is routed

109

along to the next node. If one node is busy, or oine, the packet can be routed via a
dierent node.
Packets that make up the same file, may travel to their destination via dierent routes and
may arrive at their destination in any order. The Transmission Control Protocol (TCP) is
responsible for ensuring that all expected packets have been received and that they are
then reassembled in the correct order.

110

Network Topologies

There are several ways of configuring a computer network, each with benefits and
drawbacks. An organisation looking to setup a network will need to consider costs and
performance when choosing which topology (configuration) to use.

111

Bus
Bus networks feature a central backbone cable to which all computer nodes including
servers and printers are connected.
When any computer
on the network needs
to pass data to another
computer, the packet
of data is sent down
the bus in both
directions to every
computer node on the
network until the
intended recipient is
found. If more than
one node attempts to
send data down the bus at the same time collisions occur and as such bus networks do
not cope well will lots of trac; they are only suitable for domestic home use, or for small
organisations with few computer nodes.
A bus network only features one main cable and and as such is relatively inexpensive to
setup.

Ring
Ring networks are setup in a circular configuration and
data travels only one way around the ring passing
from one computer to the next with each computer
acting as a repeater.
Every node in a ring network is critical; if one of the
computers is broken, it cannot pass on the data to the
next and the network will fail.

112

Star
Every node on a star network is connected to a central
server or switch; this is the most common network
infrastructure. Star networks take much longer to
setup and configure and and more expensive than the
alternatives as it is necessary to run a cable from every
computer back to the central server (which might be
quite far away). Despite these drawbacks, the
performance of star networks is much greater than the
alternatives and if any node breaks, it does not aect
any other computer on the network. It is also very
simple to add additional nodes to the network without
disrupting existing nodes.

113

Network Protocols

In order for computers networks to function, all computer systems on the network
(including clients and servers) need to understand one another. Protocols are the formal
rules that set out how communication between computers on a network will work;
successful communication can only happen if all computers follow these protocols.

Handshaking
Before data can be transmitted or received, the client and the server need to acknowledge
one another, and agree on the set of protocols that will be used. Any interaction between
computers on a network starts with the handshaking process.
The client sends a message to the server requesting a connection; kind of like a hello.
The server may be busy or oine, but if it is available, the server will respond and grant a
connection. The client will then negotiate with the server until the protocols to be used
114

have been agreed. Once this has happened, the client can go ahead and request a file or
service.

TCP
Transmission Control Protocol (TCP) is the protocol used to break up large amounts of
data into packets (small chunks of data) before they are sent over a network. The protocol
ensures that the packets are put back together correctly at the destination to recreate the
original data.

IP
Internet Protocol ensures that when sending data across a network it arrives at the correct
intended IP address.

SMTP / POP / IMAP


The Simple Mail Transfer Protocol (SMTP) is the most common protocol used for
sending email. Post Oce Protocol (POP) and Internet Message Access Protocol
(IMAP) are common protocols for retrieving email. When checking your email using POP,
the emails are usually downloaded to your computer and deleted from the mail server.
When checking your email using IMAP, the emails are generally left on the mail server. If
you only use one computer system POP is a good choice, but if you wish to access email
from multiple devices youll need to use IMAP, as POP will delete them from the mail
server.

115

HTTP
Hypertext Transfer Protocol (HTTP) is the standard protocol used for transmitting
webpages (built using Hypertext Markup Language - HTML) over the Internet. Although
modern web browsers do this for us if we forget, when visiting any website, the domain
name is also preceded by the http:// prefix to let the browser know that this protocol
needs to be used.

FTP
Viewing websites is handled using HTTP, but in order to copy those website files to the
web server (so that they become live on the Internet), we need to use the File Transfer
Protocol (FTP).

116

The Internet

The Internet is a network of networks. The Internet consists of private LANs connected by
making use of infrastructure owned and managed by third parties such as the telephone
network and fibre optic cables; the Internet is therefore a very large WAN.

Key Point
The Internet and the World Wide Web (WWW) are not the same.
The Internet is the infrastructure of cables and routers that connect
computer systems. The World Wide Web is a collection of webpages and
resources hosted (stored) on the Internet.

117

Schools and universities have their own LANs; companies and corporations have
networks; individuals have personal home networks. The Internet is simply how we
describe all of these global networks connected to one another.
The Internet isnt owned or managed by one person, or one group, or one country.

IP Addresses
As we saw in the previous Network Infrastructure section of this book, in order to
successfully send a message from one computer to another, we need to know where to
send it. This applies when talking about computer networks and the Internet.

As illustrated in the diagram above, computers are usually connected to a router (either
wirelessly or using a cable), which in turn is connected to the Internet. Each computer will
have a unique internal or private IP address; in the diagram above, the IP addresses of the
computers on the LAN are 192.168.0.5, 192.168.0.6 and 192.168.0.7. The router will have
an external, public IP address which in the diagram above is 86.23.4.12.

118

Should the computer with the internal IP address: 192.168.0.7 request a webpage, the
web server will send this webpage to the router with IP address 86.23.4.12. The router is
responsible for ensuring that the data is routed to the correct internal IP address.
Try typing what is my IP into a Google and you will be shown your public, external IP
address - that is, the IP address assigned to your router.

Domain Name System (DNS)


Websites are stored on web servers which are connected to the Internet. Websites are
accessed by typing in a Uniform Resource Locator (URL) or web address such as:
http://www.google.co.uk. This URL is in fact an alias (alternative) for the IP address of the
web server on which the website is stored.
Its much easier to remember http://www.google.co.uk than http://74.125.224.72 but both
will work.
When you enter a URL such as http://www.google.co.uk into a web browser, the browser
communicates with a special server called a Domain Name System (DNS) Server. The
DNS server runs a lookup in its database to find and translate the URL entered into the
matching IP address. The DNS then returns the correct IP which allows the browser to
request the website from the correct computer.

Hardware
Modem
Computers use binary signals (1s and 0s, on and o) to transmit data, but the telephone
network is analogue and transmits a varying voltage signal. The telephone network is a
major part of the infrastructure that allows local area networks to connect with one
another.
In order to connect to the Internet, we need a modem (modulator-demodulator) to convert
the digital information used by computer systems into analog signals that can be
transmitted across the telephone network.

119

Router
Routers are used to connect one network to another. When we connect to the Internet, we
are essentially connecting our home network to another network (the Internet), so it is
necessary to use a router. Routers ensure that packets of data leaving one network are
correctly passed to another network so that they reach the intended destination. It is
common today to buy a single box that is both the modem and router in one. This box
also often acts as a wireless access point too which allows our computers to access the
Internet wirelessly.

Hypertext Markup Language (HTML)


HTML is the standard adopted for the creation and interpretation of webpages. Even the
most complex modern webpages make use of HTML.
HTML is a text based language that uses tags to define the content of webpages. Tags
work in pairs, so it is necessary to have an opening and a closing tag. To create a large
heading, for example, we would write:
<h1>This text is our heading</h1>
Notice that we have used the opening tag <h1> and the closing tag </h1>. Some of the
most commonly used tags include:

<head>...</head>

Contains details about the webpage, such as the author of the page and the title.

<title>...</title>

The title will appear at the top of the web browser when viewing this page.

<body>...</body>

The content appearing between these tags forms the main page content.

<p>...</p>

Paragraphs are defined using these tags. Each paragraph will begin on a new line.

<h1>...</h1>

Heading tags define a title or heading. <h1> is the largest heading tag.

<img src=... />

This tag inserts an image and tells the web browser the location of the image file.

<a href=>...</>

This tag defines a hyperlink.

See some of these tags in action in the following webpage written in HTML.

120

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sheffield Wednesday Football Club</title>
</head>
<body>
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/a/a5/
Sheffield_Wednesday.svg/200px-Sheffield_Wednesday.svg.png" />
<h1>Welcome to the Unofficial Sheffield Wednesday Football Club
Website</h1>
<h3>A history of the club</h3>
<p>Sheffield Wednesday Football Club is a football club based in
Sheffield, South Yorkshire, England. They are one of the oldest
professional clubs in the world and the third oldest in the English
league.</p>
<p>The Wednesday, as they were named until 1929, were founding
members of The Football Alliance in 1889, and its first champions
that inaugural season. The Wednesday joined The Football League
three years later when the leagues merged. Sheffield Wednesday were
also one of the founding members of The Premier League in 1992.</p>
<p>For more information about Sheffield Wednesday visit <a
href="http://www.swfc.co.uk"> this link</a>
</body>
</html>
121

The HTML on the previous page when viewed using a web browser appears like this:

While HTML is used to define structure and content, Cascading Style Sheets (CSS) can
be used to control the style and appearance of webpages.

122

The following CSS code is responsible for transforming the original webpage into the
styled version.
h1
{
font-family: sans-serif;
font-size: x-large;
color: blue;
text-align: center;
}
h3
{
font-family: sans-serif;
font-size: large;
color: purple;
}
p
{
font-family: sans-serif;
font-size: medium;
color: black;
}
a
{
text-decoration: none;
}

123

Compression
Everything we do on the Internet involves uploading data from our computers, or
downloading data to our computers. When listening to music using an online streaming
service or downloading a video file a significant amount of data needs to be downloaded.
Faster Internet connectivity means that we do not now need to wait as long for data to
upload and download, but compressing data so that it takes up less space can also
speed up this process.
Lossy Compression
Removing some of the data from a file can reduce the file size and this makes transfer
over a network faster. Removing
data, means removing detail so its
important not to remove too much
detail otherwise the quality of the
file being compressed will become
unsatisfactory.
We saw in the Data
Representation chapter of this
book that reducing the quality
(compressing) a photograph from
24 bit (16,777,216 colours) to 8 bit
(256 colours) means that the image takes up just 95KB of space rather than the original
293KB of space. Although a lot of detail has been lost, it is not noticeable, as illustrated in
this 8 bit image of the Sacr-Cur Basilica de Montmartre in Paris.

124

Lossless Compression
Encoding data can allow us to reduce the file size, without losing any data or quality.
Peter Piper is a nursery rhyme and well known tongue twister:

Peter Piper picked a peck of pickled peppers. A peck of pickled peppers Peter Piper

picked. If Peter Piper picked a peck of pickled peppers, Where's the peck of pickled

peppers Peter Piper picked?

Currently this text consists of 34 words. In order to compress this section of text, we could
encode each word with a number.
peter

piper

picked

peck

of

pickled

peppers

if

wheres

10

the

11

Now, rather than 34 words, we only need 11 numbers to represent the original text as
some of the words are repeated.
1 2 3 4 5 6 7 8. 4 5 6 7 8 1 2 3. 9 1 2 3 4 5 6 7 8, 10 11 5 6 7 8 1 2 3?
We dont need to store the same word more than once and this allows us to save space.

125

Web Standard File Types


The following file formats are used for uncompressed images and sound:
Name

File Extension

Description

Bitmap

.bmp

Uncompressed image file

Waveform Audio File


Format

.wav

Uncompressed sound file used by Microsoft Windows computer


systems

Audio Interchange
File Format

.aiff

Uncompressed sound file used by Apple Macintosh computer


systems

The need, however, to reduce file size when transmitting data over the Internet has led to
the development of new compressed file formats including:
Name

File Extension

Type

Description

Graphics
Interchange Format

.gif

Lossless

Compressed bitmap image. Suitable for small images


such as icons and logos. Only supports 8 bit images.
Supports animation.

Joint Photography
Experts Group

.jpg

Lossy

Compressed bitmap image. Commonly used for


photographs both on the Internet and offline.

Portable Network
Graphics

.png

Lossless

An improved replacement for GIF. The most used


lossless image format on the Internet.

Lossy

A set of standards used to encode and compress both


sound and video. Several versions of MPEG exist are
are used to broadcast terrestrial, cable and satellite
transmissions and encode DVDs.

Lossy

The de facto standard for distributing music on the


Internet. The format is lossy, but the data removed is
generally inaudible to humans anyway so the
reduction in quality is not noticeable.

N/A

The open standard for exchanging documents.


Images and text are displayed as they were in the
original and there is no need to have the software
used to create the original.

Moving Pictures
Expert Group

Moving Pictures
Expert Group Audio
Layer 3

Portable Document
Format

.mpeg

.mp3

.pdf

126

Task
Write out your own sentence or phrase and encode this using a lossless
compression algorithm similar to the Peter Piper example.

127

6
Databases

A database is a persistent
store of related data that is
organised in such a way as
to make it useful

Thinking About Data

What is a Database
25, Sheeld and Volkswagen are pieces of data, but on their own lack meaning and
organisation. Does 25 represent age? house number? miles? We need to organise this
data so that we can understand it; then it can become useful.

Key Point
A database is a persistent store of related data that is organised in such a
way as to make it useful.

129

Databases are not temporary deposits of information they are persistent or permanent
collections; as such they are stored in computer systems on persistent or permanent
storage (HDDs or SSDs) rather than volatile memory. Databases contain related data; all
the information about one person or one thing, for example, a company might have an
employees database which contains all the related data about employees such as name,
age, address etc.

Task
For each of the organisations listed below, list the data that they would
need to collect, store, organise and search through.
the police
utility companies
hospitals
supermarkets
banks

A hospital deals with thousands of patients each day and its important that they have lots
of information about each person they treat in order to provide the best possible care.
Here is some information a hospital may collect about a patient.
Asthma

100813

Chandos

Steven

020688

325434

Hardman

Earp

Does all this make sense? Can you understand what this data means?

130

Records and Fields


Look again at the same data weve just seen. It didnt really make sense before. How
about now...

ID

FName

LName

DOB

Ward

Condition

Doctor

Admission
Date

325434

Steven

Hardman

020688

Chandos

Asthma

Earp

100813

By organising the related data (all of the data about one thing - in this case one person)
into a record consisting of several fields it all now makes much more sense.

Key Point
A field is one piece of information about one thing or one person.
A record is all of the related information about one thing or one person.

Examples of fields include the FName field or the Doctor field in a hospital database, or
the Price field or Weight field in a supermarket database.
A hospital database might have a record for Steven Hardman which includes all of the
data fields about Steven Hardman such as his ID, DOB, Ward, Condition, Doctor and
Admission Date. A supermarket products database might have a record for baked beans
consisting of all of the data fields about the baked beans product such as price, weight,
brand, store aisle and best before date.
Below is the Patients table from a hospital database which contains 5 records and each
record consists of 8 fields.

131

Flat file Databases


Flat file databases are set up using fields and records and used to store small amounts of
simple data. The list of contacts stored in your smartphone is an example of a simple flat
file database and when viewed in a Database Management System (DBMS) might look like
the image below.

While flat file databases are easy to setup, they are not appropriate when you wish to store
and manage larger quantities of related data. A hospital for example, needs to store
additional information such as ward, doctor, condition etc.

132

Database Management Systems

Organisations use Database Management Systems (DBMSs) to store, organise, add, edit,
delete and search through records. A DBMS is a piece of software that allows us to create
and work with databases. Just like a word processor allows us to create letters, a DBMS
allows us to create databases. DBMSs also manage:
Automatic Backups
Concurrency Control
Data Integrity
Data Redundancy

133

Automatic Backups
Many DBMSs allow you to schedule automatic backups. Consider the implications to a
hospital, popular social networking website, or bank of losing all of their data. It could cost
these organisations millions of pounds and even endanger lives. Its therefore critical that
organisations backup their data.

Concurrency Control
While a simple database might only need to be accessed by one person at once, some
databases need to be accessed concurrently by multiple users. At the time of writing the
most popular social networking website in the world has over 526 million active users
each day. This website, like many others, is driven by databases, and with 526 million
active users each day, the chances are that more than one person will be accessing their
databases at the same time.
DBMSs need to manage and control concurrency to avoid conflicts. Consider a ticket
sales website allocating seats and taking payment for sporting fixtures; many users may
be viewing and selecting seats at the same time. What is to stop two people choosing and
paying for the same seats at the same time? Who would the seats belong to?

134

DBMSs can lock a record if it is currently being accessed by another user to prevent this
problem from occurring. Once a record has been locked by one user, other users cannot
edit that record. There is usually a time limit on record locking. When booking tickets the
user may be given a limited amount of time to make payment (as illustrated in the previous
image) during which the record for those seats in the database is locked to prevent
anybody else from purchasing them. Once the time has elapsed, if the user has not made
payment, the database record for those seats would be unlocked and they would become
available for another user to purchase.
Record locking prevents concurrency problems and conflicting updates.

Data Integrity
If a person has integrity it means you can take them at face value: they are honest and
true. Data integrity means that the data is accurate, valid and as expected. If data is
entered incorrectly into a DBMS, or if that data is not processed correctly integrity is lost.

135

When entering data into a computer system to be stored in a DBMS validation checks can
be performed on the data to assure the integrity of the data.
Validation Check

Description

Format

Date of Birth is usually entered as DD / MM / YYYY.


Entering 01 / CB / QM34 would cause the format
validation check to fail as only numbers were
expected.

Length

UK telephone numbers are no longer than 11 digits


long. Entering 12 or more digits for a telephone
number field would cause a length check to fail.

Lookup

When entering a car registration, for example, a


lookup check might be performed to check the
registration against a list to ensure that the
registration actually exists.

Presence

This check looks to see if each field has been


completed. If a telephone number or email address
field has been left blank, the presence check will fail.

Range

A range check ensures the data entered is within a


valid range. A valid range for age might be 1-110.
Somebody inputting their age as 130 is likely to be
entering invalid data.

Type

A telephone number will have up to 12 digits and no


letters. Entering letters in a telephone number field
will cause the type check to fail.

Verification is another method of ensuring data integrity and is often used along with
validation. Typing in the same piece of data twice (such as when confirming a password) is
an example of verification - its there to make sure you dont accidentally press the wrong
key.

Data Redundancy
Within organisations there are often several departments: in a hospital for example, there
are wards specialising in the heart, the brain, fractures and bones etc.
If a patient visited several wards in a hospital and each ward created a new database
record for the patient data would be duplicated. Even if the patient only even visited one
136

ward, but attended several times, multiple records for that patient would be created as
illustrated below where David Jones has attended several times on dierent dates.

Having redundant (duplicated) data is a problem. Should the patient change their name,
move house or get a new telephone number, each department would then need to update
every single occurrence of the patients details in their records; if some departments
updated their records and other did not, there would be inconsistencies in the data.
The solution is to have one version of the data in one place which is accessed by all
departments. For anything other than very simple databases it is also often necessary to
use relational databases with multiple tables to avoid data redundancy and remove the
possibility of inconsistencies.

137

Relational Databases

Every time a patient visits the hospital, a record of that visit needs to be kept. If we were to
use a flat file database to record patient visits it may look like this:

138

Here we can see that David Jones has made several visits to the hospital and has been
treated by dierent doctors - but there are still 3 entries for David Jones in the database his FName, LName and DOB have been duplicated leading to redundant data.
Rather than using a flat file database, a hospital could use a relational database with
several tables each focusing on one thing.

The only data now stored in the patient table is ID, FName, LName and DOB. Each time a
patient visits the hospital a new record is created in the PatientVisits table; this new record
will include the Admission Data and Ward. Rather than entering the patients personal
details into the PatientVisits table which would result in data redundancy, the Patient ID is
included instead which links to the ID field of the Patient table. Similarly, rather than
including of details about the doctor in the PatientVisit table, the DoctorID is included
which links to the Doctor table.

Relations
Relational databases have relations between entities in dierent tables which allows us to
keep data about dierent entities separate e.g. keeping data about a patient separate to
the data about a doctor.
The entity relationship diagram below illustrates the relationship between a doctor who
can have many patients, but a patient only has one doctor.

139

In this diagram, the one connection is made using a single line; this is sometimes also
accompanied by the number 1. The many connection is represented using three lines
(which look a little bit like a crows foot); this is sometimes instead represented with a
single line and the n symbol.

Key Fields
One of the ideas behind relational databases is to eliminate data redundancy (the
duplication of data). In order to enforce this, every record in a database should be unique.
A primary key, or combined key can be setup to ensure that duplicate records are not
permitted.
In our hospital database Patient ID is used to uniquely identify each patient, Doctor ID is
used to uniquely identify each doctor and Visit ID is used to uniquely identify each patient
visit. Notice the key symbols which identify the primary keys in the diagram on the
previous page?
Because each table in a database must have a primary key, this primary key can appear in
other tables because of its relationship to data within those tables. When a primary key
from one table appears in another table, it is called a foreign key. In the hospital database,
DoctorID and PatientID are stored in the PatientVisits table as a foreign keys. Foreign keys
create the link that allows the data to be stored in separate tables and therefore removing
redundancy.

140

Referential Integrity Enforcement


Referential integrity refers to the relationship between tables. DBMSs use the relations
setup through primary and foreign keys to control and enforce referential integrity. Foreign
keys join tables and establish dependencies between tables. These dependencies mean
that if you change or delete a row in one table, you destroy the meaning of rows in other
tables.
Dr Earps ID: 3478, for example, might be linked to several patients through relations in the
database. If we try and simply delete the record for Dr Earp (perhaps if he has left the
hospital) his ID becomes meaningless as 3478 no longer links to data about the doctor for
that patient.
In a standard setup, the DBMS will not allow us to violate referential integrity and an error
message will be shown if we try to delete rows (doctors) from the doctor table before we
delete or amend the associated patient records.
If we need to remove a doctor from the database we will first need to go through and edit
any patient records linked to that doctor and assign them all a new doctor. When no
further records link to the doctor we will be able to delete him.

Security Measures and Views


Databases can be configured with multiple user profiles each with dierent privileges and
rights. This ensures that only authorised people can access sensitive data, but it also
removes data that is not necessary and could cause confusion.
Access is usually controlled through a username and password and once logged in,
dierent people will see dierent views.
General users of the database (such as a hospital secretary or receptionist) who may
simply need to enter new data or perform simple searches may have access to a form
view similar to the one below.

141

Forms are designed to be user friendly and do not require the user to have an expert
knowledge.
The database designer who is responsible for ensuring the database system is well
maintained may need to make changes to the fundamental structure of the database and
the relationships between tables. They will therefore need to access the logical view of the
database.

When initially building the database and in future if changes are necessary the database
designer will need to access the database tables in design view where the field names and
field data types can be set as illustrated below.
142

Separating of Data and Applications


DBMSs ensure that data is always kept separate to the application programs that need to
access it. This is important, as if application programs had free access to the data this
could create conflicts with other programs also trying to access the data. A DBMS
controls: which applications can
access data; when they can access it
and for how long; whether the
application can just read data, or
make changes too.
Separating data from applications is
also important as things change all
the time. Consider a smartphone app
which displays football fixtures. The
app does not store this data; instead
it will send a query to the DBMS
which will return the requested

143

information. If the developers of the app make changes to the app, this will not aect the
database. If the structure of the database is changed, this will not aect the app. This also
makes it possible for the database to be used by dierent apps or even entirely dierent
systems. A website may also display football fixtures and fetch this data from the same
database. The separation of data from applications makes this possible.

ACID
Interactions with databases are known as transactions and it is important that the DBMS
controls these transactions in order to prevent conflicts and maintain data integrity.
DBMSs follow the ACID properties in order to guarantee that transactions are processed
reliably.
Atomicity
Atomicity means all or nothing. It requires that either the whole transaction is completed
or that none of it is completed. If one part of the transaction fails, the entire transaction
fails, and the database state is left unchanged in the event of power failures, errors and
crashes.
Consistency
The consistency property requires that any transaction will take the database from one
valid state to another. All data written to the database must follow any validation rules that
have been set up.
Isolation
No transaction should interfere with any other transaction. The isolation property requires
that either transactions execute serially (e.g. one at a time) or if they do execute
concurrently (in parallel at the same time) they behave as though they were ran serially and
do not aect other transactions.
Durability
The durability property requires that once a transaction has been committed (completed),
the transaction will remain completed even in the event of a power cut, crashes, or errors.
144

Queries

The database can be used by people who need to query the database to find information
relevant to them. Lets say, for example, that Dr Earp wants to print o a list of his current
patients; he could run a query to find all records where the search criterion on the Doctor
field is equal to Earp.
Some DBMSs allow us to create queries visually using query by example (QBE) as
illustrated in the following image. Here, you can see that the criterion Earp has been
typed in the Criterion row under the Doctor column.

145

There are many dierent types of DBMS software (just as there are many dierent types of
word processing software); some use a GUI and allow the user to work with windows,
icons, menus and buttons, while others are controlled through a command line interface
and expert users write textual commands in a programming language called Structured
Query Language (SQL).
Most medium and large organisations today including most of the popular websites that
we use on a daily basis are driven by databases built and managed using SQL.
Expert users such as database managers often find it quicker, easier and more flexible to
write queries using SQL. The SQL statement to run the same query as the one above built
using QBE would be:

SELECT "ID", "FName", "LName", "DOB", "Ward",


"Condition", "Doctor", "Admission Date" FROM
"Patients" WHERE "Doctor" = 'Earp'

146

Once the query has been execute the following results are returned. Notice how only those
records where Doctor = Earp are returned.

It is possible to run queries that contain multiple search criteria. The following query has
two criteria and only results which match both will be displayed.

SELECT "ID", "FName", "LName", "DOB", "Ward",


"Condition", "Doctor", "Admission Date" FROM
"Patients" WHERE "Doctor" = 'Earp' AND "Condition" =
'Lungs'

147

7
Algorithms

In 1854 a British
mathematician, George
Boole, developed Boolean
Algebra

Logic Gates

In 1854 a British mathematician, George Boole, developed Boolean Algebra. Instead of an


algebra that uses numbers, boolean algebra uses truth values, true (1) and false (0).
We know that the very foundation of computing systems is based upon binary, 1 and 0, on
or o. The ALU (part of the CPU) performs simple logical calculations by evaluating the
sequences of 1s and 0s.
The relationship between input and output can be illustrated using a truth table. In truth
tables we use algebraic values such as A, B, C for inputs and P, Q and R for outputs

149

NOT

A NOT gate inverts the input so if A (the input) is equal to 1 then P (the output) will be 0.

150

AND

An AND gate requires both inputs, A and B to be 1 in order for the output to be 1. If just
one input is 1 and other is 0, the output will be 0.

1
151

OR

An OR gate will output a 1 if either input, or both is 1. If both inputs are 0, the output will
be 0.

1
152

XOR (Exclusive OR)

An XOR gate will only output high if just one input is high. If both inputs 1, or neither input
is 1, an XOR gate will output 0.

0
153

NAND

A NAND gate is also known as an inverted AND. An AND gate requires both inputs to be 1
in order to output a 1. A NAND gate is the opposite and will output a 1 if either input, or no
inputs are 1.

0
154

NOR

A NOR gate only outputs a 1 if both inputs are 0.

155

Sequencing

Computer systems run programs, and programs are simply sequences of instructions. So,
computers follow sequences of instructions, but there is often more than one way to
accomplish a task, and more than one factor influencing the running of the program.
To get a new outfit you could:
Make one yourself
Go to a large shopping centre
Go to a local shop
Browse and purchase online

156

Each of these would options would involve dierent steps or instructions. These
instructions are called algorithms.
The end result is the same; you end up with a new outfit.
Mathematical Algorithms
Mathematicians are familiar with algorithms. In maths, the word algorithm refers to a set of
instructions used to solve a problem.
If were performing long division of 75 divided by 4 we would use the following algorithm:
How many times does 4 go in to 75?
The answer is 18
How many left over?
The answer is 3

Ordering Instructions
When thinking about writing algorithms and computer programs its important to first think
through what the program is trying to achieve, and in what order.
Think about an everyday task such as making a cup of tea. What order would you put
these instructions in so that you ended up with a cup of tea? Remove bag, fill kettle, enjoy,
add milk, add tea bag, pour hot water, stir, wait for kettle to boil.

157

The correct sequence would look like this:

158

If we move the add tea bag instruction to the end - we dont end up with a cup of tea; if
we move the wait for kettle to boil instruction to the end - we dont end up with a cup of
tea. Getting instructions in the correct order - precision - is crucial here.
Similarly, think about a set of trac lights that control the flow of trac at a crossroads.
The correct sequences of instructions is show below: red, red and amber, green.

When everything is operating correctly, the trac flowing from East to West and West to
East passes safely, while the North to South and South to North trac waits at red lights.
If this sequences of instructions wasnt followed.......wed end up with big problems.

159

Flowcharting
The London Eye, also known as
the Millennium Wheel is the tallest
Ferris wheel in Europe.
The 135 metre tall structure is a
popular tourist attraction, and
while we may not really think about
it, the London Eye is fully
controlled by computer systems.

There are 32 capsules attached to the wheel, each able to hold 25 people. As these
capsules are attached to the wheel, and the wheel is rotating, what is stopping the
passengers in the pods from being turned upside down as shown in the diagram below?

160

As the large wheel rotates in


one direction, each of the pods
rotates in the opposite
direction at the same time in
order to keep the floor perfectly
level.
There are sensors in each
capsule that detect whether the
floor is level and pass this
information back to the
computer system. If the
computer detects that any
capsule is not level, it will
speed up or slow the motors as
necessary in order to bring the
floor back to normal.
Before constructing the London Eye and developing the software used to control it, a lot
of planning would have taken place. The developers would have produced structured
diagrams that illustrate how the program will work; a common method for visually
representing computer programs is to use flowcharts.
The basic symbols used when drawing flowcharts are:

To show how these symbols work, lets look at the sort of flowchart that would have been
draw by the developers of the London Eye computer system to control the floor level.

161

When the system starts it will


begin a process to monitor the
level of each capsule. Based on
the data collected, the computer
system will need to make a
decision about whether or not the
floor is level.
If the floor is level, then no action
is necessary, and the process of
monitoring the floor level can
continue. If, however, the floor is
not level, another decision is taken
about whether the floor is tilted too
much to the right.
If so, the system will need to
increase power to the motors of
the capsule in order to rotate it and
thus bring it level - this is classed
as an output from the system.
If the floor was not tilted to the right, a decision is taken as to whether the floor is tilted to
the left (and at this stage it must be) and the capsule is tilted back to the right by
increasing power to the opposite motor.

162

8
Programming

This language of 1s and 0s


that the CPU understands
is called Machine Code

Programming Languages

Before we Start
Throughout the next chapter you will see examples of programming code. Weve used
Python in this textbook, but the concepts and constructs that you will see here in Python
can easily be applied to other programming languages you might use.
Code will always be shown in a grey box, while the output, or result of running that code
will be shown in a blue box. Heres an example:

numLives = numLives + 3

13
164

The Language of Programming Languages


Programme is a UK spelling and we use it to refer to television programmes, a football
programme, a programme of events etc. It would never be correct in the UK to call it a
football program. The Americans, however, use the word program for everything
including television shows.

Unlike the Americans, in the UK, we only use the word program when referring to
computers both as a noun and a verb.
We would say:
I can program that computer. [verb]
The computer program does not work. [noun]
Developing computer programs is really fun. [noun]
We can also talking about programming, programmers and programmed as in:

165

I am a computer programmer, I am fairly good at programming and I have programmed


several apps. Notice how we use a double mm (but no e) here?

Machine Code
No matter the type of computer you are using be this a games console, a mobile device or
a traditional PC, they all feature at their heart a CPU. The only type of data that the CPU
can understand and process is 1s and 0s.
We know that computer systems operate on a base 2 or binary system with 1s and 0s on and o. The first computers were programmed by literally turning switches on and o
to input data into the system - we still do this today although we have streamlined the
process a lot.
No matter what programming language you might use to create games, apps or other
types of software, this is all ultimately converted into 1s and 0s for the CPU.
This language of 1s and 0s that the CPU understands is called Machine Code.
It is possible to create programs directly in machine code but it would be enormously time
consuming.
We know that the Von Neumann architecture used in CPUs means that data and
instructions are both stored in the same place and fed to the CPU together. The fetchdecode-execute cycle then determines which parts are instructions and which are data
values.
The following example is an example of machine code. The first byte (remember, a byte is
a sequence of 8 digits) shown here might be an instruction such as ADD; the second
byte might actually be a data value. It is for the CPU to determine what is data and what
is an instruction.

01100101 001100100

166

Instruction Sets
Although all CPUs process only binary numbers, the order in which they accept data and
instructions and the way in which instructions are converted into binary will vary between
dierent types of CPU.
The CPU used in Apple smartphones might recognise 00110101 as the ADD instruction,
and expect a data value to follow it, whereas the CPU used in some Sony laptops might
recognise 00000011 as the ADD instruction, and expect a data value to always come
before it.
Dierent CPUs expect programs written by developers to be converted into their own
particular variant of machine language which they can understand. Each CPU has its own
instruction set - the dictionary used during the conversion into machine code in order to
ensure that the CPU will be able to understand the code.

Assembly Language
Early programmers quickly tired of typing out so many 1s and 0s and thought there should
be a better, faster method.
Mnemonics (substitutes or abbreviations) are used to speed up the process, so rather
than writing out: 00000011 every time you wish to add something, 00000011 might be
substituted for ADD.
Mnemonics make the language easier for humans to read and understand, and made it
much quicker for early programmers.
This language consisting of mnemonics is known as Assembly Language.
While assembly language is great for programmers, the CPU can still only understand
machine code. Programs written in assembly language therefore need to be converted
into machine code using an assembler (a special kind of program). In order to perform
this conversion, the assembler will use a lookup table to find the mnemonic that can be
substituted for binary instructions.

167

An assembly language lookup table might look like this.


Binary

Mnemonic

00000011

ADD

10101010

MUL

1110111

MOV

High-Level Languages
Even though assembly language is a little more friendly than machine code it would still
take an incredibly long time to write complex software of the type we use today.
Assembly languages have a one-to-one correspondence of mnemonic-to-binary, so while
its a little easier to understand, you still need to write the same number of commands.
High-level languages are what we usually use today when developing software including
games and apps.

Key Point
High-level means reading and writing is really easy and it looks a lot like
regular English!

168

Some high-level languages that you might have heard of or be familiar with include:
Name

Notes

BASIC

First created in 1964, BASIC was one of the first


high-level languages that allowed non-computer
scientists to start to program.

C#

A modern language developed by Microsoft in 2000.


Often used to created computer games.

Java

Not to be confused with JavaScript. Java was created


by Sun Microsystems in 1995 and later bought by
Oracle. It is one of the most popular programming
languages in use and allows programs to be
compiled and ran on any computer.

Objective-C

Developed by Apple in 1983. Although not a new


language, it is the main language used by Apple for
their desktop and mobile operating systems, OSX
and iOS.

PHP

A popular server-sided (web based) language used to


drive many popular websites today including
Facebook.

Python

Released in 1991, Python is as popular today as it


has ever been. Programs written in Python are easy
to follow and as such it makes a great first language
to learn.

These languages do not have a one-to-one correspondence between commands and


machine code; one short command in a high-level programming language may represent
many machine level instructions.
In a high level language such as Python, in order to work out the correct answer to 8
multiplied by 8 we would write:

169

8 * 8

64

If we wanted to perform the same calculation in assembly language, as most assembly


languages dont have a multiply function we would need to add 8 lots of 8 together. It
might look like this:

ADD 00010000
ADD 00010000
STORE answer
ADD 00010000
STORE answer
ADD 00010000
STORE answer
ADD 00010000
STORE answer
ADD 00010000
STORE answer
ADD 00010000
STORE answer
ADD 00010000
STORE answer
This is clearly a much more time consuming job and only works out 8 X 8. Imagine writing
a mobile app using assembly language!

170

Generations
Weve now looked at three generations of programming languages.

High Level Language

Assembly Language

Machine Code

3rd Generation

2nd Generation

1st Generation

Uses
Statements

if (price > 150) {


discount = getDiscount()
price = price - discount
}

Uses
Mnemonics

LOAD 14X3
SUB 14X4 14X3
MOVE 14X2
STORE 14X4

Uses Binary

10110110111110100000000000000
0000000000000000000000000000
10101110101101110100101110101

171

Translators
The CPU, of course, cannot directly run high-level
languages; they need to be translated into machine
code. Remember, machine code is dierent for
dierent CPUs, so programs written in high-level
languages need to be translated into the specific
variant of machine code needed by the CPU in that
computer system.
Weve already looked at one type of translator - an
assembler - which translates assembly language
into machine code.
When it comes to high-level languages, there are
two ways of performing this translation.

Compliers
Compilers take the whole program written in a highlevel language and translate it all into machine code
before it will run.
When compiling code (which can take quite a while),
if there are any errors or bugs these are all found at
the same time; the process of compiling will stop and the programmer can then go
through and fix all of these errors.
Once all of the errors are fixed, the program can be compiled again and will run error free usually much quicker than an interpreted program as all of the translation happens before
the program runs - not during it.
Once programs have been complied, they dont need to be complied again, so the original
source code is not required. This makes it very dicult for individuals to reverse engineer
or change the software (which is seen as an advantage to software developers).

172

Complied programs will only run on the computer system that they were designed for as
the process of compiling generates CPU specific machine code. If you compile a program
to work on a particular CPU using a particular instruction set, it wont run on other CPUs
with dierent instruction sets.

Interpreters
Interpreters take one high-level line of code at a time, translate it into machine code and
run it before fetching and translating the next.
Developers love interpreted languages as its much easier to find bugs when coding. They
can keep running their programs and once an error is found, the developer can fix it and
run the program again to find the next bug.
Interpreters need to translate programs line by line while the program is running which can
slow down the running of a program and will take up more memory (RAM).
As interpreted programs are translated at runtime (when you launch the program because
you want to use it - the translation happens), they are portable. No machine code is
created in advance so the program can usually run on a range of dierent CPUs; the
interpreter will then translate the program using the correct instruction set while the
program executes.
Compiler

Interpreter

The whole program is translated before execution

Each line of code is translated one by one while the


program runs

The compiled program does not need the original


source code so this prevents reverse engineering

The program is not compiled before distribution or


sale, therefore the source code is easier to reverse
engineer.

The program runs faster as memory and CPU power


is not being used for translation

Translation happens as the program runs which can


make the program run slower

Errors for the entire program are generated at the


same time making debugging harder

Easier for developers during debugging as one line of


code is executed at once

Program is translated for a particular CPU, so once


compiled it will not work on other types of CPU.

Can run on most computer systems as the program


is translated each time for that particular CPU

173

The Basics

Print Statement
Computers are defined as being systems that take inputs, process the data and generate
outputs. We need outputs in order to understand what a computer system is doing so
that we can interact with it. In Python, the print statement is used to output data and
display this on the screen. The print statement does not send anything to your printer.

174

print(Hello and welcome to Computing Academy)

Hello and welcome to Computing Academy

Input Statement
It is also often necessary to enter data into the computer system, for example when
playing a computer game, using an app or browsing a webpage. In Python we can use the
input statement to prompt the user to enter information as follows:

input(Please enter your age)

Please enter your age

This code will prompt the user to enter their age, but it will not store or remember what the
user types in. In order to store this information we will need to assign it to a variable like
this:

age = input(Please enter your age)

Now, when the user is prompted to enter their age, anything they type in is stored in the
variable age so that we can recall and use that data later.
Lets talk more now about variables.

175

Variables and Constants

What are Variables?


Variables are one of the most basic concepts in computer programming. Computers store
data whilst programs run, even when we havent specifically asked them to (by choosing
File -> Save As).
Computer games record how many lives and points you have, and which level you are on;
when switching between several applications, web browsers remember which website you
are on and how far down the page you have scrolled; when typing an essay or report, a
word processor remembers what you have typed when switching to your email and back.
All this happens even though we havent performed a File -> Save As.
Programmers use variables when writing programs to temporarily save this type of data.

176

Understanding Variables
Picture a bank which has a
vault full of safety deposit
boxes. Customers of the bank
can rent a safety deposit box
and store anything they like
within it such as money,
jewellery and documents.
Each box will have a number
so that it can easily be
identified.
Customers can visit their
safety deposit box whenever
they like; add things into the
box, take things out of the box or change the contents of the box altogether. When the
customers goes to the bank they will use the identifier (number) so that they get the
correct box.
You can think about variables a little like bank safety deposit boxes.
Computer memory has lots of locations in which data (like lives or points in a game) can
be stored. During the course of play, the game will need to regularly access a location in
memory to store lives and then access it again later to update lives if the player gains or
loses a life.
Rather than using a number as an identifier (like a safety deposit box), we usually give
each variable a meaningful name or identifier so that we can refer to it throughout a
program. A computer game might do something like this:

numLives = 10

177

This line of code stores or assigns the number 10 to a variable (a space in memory a little
bit like a safety deposit box) with the name or identifier numLives.
Perhaps during the game a player would like to know how many lives they have left.

print(numLives)

10

This line of code simply reads the value of the variable numLives (by going to that
location in memory and fetching the value); it then uses print to display this on the
screen.
During gameplay we might gain 3 lives. The computer would need to update the variable
to reflect this.
numLives already exists (we made it at the start of the game and assigned to it the value
10. We now just want to increase the existing value of numLives by 3.

numLives = numLives + 3
print(numLives)

13

This line of code means the new value of numLives should be equal to itself + an extra
3. numLives was 10 to start with, so now when we print numLives, we get 13.

178

Key Point
Variables are called variables because the values which they store can
change (vary) throughout the program.

Websites, apps and computer games often want to personalise the experience that users
have. Its very common therefore to save the users name.

playerName = Rachel

Here, we have created a new variable and given it the name (or identifier) playerName.
Weve then assigned the value Rachel to that variable. We could now go ahead and
display this back to the user, perhaps with a nice welcome message like this:

playerName = Rachel
print(Hello, + playerName + how are you?)

Hello, Rachel how are you?

Notice how we write Hello playername, rather than Hello Rachel? This is because we
want to make use of the data that we have just stored into the variable called
playerName.

179

Constants
Constants are similar to variables, but the values that they store cannot vary...they stay
constant.
Constants are used to store data whilst a computer program runs; like variables, they also
have a name or identifier which can be used to refer to the constant.
Variables can change during a program, for example if we gain additional lives, wed
update numLives to reflect this; constants cannot. Once a constant is declared at the
start of a program and a value is assigned to it, this cannot change.
A timer program that needs to know how many minutes are in an hour, a day and a week
might declare the constants hour, day and week.

hour = 60
day = 1440
week = 10080

These constants should not, and will not change during the program.
A program used to calculate how much tax a company needs to pay on its profits might
declare the constant taxrate at the start of the program like this:

profit = 5000
taxrate = 0.20

Later, the constant taxrate might be used as follows:

180

taxdue = profit * taxrate


print(taxdue)

1000

In this example, we could have just used 0.20 in the place on the constant taxrate, but
by declaring the constant at the beginning of the program and using it throughout a
program, should the rate of tax change, wed only need to modify the constant at the
beginning of the program rather than working through many lines of code looking for every
occurrence of 0.20.

181

Data Types

What Are Datatypes?


Data comes in many dierent varieties and the computer needs to know which type of
data it is working with. This allows the computer to ensure enough space is reserved in
memory for the variable or constant you need to store.
Python automatically recognises and assigns a datatype but some programming
languages do not as you will see in the following examples.

182

Integer
Integers are whole numbers like 5, 34, 0, 4, -32, and -7. In Python we can
declare a variable to hold an integer and assign a value to it as follows:

age = 25

Some programming languages require you to specify the datatype when declaring the
variable. In Java, to declare the same variable we would write:

int age = 25;

Real (Float)
Real numbers (also known as floating point numbers) are those with decimals or
fractions such as 3.45, 1.07, 5673.4, and -5.5. In Python we declare a variable to
h o l d a fl o a t a n d a s s i g n a v a l u e t o i t a s f o l l o w s :

price = 149.50

In Java, this would be:

float price = 149.50f

183

Boolean
Boolean records the value True or False. In Python we declare a variable to hold a
boolean value and assign a value to it as follows:

answer = True
Note here that Python requires the capitalisation of the T in True. False would also
require a capital F
In Java, this would be:

boolean answer = true;


Note here that Java requires the t in true and f in false do not have capital letters.
String
A string can hold any sequence of alphanumeric characters including text, numbers and
symbols. In Python we a declare string as follows:

name = Rachel

In Java, this would be:

String name = Rachel;

Note here that Java requires the declaration of datatype String has a capital S.

184

In both Python and Java, notice that the string we wish to assign to the variable name is
enclosed in speech marks. This diers to how we assign integers or real numbers to a
variable where we do not need to use speech marks.
When working with strings, even if we choose to store numbers within the string
(remember, we can use any alphanumeric character including letters, numbers and
symbols within a string) we will not be able to perform any mathematical calculations on
those numbers. If for example we did the following:

age = 20

As we have assigned a string to the variable age, we could not now do something like:

age = age + 5

Depending on the programming language being used, doing so would either result in an
error being displayed, or in the new value being 205 rather than the intended result of 25
as the two values have been concatenated (joined together) rather than added together.

185

Operators

We would not be able to create useful and engaging applications if the only thing we could
do was assign values to variables. We need to be able to perform mathematical
operations, comparative operations and logical operations.

Mathematical Operators
Some of the mathematical operations that you will need to use frequently when
programming include: addition (+), subtraction (-), multiplication (*), division (/), integer
division (//) and modulo (%).
Mathematical operations can only be performed on numerical data types such as
integers and real numbers.

186

The following would not work as Rachel is a string, so we cannot divide it by 2:

name = Rachel
newName = name / 2

Add (+)
Here is an example of addition using the + operator to work out a total price:

price1 = 10
price2 = 15
totalprice = price1 + price2
print(totalprice)

25

The + operator has been used to add together the values stored in the two variables
price1 and price2 and store the result into another variable called totalprice.
The value stored in the variable totalprice has then been displayed on screen using
print.

187

Subtract (-)
The subtract operator can be used to work out how much money you would have after
paying tax.

grosspay = 1000
tax = 100
wages = grosspay - tax
print(wages)

900

Multiply (*)
The multiple operator can be used to calculate the revenue (money received) by selling a
certain quantity of a product.

price = 50
numSold = 10
revenue = price * numSold
print(revenue)

500

188

Divide (/)
The divide operator can be used to work out how much each person needs to pay when
splitting the bill in a restaurant.

bill = 250
people = 4
each = bill / people
print(each)

62.5

Integer Divide (//)


In the previous example, the result, 62.5, is a real number (not an integer or whole
number). There may be times when you wish to perform a division operation and
automatically disregard any decimal place, returning the result as an integer. When baking
cupcakes, you might wish to calculate roughly how many cakes youll be able to make
with one bag of flour. Decimal places are irrelevant here as you cant have 0.3 of a cake.

flour = 1000
eachCake = 35
numCakes = flour // eachCake
print(numCakes)

28
189

This code assigns the amount of flour used by one cupcake - 35g - to the variable
eachCake, and the amount of flour in a bag - 1000g - to another variable flour.
A standard divide operation: 1000 / 35 would give the result 28.57, but using integer
division as shown in the code above results in 28 - the 0.57 has been discarded
Modulo (%)
A cupcake business needs to be careful not to waste stock, so they might decide to work
out what is left over after each batch. Modulo simply the remainder of a division.

mix = 3000
eachCake = 55
numCakes = mix % eachCake
print(numCakes)

30

Here the result shows that if we had a cupcake mix of 3000g and each cupcake needed to
weigh 55g, we would have 30g of mix left over. It does not show us how many cakes we
can make, it only shows us the remainder.

190

Comparison Operators
We often want to compare values and depending on the result of this comparison take a
certain course of action. We can compare whether one value is equal to another (==), not
equal to another (!=), greater than another (>), greater than or equal to another (>=), less
than another (<) or less than or equal to another (<=).

Key Point
Note the dierence between = and ==. The single = symbol is used for
assignment; we use this when we wish to assign a value to a variable.
The double == symbol is used for comparison between two values.

Equal To (==)
We are using the Internet more and more for a variety of dierent purposes including
socialising, banking, shopping, work and school. Its now more important than ever that
our online accounts are secure, and one measure that is in place to ensure our security is
the use of passwords.
A secure system will need to check that the password entered by a user matches the
password that has been previously saved.

191

userEntered = input(Please enter your password)


actualPassword = gh%yuN&
if userEntered == actualPassword:
print(Correct Password)
else:
print(Incorrect Password)

We create a variable called userEntered and then prompt the user to type in their
password using input. Anything that the user types in is stored into the userEntered
variable.
We also have a variable called actualPassword to which we assign the correct
password.
We then need to check whether the two passwords match. Has the user typed in the
correct password?
We use an if statement to compare the two passwords and the comparison operator
== which means equal to. If the first password userEntered is equal to (==) the second
password, actualPassword, then we print a message saying Correct Password.
If this is not the case and userEntered is not equal to actualPassword we move to
the else clause of our if statement and instead print the message Incorrect
Password.

192

This is what the output would look like if we were to type in the password incorrectly.

Please enter your password


12345
Incorrect Password

This is what the output would look like if we were to type in the password correctly.

Please enter your password


gh%yuN&
Correct Password

Not Equal To (!=)


We could have written code to perform the same password check using the not equal (!=)
comparison operator instead like this.

userEntered = input(Please enter your password)


actualPassword = gh%yuN&
if userEntered != actualPassword:
print(Incorrect Password)
else:
print(Correct Password)

193

Notice that we are now using the != operator in the if statement, so if userEntered
is not equal to actualPassword we print the message Incorrect Password.
If this is not the case and userEntered is equal to actualPassword we move to the
else clause of our if statement and instead print the message Correct Password.
Greater Than (>)
We can use the greater than (>) operator to compare two value; a bank system, for
example, might check to see if a customer has enough funds in their account to make a
purchase.

currentBalance = 50
purchasePrice = 200
if purchasePrice > currentBalance:
print(Not enough funds)
else:
print(You have enough funds)

Less Than (>) and Less Than or Equal To (>=)


A company that buy second hand cars may only want to buy cars with less than 100,000
miles left on the odometer. The following code could compare a cars milage with this limit.

194

limit = 100000
carMileage = 75423
if carMileage <= limit:
print(OK, well buy your car)
else:
print(Sorry, you car has done too many miles)

The code compares the two variables limit and carMileage. Note that here we have
used the <= operator rather than just the < operator.
limit is set at 100,000. This means that as long as a car has not done more than
100,000 miles, the company will buy it - so a car that has done exactly 100,000 is OK.
Using the <= operator ensures that cars with exactly 100,000 miles are accepted.
If we only use the < operator like this:

if carMileage < limit......

...then a car that has done 100,000 miles would be rejected, because carMilage =
100000, and 100,000 is not less than the 100,000 limit - they are the same.

195

Logical Operators
Logical operators can be used in conjunction with comparison operators to build more
complex comparisons.
AND
Consider a website that can be used by customers to search for new cars. Customers can
specify their requirements, for example, the colour must be red and the brand must be
Volkswagen.

if colour == red and brand == volkswagen:


print(Weve found a car for you)
else:
print(Sorry, no cars match your search)

This code above uses the equal to (==) comparison operator to check whether the
colour of this car is equal to red. Another == is used to check whether the brand is
equal to Volkswagen.
If the customer wants both criteria to be met, the and logical operator can be used to
specify that both conditions must be met before we use the print statement to display
the message Weve found a car for you to the user.
OR
If the customer was not able to find a red volkswagen then she may have to expand
her search. Rather than searching for a red car, the customer instead wants to search for
cars manufactured by Volkswagen or Audi.

196

if brand == Audi or brand == volkswagen:


print(Weve found a car for you)
else:
print(Sorry, no cars match your search)

The code above used the or logical operator. If either of the conditions is met, the print
statement will display the message Weve found a car for you. It is not necessary
for both conditions to be met. It neither of the conditions are met, we move to the else
clause of the if statement and the second print statement displays the message
Sorry, no cars match your search.
NOT
The not logical operator inverts, or gives the opposite of an expression.

age = 25
age == 25

True

In the code above, we first assigned the value 25 to a variable called age. We then used
the expression age == 25 which checks to see whether the value assigned to the
variable age is equal to 25. In this case it is, so we see the output True.

197

age = 25
not age == 25

False

In the code above, the output should be True (because 25 is equal to the value assigned
to age, but we have used the logical operator not, which inverts the result.

198

IF Statements

Using If
Programs need to make selections and decisions all the time; if statements can change
the path taken through a computer program and select a new path. The basic structure of
an if statement is as follows:
if [this condition is met] then
[do this]
else
[do this]

199

The syntax of an if statement will vary between languages but here are some examples.
The following example written in Python uses an if statement to compare two numbers, 5
and 6.

if 5 < 6:
print(It is less.)
else:
print(It is not less.)

It is less.

if 5 is less than (<) 6 then the first print statement will run: print(It is less.).
If 5 is not less than 6 then the first print statement would be ignored, and we would
skip to the else clause and execute the second print statement: print(It is not
less.)
Notice in Python that we do not use curly brackets { }, and rather than writing then we
just use a colon :

200

In Java, the same code would look like this:

if (5 < 6)
{
System.out.println("It is less.");
}
else
{
System.out.println("It is not less");
}

So far, the if statements that we have seen just have two options: what to do if the
condition is true and what to do if the condition is false.
Consider a shopping website that personalises content depending on whether the
customer is male or female.

gender = Female
if gender == Male:
print(Taking you to the mens section...)
elif gender == Female:
print(Taking you to the womens section...)

Taking you to the womens section...

201

The code above allows us to check several expressions and then execute some actions
once one of the expressions is found to be true.
In this example, gender = Female. The first expression gender == Male
therefore evaluates as false, so the first print statement is ignored. The program
continues to the elif statement which now introduces a second expression for
evaluation: gender == Female. This expression evaluates as true, therefore the
print statement: print(Taking you to the womens section...) executes.

Key Point
Note that in some programming languages we write an else if clause. using
elseif. In Python this is written elif.

In the next example, we have four expressions and only one will evaluate to true.
Customers of the shopping website can be a Man, Woman, Boy or Girl,
and each type of customer will be shown a message intended for them.

202

type = Boy
if type == Man:
print(Taking you to the mens section...)
elif type == Woman:
print(Taking you to the womens section...)
elif type == Boy:
print(Taking you to the boys section...)
elif type == Girl:
print(Taking you to the girls section...)

Taking you to the boys section...

The first two expressions evaluate as false so the program skips to the third expression:
type == Boy which evaluates as true.

203

Nested If Statements
It is often necessary to ensure several expressions are true before executing some code.
Weve seen already that we can do this with the logical operator and, as in:

if colour == red and brand == volkswagen:


print(Weve found a car for you)
else:
print(Sorry, no cars match your search)

Sometimes, however, we need even more control. The code above demands that the car
is red and a Volkswagen. We might want to take a dierent course of action if just a red
c a r w a s f o u n d , o r i f j u s t a Vo l k s w a g e n w a s f o u n d .

if colour == red:
if brand == volkswagen:
print(Weve found a red volkswagen for you)
else:
print(Weve found a red car for you)
else:
print(Sorry, no cars match your search)

204

So, this code uses nested if statements. If the first expression evaluates as false (the
colour is not red), the program skips right to the bottom and executes the else clause: the
print statement displays:

Sorry, no cars match your search

If the first expression evaluates as true (the car is red), a second expression is then
immediately evaluated: brand == volkswagen. If this expression also evaluates as
true

the

print

statement displays:

Weve found a red volkswagen for you

If, however, brand == volkswagen evaluates as false, the program skips to the
fi r s t e l s e c l a u s e a n d t h e p r i n t s t a t e m e n t d i s p l a y s :

Weve found a red car for you

The indentation helps us to keep track of which part of the program is running: notice
how one

if..else... block is indented within another if..else... block as

indicated by the red and orange lines?

205

Loops

We often need to repeat a process when writing programs. Rather than copying and
pasting the same chunk of code several times, it is much more ecient to use a loop.
Lets say that we simply want to print the numbers 0 - 100 on the screen.

count = 1
while (count <= 100):
print(count)
count = count + 1

206

This code first sets the count to 1. We then use a while loop to tell the computer that we
want to continue to repeat or iterate through this code while (count = <= 100).
When count becomes 100, the loop will stop.
The first time through the loop, count = 1, therefore the print(count) statement
displays 1 on the screen.

The last line of code increases the value of count by 1. There will then be a second pass
over the loop. count is now equal to 2 (which is less than 100 so the program will
continue). The print(count) statement displays 2 on the screen.

1
2

This loop will continue to iterate while (count <= 100).

207

Lists / Arrays

We know that variables can be used to store data. Consider a travel agency who have a
computer system with a list of destinations. We could use a variable destination to
store the first destination.

destination = Alicante

The problem would be, that when we wish to store the second destination:

208

destination = Berlin
The original value stored in the variable is overwritten. The value of destination is now
Berlin and Alicante has been lost.
We could of course create multiple variables:

destination1 = Alicante
destination2 = Berlin
destination3 = Calais
...but this method takes up quite a lot of memory and makes is harder to use this
information later. The way in which we should store a list of items such as this is by using
a one-dimensional array.

destinations = [Alicante, Berlin, Calais,


Dijon, Espinosa]
Here we have declared a new variable called destinations which is an array. In order
to access elements within the array we can now just use the position of that element
within the array:

print(destinations[1])

Berlin

209

Note that the first location is an array is 0, so in the previous example, in order to print
Berlin, we accessed destinations[1] which is actually the second element in the
array.
Arrays can be used eectively with loops. Imagine that we now wanted to print a list of
t h e s e d e s t i n a t i o n s . We c o u l d w r i t e :

print(destinations[0])
print(destinations[1])
print(destinations[2])
print(destinations[3])
print(destinations[4])
...but this code is not ecient as we have essentially written the same thing five times.
The follow code iterates through a loop, accessing and printing each element. Only one
print statement is used and we would need no additional code for an array containing
thousands of destinations. This makes it much more ecient.

arraySize = 4
count = 0
while (count < arraySize):
print(destinations[count])
count = count + 1

Alicante
Berlin
Calais
Dijon
Espinosa

210

Documenting Code

Even simple computer programs consist of thousands of lines of code. Often, it can take
months or even years to write complex computer programs such as console games, and
these games may be developed by several people.
Furthermore, developers might not work for the same company forever, so someone new
will need to come in and continue to develop the game.
It is standard practice to document or comment your code in order to ensure that you
can look back at your code in several days, months or years and understand what you
have done and why. Comments are written in plain English by the programmer.
Comments are ignored by interpreters and compilers and so do not aect the running of a
program.

211

Using comments significantly improves the readability of your code and helps when it
comes to debugging code.

//prompt the user to enter their password


//save it to a new variable called userEntered
userEntered = input(Please enter your password)
//store actual password to a new variable
actualPassword = gh%yuN&
//compare password entered by user to actual
if userEntered != actualPassword:
//if passwords do not match
print(Incorrect Password)
else:
//if passwords do match
print(Correct Password)

Here is some code we saw earlier for checking passwords. It has now has comments
added to it so that it is clear what each line of the code does.

212

ccxiii

Вам также может понравиться