You are on page 1of 249

COMPUTER

SCEINCE
NOTES AND
WORKED
EXAMPLES
PERSON
IGCSE
2024
DATA REPRESENTATION

Number Systems
Computers & Binary
Number Systems
Converting Between Binary & Denary
Converting Binary to Hexadecimal Walkthrough:
Hexadecimal
Binary Addition
Binary Shifts
Two's Complement

Text, Sound & Images


Character Sets
Representing Sound
Representing Images

Data Storage and Compression


Data storage
Compression

DATA TRANSMISSION

Types and Methods of Data Transmission


Data Packets
Data Transmission
USB

Methods of Error Detection


Error Checking
Error Detection Methods
Check Digits
Automatic Repeat Request (ARQ)

Encryption
Encryption

HARDWARE

Computer Architecture
The CPU & Microprocessor
Von Neumann Architecture
The Fetch, Decode, Execute cycle
CPU Performance
Instruction Sets
Embedded Systems

Input and Output Devices


Input Devices
Output Devices
Sensors

Data storage
Primary Storage
Secondary Storage
Virtual Memory
Cloud Storage

Network Hardware
Network Interface Card
MAC Addresses
IP Address
Router

SOFTWARE

Types of Software and Interrupts


System Software & Application Software
The Operating System
Interrupts

Types of Programming Language, Translators & IDEs


High & Low Level Languages
Assembly Language
Translators
IDE

THE INTERNET AND ITS USES

The internet and Its Uses


The Internet & WWW
URL
Ip addresses
Protocols
Web Browser
Web Pages
Cookies

Digital Currency
Digital Currency

Cyber Security
Cyber Security Threats
Keeping Data Safe
Ethics

AUTOMATED AND EMERGING TECHNOLOGIES

Automated Systems
Automated Systems

Robotics
Robotics

Artificial Intelligence
AI

ALGORITHM DESIGN AND PROBLEM SOLVING


Development Life Cycle
Abstraction
Program Development Life Cycle - Design
Program Development Life Cycle – Coding
Program Development Life Cycle - Testing

Algorithms
Explaining Algorithms

Standard methods

Validation and Testing


Validation
Test Data
Trace Tables

Identifying Errors
Identifying Errors
Writing & Amending Algorithms

PROGRAMMING

Programming Concepts
Data Types
Variables & Constants
Input & Output
Sequence
Selection
Iteration
Totalling & Counting
String Handling
Arithmetic, Logical & Boolean Operators
Nested Statements
Procedures & Functions
Local & Global Variables
Library Routines
Maintaining Programs

Arrays
Array
Using Arrays

File handling
File handling

DATABASE

Database Theory
Databases
Primary Keys

SQL
SQL

BOOLEAN LOGIC
Logic Gates
Logic Gates
Logic Circuits
Truth Tables

Logic Expressions
Logic Expressions
Data
Representation
Number Systems
Computers & Binary
Why Do Computers Use Binary?
• All data needs to be converted to binary to be processed by a computer
• Binary is a numbering system that uses only 0s (off) and 1s (on)
• A computer uses binary data for all of its operations
• The 0’s and 1’s are called bits. “Bits” is short for binary digits
• A bit is the smallest unit of data a computer can use (a single 0 or 1)
• Bits can be grouped to form larger units of data, such as bytes, kilobytes, etc.
• By using binary, computers can process and store data using electronic transis-
tors that can be either on or off
• Millions or billions of transistors fit onto a microchip
• Any form of data, including text, images, and sound, needs to be converted to bi-
nary before it can be processed by a computer
• This conversion process involves assigning a binary code to each character, pixel, or
sample in the data
• The resulting binary code can then be processed using logic gates and stored in reg-
isters

Logic Gates

• Logic gates are electronic devices that perform logical operations on binary data
• Logic gates are used to process binary data by applying Boolean logic to the input
values and producing a binary output
• Registers are temporary storage areas in a computer's CPU (central processing unit)
that hold binary data during processing
• Registers are used to store data that needs to be accessed quickly, such as variables
in a program or data being manipulated by logic gates
• The size of a register determines the maximum amount of binary data that can be
stored in it at one time
Number Systems
The Denary, Binary & Hexadecimal Number Systems
• In Computer Science there are 3 numbering systems used to represent data:
o Denary
o Binary
o Hexadecimal
The Denary Number System
• The denary number system, also known as the decimal system, is a base-10 number-
ing system that uses 10 digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9
• Denary numbers can be used to represent any quantity, including whole numbers,
fractions, and decimals
• Each digit in a denary number represents a power of 10, with the rightmost digit
representing 100, the next representing 101, and so on
• It is necessary to convert data from one number system to another eg. denary to bi-
nary or denary to hexadecimal
• It is much easier to do conversions with a table:
o The number 3268 (three thousand two hundred and sixty-eight) can be rep-
resented in the following table:

• (3 x 1000) + (2 x 100) + (6 x 10) + (8 x 1) = 3268


The Binary Number System
• The binary number system is a base-2 numbering system that uses only two digits: 0
and 1
• Each digit in a binary number represents a power of 2, with the rightmost digit rep-
resenting 20, the next representing 21, and so on.
• Eg: the number 12 represented in binary is 1100:

• We know this as (1 x 8) + (1 x 4) + (0 x 2) + 0 x 1) =12


The Hexadecimal Number System:
• The hexadecimal number system is a base-16 numbering system that uses 16 digits:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F where 10 is represented by A, 11 by B
and so on up to 15 represented by F
• Each digit in a hexadecimal number represents a power of 16, with the rightmost
digit representing 160, the next representing 161, and so on
• E.g. the number 146 represented in hexadecimal is 92

• (0 x 4096) + (0 x 256) + (9 x 16) + (2 x 1) = 146


Exam Tip
YOU NEED TO BE ABLE TO MAKE CONVERSIONS IN BOTH DIRECTIONS, E.G. DENARY TO BI-
NARY OR BINARY TO DENARY. MAKE SURE YOU WRITE THE TABLE THE CORRECT WAY
ROUND (WITH 1 IN THE RIGHT HAND COLUMN) & USE THE CORRECT NUMBER OF BITS IN
YOUR ANSWER (THE QUESTION SHOULD TELL YOU BUT USE MULTIPLES OF 4 BITS IF
YOU’RE NOT SURE)
Converting Between Binary & Denary
Converting Denary to Binary Walkthrough:
• Write down the powers of 2 in binary from right to left, starting with 20 (1), 21 (2),
22 (4), 23 (8), and so on, until you reach 128 (as answers must be given in 8 bits)

128 64 32 16 8 4 2 1

0 0 1 0 1 0 1 1
• Starting from the leftmost column, write a 1 if the corresponding power of 2 is less
than or equal to the number you’re converting, 171 in this example, otherwise write
a 0.

128 64 32 16 8 4 2 1
1 0 1 0 1 0 1 1
• Check your working by adding together all column headings with a 1 underneath
(128+32+8+2+1=171)
• Read the binary digits from left to right to get the binary equivalent of 171.
10101011

Converting Binary to Denary Walkthrough:


• Write down the powers of 2 in decimal from right to left, starting with 20 (1), 21 (2),
22 (4), 23 (8), and so on, until you reach 128 (as answers must be given in 8 bits)
128 64 32 16 8 4 2 1
• Starting from the leftmost column, write the binary digit in the column if it is a 1
write 1, and write 0 if it is a 0.
128 64 32 16 8 4 2 1
0 1 1 0 0 1 1 0
• Add up the values in each column where the binary digit is 1.
64 + 32 + 4 + 2 = 102

Exam Tip
IF THE QUESTION TELLS YOU TO SHOW YOUR WORKING YOU WILL GET A MARK FOR THIS
SO DON'T FORGET TO WRITE DOWN YOURS

V
Converting Binary to Hexadecimal Walkthrough:
• Group the binary digits into groups of 4, starting from the rightmost digit. If there
are not enough digits to make a group of 4, add leading zeros as needed.
0110 1110

• Add column headings to work out the value of each nibble

8 4 2 1 8 4 2 1
0 1 1 0 1 1 1 0
4+2 = 6 8+4+2=14 = E in hex
• Replace each group of 4 bits with its corresponding hexadecimal value:
0110 1110
6 E
• Write down the resulting hexadecimal values to get the final answer:
6E
Converting Hexadecimal to Binary Walkthrough:
• To convert a Hex number like A2 into binary write each hex digit in 4-bit binary

• A=10
8 4 2 1 8 4 2 1
1 0 1 0 0 0 1 0
• The binary representation is the numbers altogether: 10100010
Hexadecimal
Why Use Hexadecimal?
• Hexadecimal numbers are often used as a beneficial method of data representation
in computer science
• It takes fewer digits to represent a given value in hexadecimal than in binary
• One hexadecimal digit can represent four bits of binary data
• It is beneficial to use hexadecimal over binary because:
o The more bits there are in a binary number, the harder it is to read
o Numbers with more bits are more prone to errors when being copied

Worked example
The following binary number has 24 bits: 101110110011101011101010. Write the number in
hexadecimal and explain why it is better to write the number in hexadecimal rather than in
binary.
• This number can be represented with only 6 digits in hexadecimal:
• B B 3 A E A Mark for each character [6]
• This number is:
o Much shorter and a more efficient way of representing numbers [1]
o Easier to spot any errors in [1]

How is Hexadecimal used in Computers?


• Using hexadecimal allows computer scientists to represent large amounts of binary
data in a more manageable and readable format
• There are many uses of hexadecimal in computers:
o Memory addresses and other hardware related values
o Representation of colour values
o Error messages
o Memory dump
o Debugging
o IP addresses
o ASCII / Unicode
o Assembly language
o URLs
• Representation of colour values in HTML/CSS and in computer graphics: eg. RGB
(red-green-blue) colour values can be represented in a compact and readable for-
mat. E.g. #FF0000
• Error messages & debugging: eg. 0x80070643 to give technicians/developers infor-
mation about what the error is in relation to
• Memory dump: this is a record of what happened in the computer's memory at the
time of an error. These are often difficult to read because they contain a lot of tech-
nical information, but computers can use hexadecimal values in memory dumps to
identify specific memory locations and values.
o Eg. A video game on a computer crashes and a memory dump is created. A
technician analyses the memory dump and looks for hexadecimal values to
identify the cause of the crash. They might look for specific memory ad-
dresses and values that relate to the game being played or the graphics card
in the computer.
• IP addresses:
o Hexadecimal values can be used to represent each set of numbers in an IP
address
o Each set of numbers can be converted into a two-digit hexadecimal value,
giving a total of eight digits in the IP address
o Eg. the IP address "192.168.0.1" could be represented in hexadecimal as
"C0A80001"
o The hexadecimal values can make IP addresses easier to work with in some
cases, such as when configuring network devices or writing scripts that inter-
act with IP addresses, however, they are not commonly used in everyday
applications or browsing the internet
• ASCII / Unicode: eg. The letter "A" is represented in ASCII as the decimal value 65,
which is equivalent to the binary value 01000001. This binary value can also be rep-
resented in hexadecimal as the value 41
• Assembly language:
o Hexadecimal values are used in assembly language to represent the binary
code for the instructions and data
o Each instruction or data value is represented by a specific sequence of hexa-
decimal digits, which can make it easier for programmers to read and under-
stand the code
o Eg. "MOV AX, 5" instruction is represented by the hexadecimal value
"B805", which tells the computer to move the value 5 into register AX
• URLs:
o To encode a space in a URL using hexadecimal, the space character is re-
placed by a percent sign ("%") followed by the hexadecimal value of the
space character. In ASCII, the space character has a decimal value of 32,
which can be represented in hexadecimal as "20".
o So, to encode the URL "my website.com/page one" using hexadecimal, it
would look like this: my%20website.com/page%20one

Exam Tip
• When a question is asked which asks you to name a certain number of uses of hexa-
decimal, ensure you write the number asked for and no more. E.g. name 3 uses of
hexadecimal - if you write more than 3, the last ones will be ignored by the exam-
iner, even if they’re correct
• If you're asked to name any uses of hexadecimal, don't write down any given in the
question as you won't get marks for this
Binary Addition
• Adding binary numbers follows a similar process to adding denary numbers

• The binary adding rules are:


o 0+0=0
o 0+1=1
o 1+1=10 (The 1 is carried into the next column on the left)
o 1+1+1=11 (The 1 is carried into the next column on the left)

Adding binary steps:


Step 1:
• Start by writing the two binary numbers you want to add underneath each other,
with the least significant bit (LSB) on the right.
Step 2:
• Begin by adding the LSBs together. If the sum is less than or equal to 1, write it down
in the sum column. If the sum is 2 or greater, write the remainder of the sum (i.e.,
the sum minus 2) in the sum column and carry over the quotient (i.e., 1) to the next
column
Step 3:
• Repeat this process for the next column to the left, adding the two bits and any
carryover from the previous column. Again, if the sum is less than or equal to 1,
write it down in the sum column; if the sum is 2 or greater, write the remainder of
the sum in the sum column and carry over the quotient to the next column.
Step 4:
• Continue this process for each subsequent column until you have added all the bits.
Step 5:
• If the sum of the last two bits produces a carryover, add an additional bit to the left
of the sum to represent the carryover.
Step 6:
• Check the sum to make sure it fits within 8 bits. If it doesn't, you will need to use
more bits to represent the sum.
Adding binary walkthrough:

• In this example, we start by adding the two LSBs: 0 + 0 = 0, which we write down in
the sum column
• We then move to the next column to the left and add the two bits and the carryover
from the previous column: 1 + 1 + 0 = 10
• We write down the remainder of the sum (i.e., 0) in the sum column and carry over
the quotient (i.e., 1) to the next column
• We repeat this process for the next two columns, and end up with the sum
101110000

Overflow
• An overflow error occurs when the result of a binary addition exceeds the maxi-
mum value that can be represented. In the case of 8-bits, the maximum value is 255
• Overflow occurs when the addition of two numbers results in a carry bit that cannot
be accommodated
• To avoid overflow errors, it's important to check the result of binary addition to en-
sure that it doesn't exceed the maximum value that can be represented
• Overflow errors can also occur in other operations besides addition, such as multi-
plication or division

Exam Tip
YOU CAN CONVERT YOUR BINARY NUMBERS TO DENARY, THEN PERFORM THE CALCULA-
TION AND THEN CONVERT THEM BACK TO CHECK YOU’VE GOT THE RIGHT ANSWER. LABEL
THIS AS CHECKING TO MAKE SURE THAT THE EXAMINER KNOWS THIS IS A CHECK AND NOT
PART OF YOUR WORKING OUT
Binary Shifts

• A binary shift is the term used for multiplying or dividing in binary


• A binary shift moves all the bits in a binary number a certain number of positions to
the left or right
• When performing a logical binary shift to the left, the bits shifted from the end of
the register are lost, and zeros are shifted in at the opposite end
• When performing a logical binary shift to the right, the bits shifted from the begin-
ning of the register are lost, and zeros are shifted in at the opposite end
• When performing a logical binary shift, the positive binary integer is multiplied or
divided according to the shift performed. A shift to the left is equivalent to multipli-
cation by a power of 2, while a shift to the right is equivalent to division by a power
of 2
• When performing a logical binary shift, the most significant bit(s) or least significant
bit(s) are lost, depending on the direction of the shift

Binary shift walkthrough:


• E.g. shifting the binary number 11001100 to the left by two positions gives
00110000. The two bits shifted from the end are lost, and two zeros are shifted in at
the opposite end
• E.g. shifting the binary number 11001100 to the right by two positions gives
00110011. The two bits shifted from the beginning are lost, and two zeros are
shifted in at the opposite end
• E.g. shifting 11001100 to the left by two positions, is multiplying it by 22, or 4. The
result is 00110000, which is equal to 4 times the original value
• Shifting the binary number 11001100 to the right by two positions, is dividing it by
22, or 4. The result is 00110011, which is equal to the original value divided by 4

Exam Tip
MAKE SURE YOU’VE GOT THE SAME NUMBER OF BITS IN YOUR ANSWER AS THERE WERE
IN THE QUESTION. CHECK YOUR ANSWER BY CONVERTING THE BINARY NUMBER TO DE-
NARY, WORKING OUT YOUR ANSWER AND CONVERTING IT BACK AGAIN. MAKE SURE TO
LABEL THIS CHECKING SO THE EXAMINER KNOWS IT ISN’T PART OF YOUR WORKING OUT
Two's Complement
• Two's complement is a method of representing signed integers in binary form,
where the leftmost bit represents the sign (0 for positive and 1 for negative)
• To convert a positive number to a two's complement 8-bit integer, first represent
the number in binary form with leading zeros until it is 8 bits long. If the number is
positive, the leftmost bit should be 0
• To convert a negative number to a two's complement 8-bit integer, first invert all
the bits in the binary representation of the positive equivalent of the number (i.e.,
flip all the 1's to 0's and all the 0's to 1's). Then, add 1 to the result to obtain the
two's complement representation

Two's complement walkthrough:


• The binary number 00101011 represents the positive integer 43 in 8-bit binary form
• E.g. to represent the negative integer -43 in two's complement 8-bit form, start by
representing the positive equivalent of 43 in binary form: 00101011. Then invert all
the bits to get 11010100, and add 1 to get 11010101
Text, Sound & Images
Character Sets
• Text is a collection of characters that can be represented in binary, which is
the language that computers use to process information
• To represent text in binary, a computer uses a character set, which is a col-
lection of characters and the corresponding binary codes that represent
them
• One of the most commonly used character sets is the American Standard
Code for Information Interchange (ASCII), which assigns a unique 7-bit binary
code to each character, including uppercase and lowercase letters, digits,
punctuation marks, and control characters
• E.g. The ASCII code for the uppercase letter 'A' is 01000001, while the code
for the character '?' is 00111111
• ASCII has limitations in terms of the number of characters it can represent,
and it does not support characters from languages other than English
• To address these limitations, Unicode was developed as a character encoding
standard that allows for a greater range of characters and symbols than
ASCII, including different languages and emojis
• Unicode uses a variable-length encoding scheme that assigns a unique code
to each character, which can be represented in binary form using multiple
bytes
• E.g. The Unicode code for the heart symbol is U+2665, which can be repre-
sented in binary form as 11100110 10011000 10100101
• As Unicode requires more bits per character than ASCII, it can result in larger
file sizes and slower processing times when working with text-based data
Representing Sound
• Sound is a type of analog signal that is captured and converted into digital form to
be processed by a computer.
• To convert sound into digital form, a process called sampling is used. This involves
taking measurements of the sound wave at regular intervals and converting these
measurements into binary data
• The quality of the digital sound depends on the sample rate, which is the number of
samples taken per second. A higher sample rate results in a more accurate repre-
sentation of the original sound wave, but also increases the file size of the digital
sound
• E.g. A typical CD-quality digital sound has a sample rate of 44.1 kHz, which means
that 44,100 samples are taken per second
• The sample resolution is another factor that affects the quality of the digital sound.
This refers to the number of bits per sample, which determines the level of detail
and accuracy of each sample
• A higher sample resolution results in a more accurate representation of the sound
wave, but also increases the file size of the digital sound
• E.g. A CD-quality digital sound typically has a sample resolution of 16 bits, which
means that each sample is represented by a 16-bit binary number
• It's important to choose the appropriate sample rate and resolution based on the
specific requirements of the digital sound application. E.g. A high-quality music re-
cording may require a higher sample rate and resolution than a voice recording for a
podcast
• Two examples of sound files are:
o MIDI
▪ Musical Instrument Digital Interface (file)
▪ Stores a set of instructions (for how the sound should be played)
▪ It does not store the actual sounds
▪ Data in the file has been recorded using digital instruments
▪ Specifies the note to be played
▪ Specifies when each note plays and stops playing
▪ Specifies the duration of the note
▪ Specifies the volume of the note
▪ Specifies the tempo
▪ Specifies the type of instrument
▪ Individual notes can be edited
o MP3
▪ MP3 is a format for digital audio
▪ MP3 is an actual recording of the sound
▪ MP3 is a (lossy) compression format
▪ It is recorded using a microphone
Representing Images
• A bitmap image is made up of a series of pixels, which are small dots of colour that
are arranged in a grid. Each pixel can be represented by a binary code, which is pro-
cessed by a computer
• The resolution of an image refers to the number of pixels in the image. A higher
resolution image has more pixels and is, therefore, sharper and more detailed but
also requires more storage space
• The colour depth of an image refers to the number of bits used to represent each
colour. A higher colour depth means that more colours can be represented, result-
ing in a more realistic image but also requires more storage space
• E.g. an 8-bit colour depth allows for 256 different colours to be represented
(28=256), while a 24-bit colour depth allows for over 16 million different colours to
be represented (224=16,777,216)
• The file size of an image increases as the resolution and colour depth increase. This
is because more pixels and colours require more binary data to represent them
• The quality of an image also increases as the resolution and colour depth increase.
However, it's important to balance the desired quality with the practical limitations
of storage space

Worked example
An image has a resolution of 600 x 400 and a colour depth of 1 byte. Calculate the file size of
the image giving your answer in bytes. Show your working
[2]
• 600 x 400 = 240,000[2]
• 1 mark for the working and 1 mark for the answer
Data Storage and Compression
Data storage
• Data storage is measured in a variety of units, each representing a different size of
storage capacity. The smallest unit of measurement is the bit, which represents a
single binary digit (either 0 or 1)
• A nibble is a group of 4 bits, while a byte is a group of 8 bits
• Kibibyte (KiB), mebibyte (MiB), gibibyte (GiB), tebibyte (TiB), pebibyte (PiB), and
exbibyte (EiB) are all larger units of measurement
• Specifically, 1 KiB is equal to 210 bytes, 1 MiB is equal to 220 bytes, 1 GiB is equal to
230 bytes, 1 TiB is equal to 240 bytes, 1 PiB is equal to 250 bytes, and 1 EiB is equal to
260 bytes

To calculate the file size of an image file:

• Determine the resolution of the image in pixels (width x height)


• Determine the colour depth in bits (e.g. 8 bits for 256 colours)
• Multiply the number of pixels by the colour depth to get the total number of bits
• Divide the total number of bits by 8 to get the file size in bytes
• If necessary, convert to larger units like kibibytes, mebibytes, etc

Calculating image file size walkthrough:


An image measures 100 by 80 pixels and has 128 colours (so this must use 7 bits)
100 x 80 x 7 = 56000 bits ÷ 8 = 7000 bytes ÷ 1024 = 6.84 kibibytes
To calculate the file size of a sound file:
• Determine the sample rate in Hz (e.g. 44,100 Hz)
• Determine the sample resolution in bits (e.g. 16 bits)
• Determine the length of the track in seconds
• Multiply the sample rate by the sample resolution to get the number of bits per sec-
ond
• Multiply the number of bits per second by the length of the track to get the total
number of bits
• Divide the total number of bits by 8 to get the file size in bytes
• If necessary, convert to larger units like kibibytes, mebibytes, etc

Calculating sound file size walkthrough:


A sound clip uses 48KHz sample rate, 24 bit resolution and is 30 seconds long.
48000 x 24 = 1152000 bits per second x 30 = 34560000 bits for the whole clip
34560000 ÷ 8 = 4320000 bytes ÷ 1024 = 4218.75 kibibytes ÷ 1024 = 4.12 mebibytes

Exam Tip
REMEMBER TO ALWAYS USE THE UNITS SPECIFIED IN THE QUESTION WHEN GIVING THE
FINAL
ANSWER.
Compression

Compression is reducing the size of a file. This is done to reduce the amount of storage
space it takes up or to reduce the bandwidth when sending a file. There are 2 types of com-
pression:

• Lossless Compression:
o A compression algorithm is used to reduces the file size without perma-
nently removing any data
o Repeated patterns in the file are identified and indexed
o The data is replaced with the index and positions stored
o The number of times the pattern appears is also stored
o Techniques like run-length encoding (RLE) and Huffman encoding are used
o RLE replaces sequences of repeated characters with a code that represents
the character and the number of times it is repeated
o Huffman encoding replaces frequently used characters with shorter codes
and less frequently used characters with longer codes
• Lossy Compression:
o Lossy compression reduces the file size by permanently removing some
data from the file
o This method is often used for images and audio files where minor details or
data can be removed without significantly impacting the quality
o Techniques like downsampling, reducing resolution or colour depth, and
reducing the sample rate or resolution are used for lossy compression
o The amount of data removed depends on the level of compression selected
and can impact the quality of the final file
• Overall:
o Compression is necessary to reduce the size of large files for storage, trans-
mission, and faster processing
o The choice between lossy and lossless compression methods depends on
the type of file and its intended use
o Lossy compression is generally used for media files where minor data loss is
acceptable while lossless compression is used for text, code, and archival
purposes
Data
Transmission
Types and Methods of Data
Transmission
Data Packets
What are packets?
• Information on the internet is broken down into packets and are created by TCP and
transmitted over the internet.
o Packets are small chunks of information / data.
o TCP stands for Transmission Control Protocol and is used for organising data
transmission over networks.
• Small chunks of data are easier and quicker to route over the internet than big
chunks of data.
o Routing involves finding the most optimal path over a network.
• Data can include anything from text, images, audio, video, animations, etc, or any
combination of these.
What do packets contain?
• Packets are “chunks” of information. This information is called the “payload.
• Packets act like postage letters, each one has:
o A delivery address (destination IP address)
o A return address (source IP address)
o And a message (data payload)
• Packets are split into three parts:
o Packet header
o Payload (the actual data)
o Trailer
• The header contains:
o Source / sender IP address (in case of malicious attacks)
o Destination IP
o Packet number
o Error checker e.g., a checksum or parity bit
• The trailer contains:
o Additional error checks
o End of packet notification

Figure 1: To transmit the message “This is a message :)” over the internet, the TCP might
break the message down into 4 packets.
• Each packet in figure 1 contains a source IP address, destination IP address, payload
(the data) and a packet number. Error checking and end of packet notifications
• Error checking and end of packet notifications have not been included in this
example.
• Individual packet structure depends on the protocol used to create them; variations
exist.
• Error checks make sure that when a packet is received there is minimal or no
corruption of the data.
• Corruption is where the packet data is changed or lost in some way, or data is
gained that originally was not in the packet.
• A parity bit checks that not bits have been flipped from 0 or 1 or vice versa.
• A checksum performs a calculation and compares the result to the checksum value.
• if the values are different then the data has been corrupted
How are packets sent across the internet?
• Sending packets overt the internet is called packet switching and is more efficient
than circuit switching.
• Packet switching involves:
o Routers know which nearby router is closer to the destination device.
o Like normal car traffic, data traffic builds up on the internet. Routers can see
this and decide to send a packet down a different route that avoid traffic.
o Packets from the same message can take different routes from the sender
to the receiver and may arrive in different orders. The receiver’s computer
resembles the message by reordering the packets using the packet numbers.
o Breaking down a file into packets and sending these packets down different
routes over the internet (via routers) from a source to a destination and
reassembling them at the end
o Packet numbers allows for the original message, which has been broken
down into smaller parts, to be re-assembled in the correct order, or
assembled like a jigsaw, once all the packets have been received.
o Routers contain routing tables which keep track of nearby routers like a
map or contracts list.
o If a packet does not reach its destination the receiver can send a resend
request to the sender to resend the packet

Figure 2: Packets take different routes across a network from the source address to reach
the destination address as shown by the green, blue and red routes taken.
• The advantages are:
o Interference and corruption are minimal as individual packets can be resent
if they are lost or damaged.
o The whole file doesn’t need to be resent if corruption occurs, only the
individual packets that were corrupted need to be resent. This saves time
and internet bandwidth.
o Packet switching is quicker than sending a large packet as each packet finds
the quickest way around the network.
o It’s harder to hack an individual’s data as each packet contains minimal data,
and travels through the network separately.
• Here is a table comparing the different transfers.

Disadvantages:
• Packet loss
• Congestion
• Latency is the time taken High latency bad Low latency.
• High bandwidth
• Requires error checking mechanisms.

Worked example.
A local market shop wishes to arrange a delivery of goods from a supplier. Anna, the shop
owner, decides to send an email to request the delivery of the goods at a certain date and
time.
Describe how packet switching is used to send this email and how it can be protected from
corruption.
[8]

• The business email is first broken down into packets which are given a source
address (where it’s come from) and a destination address (where it’s going to) [1]
• Each packet receives a packet number so that the email can be reassembled when it
reaches its destination [1]
• Each packet also receives an error check such as a parity bit. A parity bit checks
whether any bits have been flipped due to corruption [1]
• Each packet is sent over the internet via routers. Routers contain routing tables that
determine the next closest router to the destination [1]
• Packets may take different routes depending on internet traffic and arrive at their
destination in any order [1]
• Packets are checked for errors using the error checks and missing packets can be
requested to be resent [1]
• Once all packets have been received then they can be put together in order using
the packet numbers [1]
• Once assembled the original email can be read by the other business [1]
Exam Tip
FOR HIGH MARKS MAKE SURE YOUR ANSWER IS COHERENT, THAT IS IT FOLLOWS LOGI-
CALLY FROM ONE POINT TO THE NEXT. SOME MARKS DEPEND ON PREVIOUS POINTS YOU
HAVE MADE. EXPLAINING PARITY BITS WITHOUT MENTIONING ERROR CHECKING FIRST
MAY NOT GAIN YOU ADDITIONAL MARKS
Data Transmission
Wired connections
• Wires can be:
o Serial
▪ One bit is sent at a time across a single wire.

Figure 1: A sender sends a stream of bits in sequence, one after the one across a single
wire.
o Parallel
▪ Multiple bits are sent at a time across serval wires.
▪ Transmission is asynchronous as some bits may arrive quicker than
others.
▪ This is known as skewing or skewed data.
• Asynchronous transmission means data does not always
arrive at the same time.

Figure 2: A sender sends a stream of bits in sequence, one after the other across multiple
wires at the same time.
o Simplex
▪ Simplex transmissions are unidirectional and travel in only one
direction.
o Half – duplex
▪ Half – duplex transmission is bidirectional i.e., can travel in both
directions, but not simultaneously!
o Full – duplex
▪ Full – duplex transmissions are bidirectional but can transmit signals
in both directions at the same time.
• Wires can be combinations of serial, parallel, simplex, half – duplex and full – duplex.
Type: Simplex Half - Duplex Full – Duplex
Serial Serial - simplex Serial - Half – duplex Serial – Full – Duplex
Parallel Parallel - simplex Parallel - Parallel – Full - duplex
Figure 3: Wire types can be combined between serial/parallel and simplex/half-duplex/full
duplex.
o Serial – simplex
▪ Data is transmitted one bit at a time in a single direction on one
wire.
o Serial – Half – duplex
▪ Data can be transmitted in both directions on a single wire but only
one bit at a time can be transmitted at only one direction at a time
b.
o Serial – full – Duplex
▪ Data can be transmitted in both directions at the same time on a
single wire one bit at a time.
o Parallel – Simplex
▪ Multiple wires transmit one bit at a time in one direction.
o Parallel – Half – Duplex
▪ Multiple wires send multiple bits of data in both directions but only
one direction at a time.
o Parallel – Full – Duplex
▪ Multiple wires send multiple bits of data in both directions at the
same time
• Table demonstrating the advantages and disadvantages of each method:
Type: Advantages Disadvantages
Serial • The data will arrive in the • Data transmission is slow,
order it is sent. especially over long distance as
• It is less likely to have errors. only small quantities of data
• Serial transmission is cheap can be transmitted at a time.
over short and long distances • Serial transmission is expensive
as the cost of wire is over very long distances as the
inexpensive cost of wire dramatically
increases
Parallel • Parallel transmission is fast as • Parallel transmission s
large quantities of data can expensive over distances as
be transmitted at any one multiple wire need to be
time purchased. Transmission is very
expensive over long distances
as the cost of wires
dramatically.
• Delays can be caused if data
arrives asynchronously as the
receiver must wait for all the
bits before accepting new data.
This is especially true over
longer distances.
• Buffers may be used to store
data temporarily while waiting
for all bits to arrive
Simplex • Simplex wires are cheap • Data transmissions is slow as data
as one wire is used still travels one bit at a time in only
one direction at a time.
• Simplex transmission requires two
sets of wires for bidirectional
transmission meaning it can
become expensive`
Half – Duplex • Half- duplex transmission is • Transmission is still slow as
cheaper than simplex data travel one bit at a time in
only one direction at a time
Full - Duplex • Full – Duplex transmission is • Full duplex is expensive as the
faster as data can travel in wire technology to transmit in
both directions both directions is more difficult
simultaneously. The receiver to implement
does not have to wait for the
sender to stop before they
can start transmitting their
data
Example scenarios of using each method
• Serial
o Connecting an external hard drive to a computer
o Transmitting data over a telephone line
• Parallel
o Transmitting data from a computer to a printer using a multi-wire connector
• Simplex
o Transmitting data from a computer to a printer. The printer doesn’t need to
send data back to the computer.
▪ Modern versions of devices such as printers may send
acknowledgement signals to confirm they have received the data.
This may require half – duplex rather than simple connections.
• Half – duplex
o Phone conversations where only one person needs to speak at a time.
o A walkie- talkie is a two-way radio with a push to speak button. The receiver
is turned off while the transmitter is on. #This prevents you from hearing the
other Pearson while you speak
• Full – duplex
o Broadband connections to the internet. Data must be sent and received at
the same time. Accessing information on the internet is known as
downloading information. Putting information not the internet for others to
access is known as uploading.
o Phone conversations where both people can talk and be heard at the same
time allowing them to interrupt each other.

Worked example.
A company has a website that is stored on a web server

The company uses parallel half-duplex data transmission to transmit the data for the new
videos to the web server.

Explain why parallel half-duplex data transmission the most appropriate method is.
[6]

• Parallel would allow for the fastest transmission [1]


• as large amounts of data [1]
• can be uploaded and downloaded [1]
• but this does not have to be at the same time [1]
• Data is not required to travel a long distance [1]
• Therefore, skewing is not a problem [1]

Exam Tip
ANY FOUR OF THESE POINTS QUALIFIES AS A FULL ANSWER HOWEVER MAKE SURE YOUR
ANSWER IS COHESIVE. SAYING “PARALLEL WOULD ALLOW FOR THE FASTEST TRANSMIS-
SION BUT THIS DOES NOT HAVE TO BE AT THE SAME TIME” WOULD QUALIFY AS ONE
MARK AS ONLY THE FIRST PART MAKES SENSE AND FOLLOWS LOGICALLY
USB

Images of USB connectors


• The Universal serial Bus (USB) is an asynchronous and serial method of transmitting
data between devices and has become an industry standard.
• Many devices use USB such as keyboards, mice, video cameras, printers, portable
media players, mobile phones, disk drives, network adapters, etc.
• Different USB connectors exist for different devices such as:
o USB-A (flash drives, mice, keyboards, external HDD, etc)
o USB-B (printers, scanners, optical drivers, floppy drives, etc)
o USB-C
• USB-C is becoming the new standard of USB due to its small size and speed.
• When a device is connected to a USB port the computer is:
o Automatically detects that the device has been connected.
o Automatically recognised and that appropriate device driver is loader so
that the device can communicate with the computer.
▪ If the device is new, the computer will look for a matching device
driver. If one cannot be found, then the user just downloads and
install an appropriate driver manual.
Advantages and disadvantages
Advantages Disadvantages
Devices are automatically detected, and driv- The maximum cable length is roughly 5 meters
ers are automatically loaded for communica- meaning it cannot be used over long distances,
tion. This simplifies the data transmission pro- limiting its use
cess for the user
Cable connectors fit in only one way. This pre- Older version of USB has limited transmission
vents incorrect connections and ensures com- rates for example USB 2.0 has 480Mbps
patible data transmission
AS USB usage is standardised, there is a lot of Very old USK standards may not supported
support available online and from retailers soon (USB 1.1, USB 2.0, etc)
Several different data transmission rates are
supported. The newest transmission rate as of
2022 is USB4 2.0 with 80 Gbps (81,920 Mbps,
170x faster than USB 2.0)
Newer USB standards are backwards compati-
ble with older USB standards

Worked example.
Julia uses a USB connection to transfer data onto her USB flash memory drive.
(i) One benefit of using a USB connection is that it is a universal connection. State two other
benefits of using a USB connection.
[2]
• Any two of:
o It cannot be inserted incorrectly [1]
o Supports different transmission speeds [1]
o High speed transmission [1]
o Automatically detected [1]
o Powers the device for data transfer [1]
(ii) Identify the type of data transmission used in a USB connection.
[1]
• Serial [1]
Methods of Error Detection
Error Checking
• when data has been received it could be subject to errors and Corruption
Why check for errors?
• Computer expect data in certain formats.
o A format is a way of arranging the data so that it can be easily understood
by people and by computers.
o People agree to certain formats so that systems work more efficiently and
there is little chance of misunderstanding each other.
• An example of a format is date and time. Data and time can have multiple formats
such as:
o 3/04/14 (DD/MM/YY)
o 12/31/2020 (MM/DD/YYYY)
o Jul-04-16 (MMM/DD/YY)
• Computers usually perform processes and calculations on data. If the data is not as
expected, things can go wrong. For example, if a receiver expected to receive a date
in format DD/MM/YY as 03/04/17 but received 04/03/17, did the sender mean 3rd
April 2017 or 4th March 2017?
• An error or corruption occurs when data received is not as expected and therefore
is difficult or impossible to process.
How is data represented?
• All data is represented in binary as 1’s (high voltage) and 0’s (low voltage)
o For example, the number 67 is represented as 01000011.
o An error could cause one of the bits to flip from 1 to 0 or vice versa.
o If the sixth most significant bit is flipped, 01000011 -> 01000111, 67 be-
comes 71.
o The number 67 in ASCII represents the uppercase letter ‘C’ whereas the
number 71 represents ‘G’.
o By flipping a single bit, the meaning of the binary string has changed.
o If a book was transmitted over a network, assuming many bits were flipped,
it would likely be difficult to read the original text.
How can errors cause problems?
• Some errors are small and trivial such as a single swapped letter in a large text.
• Other errors, in data such as postage addresses, aerospace coordinates or bank
transfers, can be difficult to rectify or be disastrous.
• Any job or task that relies on a computer to perform highly sensitive or secure pro-
cesses must have methods of error checking and correction.
How do errors occur?
• Errors can occur using wired or wireless technology due to interference.
• Examples of interference include wire degradation or electrical fields changing the
signal.
• Results of interference include:
o Data loss - data is lost in transmission.
o Data gain - additional data is received.
o Data change - some bits have been changed or flipped.
• Wireless technology uses radio signals or other electromagnetic signals to transmit
data.
o These signals can be blocked by physical barriers such as buildings, walls,
cars or other objects.
o Interference can be caused by bad weather such as rain or clouds, or by
other wireless signals or electromagnetic radiation.
• Wired technology carries more chance of causing an error as physical components
can be damaged, degrade or receive interference from outside signals.
o Data loss can also occur from interruptions to data transmission such as
a blocked signal or if the transmission is intermittent.
Worked example.
Alex receives an email over a wireless connection from a work colleague containing an im-
portant document.
Identify what interference Alex could experience when sending this email and identify the
outcomes of interference. Further explain why Alex should check to make sure the docu-
ment contains no errors.
[4]
• Weather conditions or physical barriers such as building can affect signals, for exam-
ple bits could be flipped in the document making it hard to understand the original
meaning [1]
• Alex should be aware that interference can cause wirelessly received data to contain
errors or corruption [1]
• Data could be lost; additional data could be gained, or data could be changed [1]
• As Alex received an important work document, they need to check for errors so that
their work is unaffected, and they do not receive incorrect information [1]
Error Detection Methods
Parity check
• The parity checking protocol determines whether bits in a transmission have been
corrupted.
• Every byte transmitted has one of its bits allocated as a parity bit.
• The sender and receiver must agree before transmission whether they are going to
be using even or odd parity.
• If odd parity is used then there must be an odd number of 1’s in the byte, including
the parity bit.
• If even parity is used then there must be an even number of 1’s in the byte,
including the parity bit.
• The value of the parity bits is determined by counting the number of 1’s in the byte,
including the parity bit.
• If the number of 1’s does not match the agreed parity, then an error has occurred.
• Parity checks only check that an error has occurred, they do not reveal where the
error(s) occurred.
Even parity
• Below is an arbitrary binary string.
EVEN Byte
Parity bit
0 1 0 1 1 0 1 1
• If an even parity bit is used then all bits in the byte, including the parity bit,
must add up to an even number.
o There are four 1’s in the byte. This means the parity bit must be 0 otherwise
the whole byte, including the parity bit, would add up to five which is an odd
number.
Odd parity
• below is an arbitrary string.
ODD byte
Parity
bit
1 1 0 1 1 0 1 0
• if an odd parity bit is used then all bits in the byte, including the parity bit, must add
up to an odd number.
o there are four 1’s in the byte. This means the parity bit must be a 1
otherwise the whole byte, including the parity bit, would add up to four
which is an even number.
• the table below shows several examples of the agreed parity between a sender and
receiver and the parity bit used for each byte.
Exam- Agreed Parity Main bit string Total
ple # parity bit num-
ber of
1’s
# O 0 1 1 0 1 0 1 1 5
1 D
D
# E 1 0 0 0 1 0 0 0 2
2 V
E
N
# E 1 0 1 0 1 1 1 1 6
3 v
e
n
# O 1 0 1 1 1 0 0 1 5
4 D
D
# O 1 1 0 1 0 1 0 1 5
5 D
D
# E 0 1 0 0 1 1 1 0 4
6 V
E
N

• Example #1: The agreed parity is odd but the total number of 1’s is even (6). An er-
ror has occurred somewhere.
• Example #2: The agreed parity is even and the total number of 1’s is even (2). No er-
ror has occurred here.
• Example #3: The agreed parity is even but the total number of 1’s is odd (7). An er-
ror has occurred somewhere.
• Parity checks are quick and easy to implement but fail to detect bit swaps that
cause the parity to remain the same.
• Below is an arbitrary binary string. The agreed parity is odd and the total number of
1’s is five (odd)
Agreed Parity bit Total number of 1’s Er-
Parity bit ror
O 1 0 1 0 1 0 1 1 5N
D o
D -
er
ro
r
Agreed Parity Total number of 1’s Er-
Parity bit ror
O 1 1 0 0 0 0 0 1 3N
D o
D -
Er
ro
r

Parity bytes and parity blocks


• Parity checks do not pinpoint errors in data, only that an error has occurred.
• Parity blocks and parity bytes can be used to check an error has occurred and where
the error is located.
o A parity block consists of a block of data with the number of 1’s totalled
horizontally and vertically.
o A parity byte is also sent with the data which contains the parity bits from
the vertical parity calculation.
• Below is a parity block with a parity byte at the bottom and a parity bit column in
the second column.
ODD BIT BIT BIT BIT BIT BIT BIT BIT
1 2 3 4 5 6 7 8
Byte 0 1 1 0 1 0 1 1
1
Byte 0 0 0 0 1 0 0 0
2
Byte 1 0 1 0 1 1 1 1
3
Byte 1 0 1 1 1 0 0 1
4
Byte 1 1 0 1 0 1 0 1
5
Byte 1 1 0 0 1 1 1 0
6
Byte 0 0 1 1 1 1 1 0
7
Byte 0 1 0 1 1 0 0 0
8
Par- 0 1 1 1 1 1 1 1
ity
Byte

• The above table uses odd parity.


• Each byte row calculates the horizontal parity as a parity bit as normal.
• Each bit column calculates the vertical parity for each row. This is the parity
byte. It is calculated before transmission and sent with the parity block.
• Each parity bit tracks if a flip error occurred in a byte while the parity
byte calculates if an error occurred in a bit column.
• By cross referencing both horizontal and vertical parity values the error can be
pinpointed
• In the above example the byte 3 / bit 5 cell is the error and should be a 0
instead
• The error could be fixed automatically, or a retransmission request could be
sent to the sender.

Exam Tip
REMEMBER, PARITY BITS ONLY TRACK IF AN ERROR OCCURRED, NOT WHERE IT IS LO-
CATED. THE PARITY BIT ITSELF MIGHT BE THE ERROR. PARITY BYTES ARE CALCULATED
BEFORE TRANSMISSION SO ACT AS A CHECK ON THE PARITY BITS THEMSELVES.
Checksums
• Checksums determine if data has been corrupted but do not reveal where.
• Data is sent in blocks and an additional checksum value is added at the end of the
block.
• Checksums are custom user-created algorithms that perform mathematical calcula-
tions on data.
• An example of a custom checksum algorithm in computer science is:
o A checksum byte is defined as a value between 1 and 255 which is stored in
8 bits. 8 bits are collectively known as a byte.
o If the sum of all the bytes of a transmitted block of data is <= 255 then
the checksum value is the sum of all the bytes
o If the sum of all the bytes is > 255 then the checksum is calculated with an
algorithm:
▪ X = sum of all the bytes
▪ Y = X / 256
▪ Round down Y to nearest whole number
▪ Z = Y * 256
▪ Checksum = X – Z

Custom Checksum Walkthrough


o If X = 1496
▪ Y = 1496 / 256 = 5.84
▪ Rounded down Y = 5
▪ Z = 5 * 256 = 1280
▪ Checksum = 1496 - 1280 = 216
o The checksum value in this example would be 216.
• When a block of data is to be transmitted, the checksum is first calculated and then
transmitted with the rest of the data.
• When the data is received the checksum value is calculated based on the received
data and compared to the checksum value received. If they are the same, then the
data does not contain any errors.
• If an error does occur, then a resend request is sent and the data is retransmitted.

Exam Tip

IT IS WORTH NOTING THAT THE CHECKSUM VALUE ITSELF MAY BECOME CORRUPTED OR
CONTAIN ERRORS! CHECKSUMS MAY BE SENT MULTIPLE TIMES AND TALLIED. THE MOST
COMMON CHECKSUM IS THEN ASSUMED TO BE THE CORRECT ONE

Worked example.
(b) Describe the process a checksum algorithm uses to determine if an error has occurred
[5]
• Before data is transmitted a checksum value is calculated [1]
• The checksum value is transmitted with the data [1]
• The receiver calculates the checksum value using the received data [1]
• The calculated checksum is compared to the transmitted checksum [1]
• If they are the same, then there is no error otherwise an error has occurred [1]
Echo check
• Echo checks involve transmitting the received data back to the sender.
The sender then checks the data to see if any errors occurred during transmission.
• This method isn’t reliable as an error could have occurred when the sender trans-
mits the data or when the receiver transmits the data. Neither will know when the
error occurred.
• If an error does occur the sender will retransmit the data

Worked example.
Four 7-bit binary values are transmitted from one computer to another. A parity bit is added
to each binary value creating 8-bit binary values. All the binary values are transmitted and
received correctly.
(a) Identify whether each 8-bit binary value has been sent using odd or even parity by
writing odd or even in the type of parity column.
8 – bit binary value Type of parity
0110 0100
1001 0001
0000 0011
1011 0010

[4]
•Odd [1]
•Odd [1]
•Even [1]
•Even [1]
(b) An error may not be detected when using a parity check. Identify why an error may not
be detected.
[1]
• Any one from:
o there is a transposition of bits [1]
o it does not check the order of the bits (just the sum of 1s/0s) [1]
o even number of bits change [1]
o incorrect bits still add up to correct parity [1]
Exam Tip
DO NOT ADD YOUR OWN PARITY BIT OF 1 OR 0 UNLESS SPECIFICALLY ASKED TO DO SO
Check Digits
• Check Digits to determine if data has been corrupted but do not reveal where.
• Data is sent in blocks and an additional check digit value is added at the end of the
block.
• Check Digits are custom user-created algorithms that perform mathematical calcu-
lations on data.
• An example of a check digit is the ISBN value on books:
o Each book has a unique ISBN number that identifies the book.
o A standard ISBN number may be ten digits, for example, 965-448-765-9
o The check digit value is the final digit (9 in this example). This number
is chosen specifically so that when the algorithm is completed the result is
a whole number (an integer) with no remainder parts.
o A check digit algorithm is performed on the ISBN number. If the result is a
whole number, then the ISBN is valid.
ISBN Check Digit Walkthrough
▪ To calculate an ISBN check digit the following algorithm is per-
formed on 965-448-765-9:
▪ Multiply each ISBN digit by 1 to 10 and add them all up:
▪ 9x1 + 6x2 + 5x3 + 4x4 + 4x5 + 8x6 + 7x7 + 6x8 + 5x9 +
9x10 = 352
▪ Take the total number and divide it by 11: 352/11 = 32. 32 is
a whole number with no remainder so the ISBN is valid

• Another example of a check digit is barcodes on purchasable items:


o Barcodes consist of black and white lines which can be scanned using bar-
code scanners. Barcode scanners shine a laser on the black and white lines
which reflect light into the scanner. The scanner reads the distance be-
tween these lines as numbers and can identify the item.
o Barcodes also use a set of digits to uniquely identify each item. The number
of digits varies from code to code. An example would be 9780201379624.
o The final digit on a barcode is usually the check digit. Like an ISBN this can
be used to validate and authenticate an item
Barcode Check Digit Walkthrough
o To calculate a barcode check digit, we can perform the following example
algorithm on 9780201379624 (the final digit is the check digit):
▪ Multiply each digit by 1 or 3, alternating between these two values
and add them all up.
▪ 9x1 + 7x3 + 8x1 + 0x3 + 2x1 + 0x3 + 1x1 + 3x3 + 7x1 + 9x3 +
6x1 + 2x3 = 96

▪ The check digit (the final digit) should be the difference between the
sum and the closest multiple of 10 that is larger or equal to the sum.
▪ 96 rounded to the nearest 10 = 100
▪ 100-96 = 4
▪ The check digit is therefore 4 which matches our original
barcode number

• An example of a custom check digit algorithm in computer science is:


o A check digit byte is defined as a value between 1 and 255 which is stored in
8 bits. 8 bits are collectively known as a byte.
o If the sum of all the bytes of a transmitted block of data is <= 255 then
the check digit value is the sum of all the bytes
o If the sum of all the bytes is > 255 then the check digit is calculated with an
algorithm:
▪ X = sum of all the bytes
▪ Y = X / 256
▪ Round down Y to a nearest whole number
▪ Z = Y * 256
▪ Check digit = X – Z

Custom Check Digit Walkthrough


o If X = 1496
▪ Y = 1496 / 256 = 5.84
▪ Rounded down Y = 5
▪ Z = 5 * 256 = 1280
▪ Check digit = 1496 - 1280 = 216
o The check digit value in this example would be 216

• When a block of data is to be transmitted, the check digit is first calculated and then
transmitted with the rest of the data.
• When the data is received the check digit value is calculated based on the received
data and compared to the check digit value received. If they are the same, then the
data does not contain any errors.
• If an error does occur, then a resend request is sent and the data is retransmitted.
Worked example.
Check digit algorithms are used to determine whether an error has occurred in transmitted
data.

a)
State the names of two examples of a check digit algorithm.
[2]
• ISBN [1]
• Barcode [1]
Automatic Repeat Request (ARQ)
• When the receiver receives transmitted data, it must check for the presence of any
errors. Errors can usually be detected but not always pinpointed.
• An Automatic Repeat Request is a protocol that notifies the sender that an error
has occurred, and that the data received is incorrect. It works as follows:
o If an error is detected the receiver sends a negative acknowledge-
ment transmission to indicate the data is corrupted
o If no error is detected the receiver sends a positive acknowledge-
ment transmission meaning the data is correct
o If the receiver does not send any acknowledgement transmission, then
the sender waits for a certain time known as a time-out before automati-
cally resending the data.
o This process is repeated until all data has been received and acknowl-
edged.
Encryption
Encryption
• Many threats exist to system and network security. Examples include:
o Malware
o Viruses
o Spyware
o Hackers
o Denial of service attacks
o Social engineering
o SQL injection
• Hackers are people who try to gain unlawful or unauthorised access to com-
puters, networks and data by writing programs.
• They look for weaknesses in the system and use them to gain access.
• Hackers have various motives such as financial gain, a challenge or pro-
tests etc.
• Hackers sometimes target data to steal and use it or block people from using
the data by creating programs called ransomware.
• Hackers may also use packet sniffer to intercept and read data transmitted
across the internet or a network.
• Hackers will often want to use people’s information and therefore it is bene-
ficial to encrypt your data.

What is encryption?
• Encryption involves encoding data into a form that is meaningless using an
algorithm.
o An example could be turning the phrase “Computer Science” into
“YekLKEZizFuFjHNCjHj3Md7qyTiGxLNNwPVFZtJU74I=”
• Once encrypted, data can be decrypted which turns the encrypted data into
data that can be understood again.
• Encryption doesn’t prevent hackers from hacking but makes the data hard if
not impossible to understand unless they have matching decryption tools.
• There are two types of encryptions: symmetric encryption and asymmetric
encryption.
Exam Tip
ENCRYPTION DOESN'T STOP THE DATA FROM BEING STOLEN. IT JUST MAKES IT
VERY DIFFICULT FOR HACKERS TO UNDERSTAND THE DATA
Symmetric and asymmetric encryption
• Encryption relies on the use of a key. A key is a binary string of a certain
length that when applied to an encryption algorithm can encrypt plaintext in-
formation and decrypt ciphertext.
o Plaintext is the name for data before it is encrypted.
o Ciphertext is the name for data after it is encrypted.
• Keys can vary in size and act like passwords, enabling people to protect in-
formation. A single incorrect digit in the key means the data cannot be de-
crypted correctly. Strong modern keys can be up to or over 1000 bits long!
Symmetric encryption
• In symmetric encryption both parties are given an identical secret key which
can be used to encrypt or decrypt information
• Key distribution problem: If a hacker gains access to the key, then they can
decrypt intercepted information.
• Methods exist to send the secret key to the receiver without sending it elec-
tronically:
o Both parties could verbally share the key in person
o Both parties may use standard postage mail to share the key (some
businesses and banks may do this to ensure someone's identity and
authenticity)
o An algorithm may be used to calculate the key by sharing secret non-
key information. An example is shown below.
Symmetric Encryption Walkthrough
▪ Both parties A and B choose a number, for example A = 3, B =
2
▪ Both parties enter their own respective numbers into the fol-
lowing equations: 7^A MOD 11 or 7^B MOD 11. ^ is another
way of writing “to the power of”.
▪ 7^3 MOD 11 = 2, 7^2 MOD 11 = 5
▪ Both parties swap their respective answers. A receives 5 and
B receives 2. These answers replace the initial 7 number, and
the calculations are performed again.
▪ Both parties enter their new number into the following equa-
tions: 5^3 MOD 11 or 2^2 MOD 11
▪ 5^3 MOD 11 = 4, 2^2 MOD 11 = 4
▪ The answer should match for both parties and this becomes
the encryption and decryption key value.
• Once the key is generated, it can be applied to the plaintext in the algorithm
that then produces the ciphertext which is sent to the receiver.
• The receiver gets a copy of the ciphertext and the key and applies the en-
cryption algorithm. The algorithm then produces the original plaintext for the
receiver.
Asymmetric encryption
• In asymmetric encryption also known as public key encryption, two keys are
used:
o Public key: a key known to everyone.
o Private key: a key known only to the receiver.
• Both keys are needed to encrypt and decrypt information
• Asymmetric encryption works as follows:
o Person A uses a public key to encrypt their message.
o Person A sends their message over the network or internet.
o Person B decrypts the message using their secret private key.
• Asymmetric encryption works such that only one private key can be used to
decrypt the message and it is not sent over the internet like a symmetric key.
• Keys can be very large, for example over 1000 bits. To get the correct key a
hacker would have to calculate almost every possible combination. To illus-
trate, a key with only 100 bits would generate
1,267,650,600,228,229,401,496,703,205,376 different combinations.

How are encryption keys created?

• Encryption keys can be created manually, randomly or via an algorithm.


• Strong encryption keys are created using a hashing algorithm.
• A hashing algorithm is a non-reversible mathematical algorithm that con-
verts a given input into an output. Once the output has been generated it
is unable to be converted back to the original input
• Encryption keys are created by supplying a message or key to the hashing
algorithm which turns it into a string of characters usually shown in hexadec-
imal.
• SHA-2 is an example of a hashing algorithm that creates hashed keys of 244-,
256-, 384- or 512-bit length.
o If the text string “Computer Science” is run through the SHA-2 algo-
rithm, it would return a 512-bit key in hexadecimal as:
o “B6e175f5fc647b1a9ce17019594ce55b58e8fd03e3c584ee384121c8b
4c7753d”
• The hashed encryption key can then be sent symmetrically or kept secret as
part of an asymmetric private key. Both sender and receiver need a copy of
the key to decrypt in encryption. regardless of using symmetric or asymmet-
ric encryption
Why use hashed encryption keys?

• In symmetric encryption, the key must be sent with the message to the re-
ceiver. If a hacker intercepts the key, they can read the message.
• In asymmetric encryption, the public key is available to everyone and
would not be useful to a hacker. The hacker must guess the private key to
read the message.
• Hashing algorithms are many-to-one. This means that many input values,
messages or keys can produce the same hash key output.
• A hashed encryption key means the hacker must first unhash the key before
it is useful.
• As hashing algorithms are non-reversible this is extremely difficult.
• With SHA-2 for example, a hacker who wants to find the symmetric or asym-
metric private key must calculate over 1.3x10^154 combinations; that is 13
with 153 0’s after it. With the computing power available today, this is virtu-
ally if not actually impossible.
Worked example.
Complete the sentences about symmetric encryption. Use the terms from the list.
Some of the terms in the list will not be used. You should only use a term once.
a
l c c d
p
g i o e
k l
o p p l
e a
ri h i e
y i
t e e t
n
h r d e
m
u u
n n
p st
p s d r
r a
u t e e
i n
b o r a
v d
l l s d
a a
i e t a
t r
c n o b
e d
o l
d e
The data before encryption is known as ______ text. To scramble the data, an en-
cryption ______, which is a type of ______, is used. The data after encryption is
known as ______ text. Encryption prevents the data from being ______ by a hacker.
[5]
One mark for each correct term in the correct place in the following order:
• plain [1]
• algorithm/key [1]
• key/algorithm [1]
• cipher [1]
• Understood [1]
Hardware
Computer Architecture
The CPU & Microprocessor

What is the role of the central processing unit (CPU) in a computer?

• A computer system consists of hardware and software


• The main hardware components of a computer system are input devices, the
central processing unit, primary memory, secondary storage and output de-
vices
• Examples of input devices - keyboard, mouse, game controller, sensors, mi-
crophone and webcam
• Examples of output devices - monitor, phone screen, speakers, printer, and
motors
• Data and commands are inputted by the user using an input device, the cen-
tral processing unit (CPU) processes data by executing instructions and the
results are outputted to an output device

A diagram showing the input, process, output sequence followed by com-


puter systems
• Below is an example of data being inputted, processed and the results being
outputted
Step Example
Input • A keyboard is used to input a number
process • If the instruction being executed is ADD, the inputted value is
added to an existing value
Output • The result of the calculation is outputted to the user via the
monitor
What is a microprocessor?
• A microprocessor is a type of integrated circuit on a single chip
• An integrated circuit is a small electronic circuit made up of transistors, ca-
pacitors, resistors and other electronic components
• The integrated circuit contains a central processor designed to perform arith-
metic and logic operations, which include adding, subtracting, transferring
numbers from one memory location to another, and comparing two numbers
• The single chip also contains input/output interfaces, and memory
• Microprocessors are a compact way of processing data and can be used in a
wide range of electronic devices, including general-purpose computer sys-
tem and Embedded system
Worked example
What is the purpose of a microprocessor?
A It is the brain of the computer
B It processes data
C It executes instructions
D It is where data is stored permanently
• B or C [1]
o The microprocessor is sometimes described as the brain of the com-
puter system but this is not an acceptable exam answer. The purpose
of a microprocessor is to process data and execute instructions
Von Neumann Architecture
The components in a CPU, in a computer that has a Von Neumann architecture
• John Von Neumann developed the concept of the stored program com-
puter in the 1940s

• The Von Neumann computer architecture which most modern day comput-
ers use, is based upon this concept
o The key feature of the stored program concept, and Von Neumann ar-
chitecture, is data and instructions are stored in the same memory
( RAM ) as binary
o Another feature of Von Neumann architecture is a central processing
unit (CPU) fetches instructions from memory and executes them one
at a time (serially)
o The CPU then stores the results back into memory
Components of the Central Processing Unit

A diagram showing the main components of the CPU


• The main purpose of the CPU is to execute instructions and process data
• The CPU has two main components - the Control Unit (CU) and the Arithme-
tic Logic Unit ALU)
o The Control Unit controls the flow of data around the CPU
o The Control Unit also sends control signals to the different compo-
nents instructing them what to do e.g. read, write, add, subtract
o The Control Unit decodes instructions (into an opcode and operand )
o The Control Unit controls the timings of operations (the clock speed)
o The Arithmetic Logic Unit(ALU) performs the calculations required to
execute the instructions, these include ADD and SUBTRACT
o The ALU also carries out logical operations such as COMPARE
o The ALU has a built-in register where it stores interim results of calcu-
lations
o After calculations, the ALU sends data to the MDR
• The CPU also contains a number of registers which are small memory loca-
tions within the CPU, which temporarily store data needed to execute an in-
struction
• Special purpose registers have specific roles to play in the execution of an in-
struction

Special purpose Definition


register
Program counter • Stores the address of the next instruction to be
(PC) fetched from memory
Memory Address • stores the address of the instruction or data to
Register (MAR) be fetched from or written to memory
Memory Data • stores the data that has been fetched from
Register (MDR) memory or being written to memory
• Data from MDR is sent to ALU to be executed
Current Instruc- • stores the instruction the CPU is currently
tion decoding or executing
Register
Accumulator • Temporarily stores the results of the
calculations performed by the arithmetic and
logic unit
ALU • Carries out all mathematical operations such as
addition and comparison
Control unit • Controls flow of data send control signals
decodes instructions, control timing of
operations
IAS • Where data and instructions are being held

Exam Tip
IF ASKED TO DESCRIBE THE PURPOSE OF THE PC, THE MAR OR THE MDR MAKE
SURE YOU EXPLAIN HOW THE DATA IS BEING FETCHED OR WRITTEN TO MEMORY.
Worked example
What are the characteristics of Von Neumann architecture?
[2]
Any 2 from:
• Both data and instructions are stored in the same memory unit [1]
• Single Arithmetic and Logic Unit [1]
• Single Control Unit [1]
• Uses the FDE cycle to execute instructions serially [1]
Buses
• Components within the CPU and wider computer system are connected by
buses. These are wires down which electronic signals and data travel. The dif-
ferent buses are collectively called the system bus
• The system bus is made up of three different buses - the data bus, the con-
trol bus and the address bus
o The data bus transmits data from the CPU to memory or input/output
controllers. It is bidirectional which means data can travel in both di-
rections
o The address bus transfers addresses from the CPU to memory. It
is unidirectional which mean addresses only go from the CPU to
memory
o The control bus transfers control signals from the control unit to
other components in the computer system such as memory or in-
put/output controllers. The control bus is bidirectional

A diagram showing how the different buses connect the components in a computer
system

Worked example
Which bus is unidirectional?
[1]
A Address bus

B Data bus

C Control bus

D System bus

A [1]
The Fetch, Decode, Execute cycle
• The Central Processing Unit (CPU) executes instructions by performing the
Fetch Decode Execute cycle
• Each core in the CPU is set out to carry out the fetch-decode execute cycle
o The CPU fetches an instruction from memory
o The instruction is then decoded ( by the Control Unit) into an op-
code and an operand
o The instruction is executed and the whole cycle is repeated with the
next instruction in the process

A diagram depicting the Fetch Decode Execute cycle


Step Explanation
fetch • The PC stores address for the next instruction
• The memory address of the instruction to be fetched is
stored in the Memory Address Register and is sent down
the address bus.
• The data/instruction at the memory address is transferred
back to the CPU, via the data bus, where it is stored in
the Memory Data Register
• The instruction is copied into the Current Instruction
Register and the Program Counter increments
de- • The instruction in the Current Instruction Register is
code decoded, by the Control unit , into an opcode and
an operand
exe- • The instruction is executed by the Arithmetic Logic
cute Unit and the opcode is performed upon the operand.
• The result is stored in the accumulator or written to a
memory location within memory
Clock • Affects the rate at which the FDE cycle occurs
cycle
Worked example
Explain how an instruction is fetched using Von Neumann architecture
[6]
• The Program Counter (PC) holds address/location of the next instruction to
be fetched [1]
• The address held in PC is sent to Memory Address Register (MAR) [1]
• The memory address is sent using address bus [1]
• The Program Counter is incremented [1]
• The instruction is sent from the address in memory to the Memory Data Reg-
ister (MDR) [1]
• The instruction is transferred using the data bus [1]
• The instruction is sent to Current Instruction register (CIR) [1]

Exam Tip
• Make sure you read the question carefully and look at the numbers of marks
allocated to judge the level of detail required. Often questions on the fetch-
decode-execute cycle only require you to describe the steps rather than ex-
plain how the registers and buses are used during each step (as shown in the
table above)
CPU Performance
• Central Processing Units can have multiple cores
o A dual-core processor has two cores
o A quad-core processor has four cores
o Each core runs separate fetch, decode, execute cycles, inde-
pendently from one another and at the same time (simultaneously)
meaning parallel processing can take place
o Multiple cores enables multitasking (running more than one program
at the same time)
o Some programs cannot be split between cores
o The more cores a computer has the more instructions that can be ex-
ecuted per second resulting in better performance
• Each core has a clock speed
o The clock speed is how many instructions the core can execute each
second
o The clock speed is measured in Hertz
o Modern cores can execute billions of instructions per second
o A gigahertz (GHz) is a billion instructions per second
o A megahertz (MHz) is a million instructions per second
o A CPU core with a clock speed of 3.4GHz can execute 3.4 billion in-
structions per second
• Cache is a small amount of memory situated within or close to the CPU with
very fast read/write speeds
o It is used for storing frequently used instructions/data, recently used
instructions, and instructions that are to be fetched and executed
next in a process.
o The impact of increasing the amount of cache is that more data can
be stored there and accessed faster than if it was in RAM …which im-
proves the performance of the CPU.
• Double the number of cores does not necessarily mean double the number of
instructions executed a second. The cores might have different clock speeds
and cache sizes

Worked example
One computer has a single core processor and the other has a dual core processor.
Explain why having a dual core processor might improve the performance of the
computer
[2]
Any 2 from:
• The computer with the dual core processor has two cores/double the
amount of cores [1]
• Parallel processing can take place [1]
• Each core can execute a separate instruction at the same time [1]
• Each core can process instructions independently of each other [1]
Exam Tip
• There are three key factors that affect CPU performance - the number of
cores in your CPU, the cache size and clock speed. You need to able to iden-
tify these factors and explain how they affect the computer’s performance.

Instruction Sets
• An instruction set is a list of all the commands that can be processed by a
CPU
• Each command has a unique binary code
• The table below shows an example instruction set. Each instruction has
a mnemonic that indicates what the instruction does alongside a correspond-
ing binary code

Instruction Set

ADD 10100001

SUB (subtract) 00100010

LDA (load) 10111111

STR (store) 01100000

BRA (branch) 01011010


• After an instruction is decoded into an opcode and an operand, the CPU finds
the opcode in the processor’s instruction set. It then knows what operation
to perform when executing the instruction

Worked example
Using the instruction set in the table above what would be the operation if the in-
struction was 00100010 00000010?
[1]
Either of:
• The operation would be SUB [1]
• If the operand was raw data the complete instruction would be to subtract 2
from the value in the accumulator [1]
• Instruction lists are machine-specific
o This means a program created using one computer’s instruction set
would not run on a computer containing a processor made by a differ-
ent manufacturer
o For example, a computer program created using Intel’s instruction set
would not run on a device containing an ARM processor
Embedded Systems
• An embedded system is a computer systems with a either one function or
limited specific functions built within a larger mechanical device
• Its purpose is to control the device and allow a user to interact with it
• It runs on firmware and does not have additional peripherals
• An embedded system is different to a general purpose computer system like
a laptop or desktop computer which can be used to perform many different
tasks
• The vast majority of microprocessors manufactured are for use as embedded
systems
• Some embedded systems are microcontrollers meaning they are part of an
integrated circuit with built in memory

type of embedded Description


system
Microcontrollers Integrated circuit containing a CPU and memory
(RAM or ROM) built in to the same chip
Microprocessor Integrated circuit containing only a CPU on the chip
RAM , ROM , peripherals need to be added

• The microprocessor used in an embedded system is often custom designed


• Embedded systems often have firmware which is software built into the sys-
tem which cannot be reprogrammed by the user. The software may be able
to be updated e.g. GPS software in a car navigation system
• Embedded systems usually have some form of analog or digital input

Diagram of an embedded system


Embedded system Possible input de- Possible Output
vices
Screen showing the
Buttons to set the
Digital clock time
time/mode/alarm
Alarm
Pedestrian button Lights
Traffic Lights Timer
Movement sensor
Lighting system Movement sensor Lights
Keypad to enter Alarm
alarm code
Security system
Camera
Movement sensor
Keypad to make Actuator controlling
Vending machine
choice movement of choice
Keypad to set tem-
Central Heating sys-
perature Heat
tem
Temperature sensor

• There are many advantages of embedded systems


o low power consumption
o small physical size
o low cost to manufacturer
o they can be controlled remotely
o can operate in real time and respond to inputs very quickly

Worked example
Describe how an embedded system controls a washing machine
[3]
• The user selects the wash cycle they require using a keypad [1]
• The microprocessor will process the inputs and begin to heat the water and
move the drum to begin the wash. The actuator controlling the drum and the
heating mechanism are the output devices [1]
• Sensors will monitor the water level and temperature [1]
Input and Output Devices
Input Devices
• Every computer system receives commands and data, from the real world,
via input devices
• Input devices converts inputs into digital data which can be processed
• For conventional computer systems, such as desktop computers and laptops,
the most common input devices are the mouse and the keyboard
• There are a wide range of input devices used in more specialist computer sys-
tems such as scanners and sensors
Exam Tip
• The exam board has limited the number of devices you may be asked about
to eight - keyboard, optical mouse, microphone, barcode scanner, digital
camera, QR code scanner, touch screen (resistive, capacitive and infra-red),
2D and 3D scanners
• If you're asked to list some input devices, check you're not listing one in-
cluded in the question as you won't get a mark for this
• You won’t be asked how they technically work but may be asked what each
device does, why it does it and when it may be used
Barcode Scanner

Diagram of a barcode being scanned by a handheld barcode scanner


• Barcodes are a series of black and white bars which represent a code
• A barcode reader shines a red laser at the barcode to read the data it repre-
sents
• The light from the white lines is reflected back
• Black lines absorb the light so less is reflected
• The different levels of reflection are converted into a binary value which can
be processed by a microprocessor
• A barcode reader can be handheld or built into a larger machine such as a
self-service checkout at a supermarket
• Barcodes can be used in many ways such as identifying a product being sold
or tracking a package through the delivery process
• Benefits include faster checkouts, automated stock control, less chance of
error due to manual entry of data, and more detailed tracking information

Worked example

How are barcodes used in supermarkets to manage stock control?

When a customer purchases an item, its barcode is scanned in at the checkout [1]
The barcode reader sends the digital code for the product to the stock database
where it is removed from the stock inventory [1]
This means the number of items of stock is always accurate and up to date [1]
and the supermarket staff can reorder items quickly when stock is low [1]
Digital Camera
• A digital camera works by capturing light and converting it into a digital im-
age
• Light enters the camera through the lens, it reaches an image sensor where it
is split into millions of pixels (small squares). Each pixel measures light inten-
sity which is converted into binary and represents a colour.
• Digital cameras are integrated into smartphones , used in security sys-
tems and by professional photographers to create high quality digital images
• An advantage of digital cameras is they show a preview of the image
• They also instantly create an image which can then be easily dupli-
cated and transmitted via Bluetooth or Wi-Fi
• Software can be used to edit digital photos, for example applying a filter or
retouching a photo

Keyboard
• A keyboard is the most common device used for text-based data input
• They are connected either by a USB cable or wirelessly to the computer sys-
tem
• They are built into laptops.
• Smartphones and tablets have virtual keyboards
• Each key on a keyboard has a peg underneath it which makes contact with a
conducting membrane. This is then converted into an electrical signal to
transmit a unique character code

Microphone
• A computer microphone works by converting sound waves into electrical
signals that can be processed by the computer.
• They can capture any real world sound and convert it into digital data which
can be stored, duplicated or modified
• The microphone has a diaphragm that vibrates in response to sound waves.
These vibrations are then converted into electrical signals by a coil of wire at-
tached to the back of the diaphragm. Changes in the signal are recorded by a
microprocessor using a analogue to digital converter
• Microphones are used to record music, telephone calls, communicate
online and dictation

Optical Mouse
• A mouse use a laser to detect and track movement, this is then processed by
a microprocessor which interprets the movement and replicates it
when moving a virtual cursor on-screen
• Items can be selected or moved using the left mouse button, whilst the right
button usually displays additional menus
• They can be wired or wireless
• They are used to control the cursor in a Graphical User Interface (GUIs)
• They are simple to use and provide the user with an intuitive way to navigate
the computer
• They are reliable due to no moving parts
QR code scanner

Diagram of a QR code being scanned by a mobile device

• A QR code is a visual representation of data using black and white squares


• QR codes can represent over 7000 digits whereas a barcode represents up to
30 digits
• QR codes are scanned by a camera (often on a mobile device)
• A piece of software convert the squares into binary data
• QR codes often link to a website where more information can be found
• They can also be used to advertise products, share contact details, pro-
vide promotional codes, train tickets, and event tickets

Worked example
Describe how festival organisers could make use of QR codes and QR code scanners
[4]
Any 4 of:
Festival e-tickets could be in the form of a QR code [1]
QR scanners could scan them on entry to the festival [1]
QR codes could be used to advertise the festival [1]
QR codes could be used to link to the festival website [1]
QR codes could be used to provide information during the festival [1]
Touchscreen
• A touchscreen can be classed as both an input device and an output device
Types of touch screen

Type How it works Benefits/Drawbacks Uses

Resis- Resistive screens con- + Cheap to produce.


tive sist of two conductive + Resistant to sur- Used in cash ma-
screen layers. The top layer face contaminants chines, infor-
is flexible. When the + Can be activated mation kiosks,
screen is touched the with nearly every ob- medical equip-
two layer connect, ject (stylus, finger, ment
completing a circuit gloved hand)
Infra- LEDs shine infrared + Excellent image
red light across a screen quality,
screens forming a matrix. + high precision
When the screen is + durable
touched the beams + allows for multiple Tablets, laptops,
are interrupted touches at the same smartphones
time
- Requires a bare fin-
ger or stylus for acti-
vation
Capaci- Made up of a protec-
+Excellent image
tive tive layer, a transpar- Large scale com-
quality
screens ent conductive layer mercial displays
+Unlimited touch-life
and a glass substrate. Information ki-
+Scale well
Touching the screen osks
- Sensitive to interfer-
changes the electro- Medical equip-
ence from light, wa-
static field of the con- ment
ter, snow
ductive layer
2D and 3D scanners
• A two-dimensional (or flat-bed) scanner shines a strip of light over a docu-
ment. Reflected light is measured for each pixel. This data is converted into
binary data so the document can be digitally recreated
• A three- dimensional laser scanner shines a light over an object. The geome-
try and dimensions are recorded so the object can be recreated digitally
• The digital 3D model can be modified using specialist software
• A 3D printer could then print out the model
• 2D scanners can be used for creating digital versions of documents or photo-
graphs
• Reading passports at airports
• 3D scanners can be used to create 3D models for use with computer-aided
design (CAD) software
• Creating replicas with 3D printers
• Typical uses of 3D scanners and printers are dentistry, product development,
medical
• A cheap and quick way of creating a digital representation of both 2D and 3D
objects so they can be manipulated, stored, transmitted or copied
Summary of input device uses and benefits

Device Example Uses Benefits

Barcode scanner Faster checkout, less errors,


Checkouts, parcel delivery detailed stock/tracking infor-
mation
QR code scanner Can hold more information
than a barcode
Advertising products, linking
Can be scanned using a cam-
to websites, e-tickets
era on a mobile device
(smartphone)
2D and 3D scanners Converts 2D and 3D objects
Scan documents, photos into digital data which is eas-
and objects ier and quicker to trans-
mit/duplicate or manipulate
Digital camera Smartphones, professional
photography, security sys- Instant preview and image
tems
Keyboard Entering text Universal, easy to use
Mouse
Navigating a GUI
Making selections and en- Intuitive
tering commands

Microphone Recording real-world sound


Musical recordings
Telephone calls
Dictation
Touchscreen Entering text and com-
mands on mobile devices
Can be durable
(tablet, smartphone)
Good image quality
Cash machines
Intuitive/easy to use
Interactive advertisements
Information screens
Exam Tip
• The exam board will refer to a touchscreen as an input device.
Output Devices
• An output device shows the results of the processing in a way humans can
understand
• In a general purpose computer system, the main output device is the moni-
tor/screen
• Other output devices include projectors, printers, speakers and actuators

Exam Tip
• If you're asked to list some output devices, check you're not listing one in-
cluded in the question as you won't get a mark for this
Actuators
• Actuators are used in conjunction with a motor to translate energy (electri-
cal, air, hydraulic) into real-world movement of a physical object.
• They come in a variety of sizes and have been made specifically for a particu-
lar function.
• Examples of use include turning a wheel, opening or closing a door, control-
ling a conveyer belt, operating machinery, moving robotic arms, vibrating a
machine, starting or stopping a pump, opening or closing a valve
• They are often used with sensors. The input of the sensor is checked
against stored values. If the input is within a certain range an actuator is used
to provide movement of a physical object

Worked example
A theme park has a game where a player has to run from the start to the finish with-
out getting wet. The system for the game uses sensors and a microprocessor to
spray water at a player as they run past each sensor

Describe how the sensors and the microprocessor are used in this system

[6]
• Motion sensors are used to detect the player’s movement [1]
• The sensor sends data to microprocessor [1]
• Data is compared with stored data [1]
• if value is within range water is sprayed [1]
• signal sent to actuator to spray water [1]
• if value is outside of range no action is taken [1]
Light projectors
• Used to project computer outputs onto a large screen
• Used to give presentations in both business and education settings
• There are two types - Digital light processing (DLP) projectors and Liquid
crystal display (LCD) projectors.
• DLP systems use millions of micro-mirrors arranged in a grid on a micropro-
cessor within the projector. Light is shone through colour filters and the mir-
rors. The position of the mirrors can be altered to change the intensity of the
light
• LCD projectors use three mirror filters to separate an image into red, green
and blue wavelengths. The three images are then combined to produce the
full colour image which is passed through the lens on to the wall/screen

Device Advantages Disadvantages

Digital light
Image tends to suffer from
projector Higher contrast ratios.
“shadows” when showing a
(DLP) Smooth video
moving image

DLP do not have grey com-


Higher reliability
ponents in the image

The colour definition is not


Smaller and lighter
as good as LCD projectors

Better suited to dusty atmospheres


than LCD projectors
LCD projector
Give a sharper image than DLP pro- Contrast ratios are not as
jectors good as DLPs

Better colour saturation and inten-


Have a limited life
sity than DLP projectors
Use less power and generate less LCD panels degrade over
heat time.
Quieter running that DLP
Laser and Inkjet printers
• Both printers create hard copies of a digital document
• Hard copies are needed when you do not have access to an electronic device
Inkjet printers:
• Have a print head which moves across the page
• Spray liquid ink droplets from ink cartridges through very fine nozzles onto
the paper (these are in the print head)
• The droplets can be piezoelectric or thermal bubble technology
• Inkjet printers produce high quality hard copies of digital images or docu-
ments
Laser printers:
• Are very fast when making multiple copies of a document
• Are useful for high volume print jobs for example producing leaflets
• Have a low running cost per page.
• Are often used in business and education setting
• Have large toner (dry ink) cartridges and large paper trays
• Use positive and negative charges to make the toner particles stick to piece
of paper, heat is then used to bond the particles to the paper
Worked example
Match the characteristic to the correct type of printer

Characteristic Inkjet Laser

Uses ink cartridges


Uses toner (powdered ink)
Great for bright colours and images
Great for clear, sharp images and text
Widely used in homes and home offices
with lower print volumes
Widely used in office with higher print vol-
umes
[1 mark per row]

Characteristic Inkjet Laser

Uses ink cartridges x


Uses toner (powdered ink) x
Great for bright colours and images x
Great for clear, sharp images and text x
Widely used in homes and home offices
x
with lower print volumes
Widely used in office with higher print vol-
x
umes
3D printers
• 3D printers create 3D models of a digital model by depositing layers of ma-
terial, such as plastic or resin, on top of one another to slowly build up a 3D
object
• They allow for precision and can be used in medicine to create prosthetics
and blood vessels
• 3D printers can be used to create rapid prototypes
• Models can be transmitted digitally and then models printed out all across
the world

Liquid Crystal Display screens


• LCD screens are made up of millions of tiny liquid crystals.
• The display is made of pixels arranged in a matrix
• The display requires backlighting
• They are used for TVs, monitors, tablets and phones
• They have low power consumption and run at a cool temperature
• They do not suffer image burn or flicker issues
• They provide bright images and colours
• They are cheaper to produce than LED screens

Worked example
Describe three benefits of LCD screens
[3]
Any 3 of:
• Low power consumption [1]
• Runs at a cool temperature [1]
• Bright image/colours [1]
• Do not suffer Image burn [1]
• Cheaper to purchase than an LED screen [1]

Light emitting diode (LED) screen


• An LED screen is made up of tiny LEDs
• They do not need backlighting which makes them thinner and lighter to
hang on the wall
• LED screens are replacing LCD displays in TVs, monitors, laptops and mobile
devices
• They have better image quality and a longer life span
• They can be used to create very large screens that can be used to show vis-
ual content at events such as football matches and music festivals
• They consume very little power making them suitable for being switched on
for many hours in the day
Organic light emitting diode (OLED) screen
• Much thinner and lighter than traditional LCD screens
• Use organic light emitting diodes (OLEDS).
• They use organic carbon compound to create semiconductors
• No form of back lighting is required
• You can have very thin, flexible screens
Speakers
• Speakers are used to take digital sounds or recordings and output them as
sound waves which can be heard by humans
• The digital data is changed into a electric current using a digital to analogue
converter (DAC)
• It is then passed through an amplifier to create a current large enough to
drive a loudspeaker
• The loudspeaker converts the current into a sound wave
• Typical uses include listening to music, listening to video sound, telephone
calls and alarms

Worked example
What would an appropriate output device be for a large screen showing replays dur-
ing a football match?
Justify your choice.
[3]

• An LED screen [1]


• Any 2 of:
• Consume little power [1]
• Can be used to create large screens [1]
• Provide a better quality image compared to alternatives [1]

Exam Tip
• This section of the course has been simplified for exams taking place from
2023 onwards. In the past students needed to know how each device physi-
cally worked. You now only need to know:

o What each device does and why it does it


o When it is used
• Older textbooks may contain more detail than is required
Sensors
• Sensors are input devices
• They measure a physical property of their environment such as light levels,
temperature or movement
• Sensors can be used for monitoring systems and control systems
o A monitoring system tracks the state of a system, it gathers data and
may issue warning messages
o A control system will control the system based upon the input from
sensors
o For example, if the water temperature in a fish tank fell below the ac-
ceptable level, a control system would start up a heater. The system
will then continue to check the water temperature readings and when
they are within the acceptable range it will switch off the heater
▪ This process of the outputs affecting the following set of input
values received from the sensors is called a feedback loop
Exam Tip
• You are likely to be given a scenario and asked to identify the sensors that
would be used.
• The 14 sensors you need to be aware of are in the table below

Sensor
What it measures Typical use
type

Acous- Sound levels To detect changes in sound levels of in-


tic dustrial machinery
To monitor noise pollution
In security system to detect suspicious
sounds
Accel- Acceleration rate, tilt, vibra- Detecting sudden changes in vehicle
erome- tion movement and deploy safety features if
ter needed
In mobile phones to detect orientation
of the device
Flow Rate of gas, liquid or powder Detect changes in the flow through
flow pipes in water system
Gas Presence of a gas e.g. carbon Detect levels of gas in confined spaces
monoxide Detect gas levels when fixing gas leaks
Humid- Levels of water vapour
Monitor humidity in greenhouses
ity
Infra- Detecting motion or a heat Security systems detecting intruders
red source who break the beam
Measures heat radiation of objects -
used by emergency services to detect
people
Level Liquid levels Detects levels of petrol in a car tank
Detect levels of water in a water tank
Detect a drop in water levels due to a
leak
Light Light levels Automatically switching on lights when
it gets dark (street lights, headlights)
Mag- Presence and strength Anti-lock braking system
netic Monitoring rotating machinery such as
field turbines
Mois- Presence and levels of mois- Monitoring moisture in soil
ture ture Monitoring damp in buildings
pH Acidity or alkaline Monitoring soil to ensure optimum
growing conditions
Monitor pHlevels in chemical processes
Pres- Gas, liquid or physical pres- Monitoring tyre pressure
sure sure Monitoring pressure in pipes during
manufacturing process
Proxim- Distance Monitoring position of objects in robot-
ity ics
Used in safety systems to prevent ob-
jects colliding
Tem- Temperature in Celsius, Fahr- Used to maintain temperature in swim-
pera- enheit or Kelvin ming pools
ture Used to control temperature in chemical
processes

Worked example
What type of sensor would be used to help drivers when reversing?
[1]
A Motion
B Infra-red
C Light
D Proximity
• D [1]
• A proximity sensor would be used to monitor how close the car was to ob-
jects. It would then sound a warning alarm when the proximity is below a cer-
tain value (meaning the car is too close to an object)
Is this a monitoring system or a control system?
[1]
A Monitoring
B Control
• A [1]
• The reversing warning system is a monitoring system. It indicates to the user
when the car is too close to an object but it does not stop the car automati-
cally
Data storage
Primary Storage
• Primary storage is directly accessible by the CPU , it includes RAM, Cache,
and ROM
• The purpose of Random Access Memory (RAM) is to store data, instructions
and software (including parts of the OS) currently in use
o RAM is also called main memory
o RAM has faster read/write speeds than secondary storage
o RAM is volatile which means it is temporary memory and all data will
be lost when the computer is switched off
o The larger the main memory, the more data the computer access
quickly, which can improve the computer's performance
o A standard desktop computer has between 4GB and 16GB of RAM
• The parts of the operating system currently in use will be stored in RAM
• The purpose of cache is to store frequently/recently used instructions and
data
o Cache has faster read/write speeds than RAM
o There are different levels of cache
▪ Level 1 cache is situated within the CPU
▪ Level 2 and 3 cache are situated on the motherboard
o If you increase the amount of cache you can store more frequently
used data and increase the performance of your computer
▪ If you have too much cache it will decrease the data access
speeds because the data requested will take longer to find
o Cache is volatile and all data will be lost when the computer
is switched off
A diagram showing the parts of a computer system which are classed as primary
storage
• The role of Read-only memory (ROM) is to store the computer’s boot-up se-
quence
o The boot-up sequence is a set of instructions the computer executes
when then computer is initially switched on
o This sequence will run a series of checks to ensure all of the sys-
tem hardware is working
o It will then load the operating system which will move from second-
ary storage to RAM
• ROM is non-volatile which means data will be stored when the computer is
switched off
• ROM is read-only which means data cannot be written to ROM
The difference between ROM and RAM

RAM ROM

Volatile Non-volatile
Can read and write data to RAM Read-only
Exam Tip
• Make sure you're specific about which component you're referring to in exam
questions and give the proper name e.g. RAM rather than memory unit
Worked example
Describe what is meant by main memory and how it is used in the Von Neumann
model for a computer system
[3]
Any 3 of:
• Memory is RAM [1]
• It is primary storage [1]
• It is volatile memory [1]
• It holds currently in use data/instructions [1]
• It is directly accessed by the CPU [1]
Secondary Storage
• Secondary storage is not directly accessed by the CPU
• It is used for permanent storage of data
• Secondary storage is non-volatile. This means data is stored even when
power is lost to the device
• Secondary storage is needed as primary storage (such as RAM ) is volatile and
will not retain data when the computer is turned off
• Unlike ROM, secondary storage can be read from and written to. ROM is
read only
• Common examples of secondary storage include hard disk
drives (HDDs), solid-state drives (SSDs), external hard drives, USB flash
drives, CDs, DVDs, and Blu-ray discs. These can be used to store data to
transfer it to another computer
• Data access speeds for secondary storage devices are typically slower than
primary storage (such as RAM)
• Secondary storage devices often have large capacity (can store large
amounts of data)
• Software such as the operating system is saved permanently on secondary
storage. The instructions and data that makes up the software then moves to
RAM when it is in use
• Secondary storage devices can be internal (inside the computer) and external
(outside the computer)

Diagram showing different internal and external secondary storage devices


Comparison of primary and secondary storage

Primary storage Secondary storage

Volatile / temporary Non-volatile /permanent

RAM and cache can be read from and writ-


Secondary storage can be read from and
ten to
written to
ROM is read-only

Can be directly accessed by the CPU Cannot be directly accessed by the CPU

Smaller capacity Larger capacity


Data access speeds faster than secondary Data access speeds slower than primary
storage storage
Stores data and instructions Stores data and instructions

Worked example
Which of the following is an example of secondary storage?
Random access
A
memory
B Read only memory
C Solid State Drive
D Blu-ray disc
• C and D [1]
• Random access memory and read only memory are both primary storage and
can be accessed directly by the CPU. Solid-state drives and blu-ray discs are
classed as secondary storage. Data can be permanently stored on them but
they cannot be accessed directly by the CPU

Exam Tip
• When referring to a USB memory stick, don't refer to it as USB as this could
be anything that is plugged in with USB and not necessarily a storage device
Types of secondary storage
• There are three types of secondary storage - magnetic, solid state and opti-
cal

Exam Tip
• You need to be able describe the operation of each type of secondary stor-
age. You may also need to recommend a type of storage for a given scenario
and justify your choice
Magnetic
• Magnetic hard disk drives have been the main type of internal secondary
storage in personal computers for many years however solid state drives are
increasingly popular due to their durability, low power consumption and high
read/write speeds
• A magnetic hard disk is made up of several metal discs coated with a mag-
netic material
o These are called platters
o Iron particles on each platter are magnetised to represent a 0 or 1

A diagram showing the structure of a magnetic hard disk


• Each platter is divided by concentric circles creating several tracks and wedge
shaped sectors. Where they intersect is a track sector

A diagram showing how each platter is divided by tracks and sectors


• The hard drive spins the metal disk(s) at a high speed (typically around 5400-
7200 RPM) using a motor
• A read/write arm, controlled by an actuator, moves the head over the sur-
face of the disc to the location of the data
• The data is read/written using electromagnets
Solid State
• Solid State secondary storage is made of transistors that are arranged in a
grid layout
• It uses NAND and NOR gates in electrical circuits to persistently control the
flow of electrons
• Current flowing is 1, no current is 0 - which is how electrical flow can repre-
sent binary values
• A NAND gate will take in two inputs and produce an output (1/electrical cur-
rent) as long as both inputs are not 1
The truth table truth table for a NAND gate

In- In- Out-


putA putB put

0 0 1

0 1 1

1 0 1
1 1 0
• A NOR gate will produce an output (1) only when both inputs are 0
The truth table for a NOR gate

In- In- Out-


putA putB put

0 0 1
0 1 0
1 0 0
1 1 0
Optical
• Optical devices include CDs, DVDs and Blu-rays
o Blu-rays have the largest capacity
o CDs have the lowest capacity
o CD-R are read-only (you cannot save data on to them)
o CD-RW can be written to and read from
o DVD-RW can be written to and read from
• All optical devices work by shining a laser at the disk and processing the re-
flection
• An arm moves the laser across the surface of the disk
• In CD-Rs a laser burns the data, permanently on to the disk, by creat-
ing pits and lands
• The laser is also used to read the data from the pits and lands
• When the laser light hits the point where the pit changes into a land or vice
versa the light scatters and is not reflected back as well. This is captured by a
sensor and can be interpreted as a change in the binary value

A diagram showing how data is burnt on to optical discs to create lands and pits
which can then be used
• In CD-RW the chemical composition of the disk is changed to represent 0s
and 1s. This change can be overwritten
Exam Tip
• Make sure you have a greater understanding of the operation of the different
types of storage
Worked example
Describe how a magnetic storage device stores data
[6]
Any 6 of:
• Storage device has platters [1]
• Platters/disk divided into tracks [1]
• Storage platter/disk is spun [1]
• Has a read/write arm that moves across storage media [1]
• Read/writes data using electromagnets [1]
• Uses magnetic fields to control magnetic dots of data [1]
• Magnetic field determines binary value [1]
Comparison of secondary storage
HHD SSD
• #moving parts • No moving parts
• Magnetic • Flash memory
• More storage per unit of currency • Faster
• Failure only due to mechanical fault • Finite number of read/writeY
Virtual Memory
• The purpose of RAM is to store current data and program instructions in use
• The amount of physical RAM available is limited. The average modern desk-
top computer has between 4GB and 16GB of RAM. Some programs are
larger than this
• Virtual memory is part of secondary storage which acts as RAM when RAM is
full
• It prevents the computer system crashing when RAM is full
• Data that needs to be accessed by the CPU directly is switched by the operat-
ing system from virtual memory into RAM and an inactive page from RAM re-
places it in virtual memory. This is called page switching
• Disadvantages
▪ Disk trashing – can permanently damage the hardware

A diagram showing page switching between RAM and virtual memory


• The table describes the steps that are taken when a program is opened on a
computer

Step Description

1 • The memory manager software built into the Operating System


checks to see if there is sufficient space in RAM to move the new
program’s instructions into RAM, so that they can be directly ac-
cessed by the CPU
2
• If RAM is full, the memory manager will move out the most inac-
tive pages of data and put them in virtual memory until needed

3
• The new program instructions are moved into RAM

Worked example
Sandy is playing an open world role playing computer game set in a large 3D environ-
ment. This requires the use of virtual memory. Explain why
[3]
• To extend the RAM capacity [1]
• To stop the computer game from crashing when the physical RAM is full [1]
• To allow the computer to process the large amount of data required [1]

Cloud Storage
• Cloud storage is the concept of storing data on remote servers, that can be
accessed via the internet, instead of on a local storage device (such as
an SSD or HDD)
• The physical servers, where the data is stored, are owned and managed by a
hosting company
o Cloud storage warehouses often have thousands of servers containing
hard drives
o The hosting company provides services such backing up the data,
managing access to the data as well as general security
• The data can be accessed at any time, on any device, as long as there is an in-
ternet connection
• The data is accessible using a web browser or dedicated software that con-
nects to the cloud storage service
• There is potentially limitless storage, although it does need to be paid for
• Online storage means it is easy to share data and collaborate with others
• If the internet connection is slow/lost the access to your data is affected

A diagram showing different devices connecting to remote servers


Advantages of cloud storage
• Cloud storage offers several advantages over storing data on a local second-
ary storage device
Benefit Explanation
Acces- • Data can be accessed from anywhere
sibility • Data can be accessed by anyone with the relevant per-
missions, making it quick to share files and collaborate
with others
• Data can be accessed on any device with an internet
connection
Scala- • Cloud storage providers allow customers to increase or
bility decrease their storage capacity as needed
Relia- • Cloud storage providers often use multiple servers to
bility store and backup data, reducing the risk of data loss due
to hardware failure
Secu- • Cloud storage providers offer advanced security features,
rity such as data encryption and multi-factor authentica-
tion multi-factor authentication, to protect user data
from unauthorised access
• There is no need to hire specialist staff as IT services
being provided by the cloud storage provider

• You also do not need to purchase local secondary storage devices


• One cloud storage centre is more environmentally friendly than millions of
individual servers
• There are some drawbacks to using cloud storage
o If the user has a slow or unreliable internet connection they would
have problems accessing their files
o If you are storing a lot of data it can be expensive
▪ You have to pay the cloud storage provider
▪ You may need to commit to an annual subscription
▪ You may have to pay for high download and upload data trans-
fer limits
o Data being sent over the internet has the potential to be intercepted
o Security is managed by the cloud storage provider which means the
user does not have complete control over it but is still legally respon-
sible for ensuring any personal and sensitive data is secure
Worked example
A school currently stores all of their data on local servers. They are considering up-
grading their system to utilise cloud storage.
Explain two disadvantages to the school of storing their data in the cloud.
[4]
• You need a constant internet connection [1]
• if the internet connection failed, teachers would not be able to access lesson
files [1]
• if the internet connection failed, teachers would not be able to access stu-
dent data/take electronic registers [1]
• if the internet connection failed, students would not be able to access their
work/coursework [1]
• Reliant on third party to carry out security procedures [1]
• but the school is still legally responsible if data is accessed by unauthorised
people [1]
• Data stored on the cloud could be hacked or intercepted [1]

Explain two advantages to the school of storing their data in the cloud.
[4]
• Additional storage can be purchased if needed [1]
• The cloud hosting company provides back up [1]
• The cloud hosting company provides security [1]
• Data can be accessed from anywhere and from any device provided there is
an internet connection [1]
• So teachers would be able to access data from home [1]
• So students would be able to access work from home [1]
Network Hardware
Network Interface Card
• A Network Interface Card (NIC) or Network Interface Controller is an internal
physical component which enables computers and other devices to connect
to a network
• They are also known as network adapters
• NICs have a built in ethernet port and can be connected to a network via an
Ethernet cable
• You can have Wireless Network Interface Cards (WNIC) which allow a device
to wirelessly connect to a network
• The primary function of a NIC is to send and receive data packets between
the computer or device and the network
• The NIC converts data to be sent into signals that can be sent across the
transmission medium
• If this is through a wired network, the signals will be voltages through an
ethernet wire or pulses of light through a fibre
• If this is through a wireless network, the signals will be radio waves
• NICs are likely to be integrated into the motherboard but can be added as an
expansion card
MAC Addresses
• A Media Access Control/MAC address is used to identify a device on a net-
work
• It is a unique code which consists of six pairs of hexadecimal codes sepa-
rated by a colon
• Each pair of hex digits is a Byte of data. So in total a MAC address is 6
bytes or 48 bits long
• An example MAC address is b4:71:ac:f3:21:a2
• The MAC address is assigned to the NIC by its manufacturer
• The first three pairs are the manufacturer ID number and the last three pairs
is the serial number of the NIC and identifies the device on the network

An example MAC address - the first part identifying the manufacturer and the sec-
ond part identify the device

• A MAC address cannot be changed. It is static


A table listing the differences between an IP address and a MAC address

MAC Address IP Address

Permanently assigned Can be used to identify devices on a


to a NIC and cannot be network but are dynamic and can be
changed changed
MAC addresses are
IP addresses are written in denary
written in hexadecimal
MAC addresses are 6
IP addresses are 4 bytes long
bytes long
MAC addresses are
MAC addresses are used to identify a
used to identify a de-
device on a WAN
vice on a LAN
Worked example
Describe what is meant by a MAC address
[4]
Any 4 of:
• Used to identify a device [1]
• It is a unique address [1]
• It is a static address/it does not change [1]
• It is set by the manufacturer [1]
• The first part is the manufacturer ID [1]
• The second part is the serial number of the device [1]
IP Address
• An IP (Internet Protocol) address is a unique numerical identifier assigned to
devices connected to the internet
o IP addresses are used to identify and locate devices on the internet
o This allows data to be sent and received between devices
• An IPv4 address is four numbers separated by a full stop
o Each number is a byte and range between 0-255
o There are over 4 billion unique addresses using the IPv4 system
• For example, an IPv4 address might look like this: 192.164.3.1
Routers and gateways have a unique public address
• Public addresses are assigned by your internet service provider and is the IP
address for the network
• Public addresses are often static addresses meaning they do not change

A diagram showing how Private and Public IP addresses are used to identify de-
vices on the Internet and within a LAN
• A router can assign private IP addresses to devices connected within its net-
work
• These are often dynamic IP addresses meaning they can change
• Dynamic addresses are assigned from a list of available addresses at the time
they are required
• The IP4 system is running out of possible addresses due to the enormous in-
crease in networked devices
• A new system called IPv6 has been developed. It provides enough unique ad-
dresses for every networked device on the planet
o IPv6 uses a 128 bit address
o Digits are organised into eight groups
▪ Each group is made up of four hexadecimal digits
▪ For example bb43:ff3f:0000:549b:e43e:db84:1f1f:0b9e
Worked example
Give two characteristics of an IP address
[2]
Any 2 of:
• A unique address [1]
• Can be public or private [1]
• Can be static or dynamic [1]
• IPv4 has four groups of digits [1]
• Each number is between 0-255 [1]
• and separated by a full stop [1]
• IPv6 has eight groups of digits [1]
A comparison of IPv4 and IPv6 IP addresses

IPv4 IPv6

32-bit address 128 bit address


Four groups of denary Eight groups of four hexa-
digits separated by a decimal digits separated by
full stop a colon
Over 4.3 billion unique Almost infinite amount of
addresses unique addresses
Worked example
Explain the difference between a private and a public IP address
[4]
Any 4 of:
• A private IP address is not accessible from the internet [1]
• and is used to identify a device within a local area network [1]
• A public IP address is used to identify a device on the internet [1]
• Public IP addresses are assigned by an internet service provider (ISP) [1]
• Public IP addresses are unique [1]
• Public IP addresses can be accessed from anywhere on the internet [1]
• Public IP addresses allow devices to communicate with each other across dif-
ferent networks [1]
Router
• A router is an important piece of network hardware. It connects one network
to another network
o This means it can be used to connect a local area network (LAN ) to
the internet, which is a wide area network(WAN )
• An important role of the router is to analyse data packet and direct them on
to their destination

A diagram showing multiple networks connected by routers, represented by the


blue circular objects
• A router being used to connect a LAN to a WAN will have a public IP ad-
dress , which has been assigned to it by an Internet Service Provider
• It is this public IP address which other routers use to identify and direct pack-
ets to the network
• An important role of the router is to analyse data packets and direct them on
to their destination
o The IP address of both the sender and intended recipient is stored in
the header of the data packet
▪ The header contains information about the packet
▪ The payload is the actual data being sent
• If the data packet is coming into the LAN, the router will send the data packet
to the specific device, within its LAN, that the packet is meant for
• If the packet is being sent from a device within the LAN, it will read the
header of the packet to determine the intended destination IP address
o It will then forward the packet on to the destination
▪ It might have to travel through several routers before it gets
to its destination
▪ Each pass from router to router is called a hop
• The network access device or ‘home hub’ used in your home network will
have a router built into it
A summary of the steps a router takes when it receives a data packet

Step Description

1 • a router receives incoming data


packets from one network and anal-
yses the packet header to determine
the destination IP address
2 • It then looks up the IP address in a
routing table (routing table of known
networks) to determine the next net-
work where the packet should be
sent
3 • The router then forwards the
packet to the appropriate network or
device
• This process is repeated by every router the data packet passes through, until
it reaches its destination
• In addition to routing data between networks, routers can also perform other
functions such as…
o assigning IP addresses to devices within the LAN
o filtering incoming traffic based on certain criteria, such as IP address,
port number, or protocol type
Software
Types of Software and Interrupts
System Software & Application Software
• Systems software provides the services that the computer requires, including
operating system and utility software
• E.g. allowing instructions to be processed by the CPU to allow word pro-
cessing software to process. Without systems software the system would be
useless
• Systems Software is made up of two core elements: the operating sys-
tem and utility software
Operating System
• This is a program designed to run other programs on a computer. It is consid-
ered the backbone of a computer, managing both software and hardware re-
sources
• Operating systems are responsible for everything from the control and alloca-
tion of memory to recognising input from external devices and transmitting
output to computer displays. They also manage files on computer hard drives
and control peripherals, like printers and scanners.
• Examples of Operating System: Windows, MAC, Linux
• Gui, CLI and Natural language interface
Utility Software
• Utility programs perform specific tasks related to computer functions, re-
sources, files and security. They help to configure the system, analyse how it
is working and optimise it to improve its efficiency. Some of these utilities in-
clude:
• Security utilities:
o Anti-Virus - Scans the computer system and ensures that files are
quarantined so that they can be removed by the user
o Encryption - uses an algorithm to scramble (encrypt) a file according
to the key which is used to make the file unreadable; the key is
needed to decrypt the file back to its original form so it can be read
o Firewall - monitors network traffic and blocks unauthorised access.
Criteria is set and if the data meets the criteria it is accepted other-
wise it is rejected
• Disk organisation utilities:
o System Clean-Up Tools – to search for and remove files no longer
needed, to reduce space and speed up access to the system
o Disk Defragmentation Tools - it is used to rearrange the parts of files
on the disk drive: when a file is saved to the disk, parts of the file
might be saved in different areas of the disk, these tools try to move
all the parts to the same area for quicker access

• Data compression utilities


o File Compression Software – to make files smaller so that they take
up less storage space and can be transmitted to other users more eas-
ily
• File backup utilities
o Full Backup - stores all files and software on the system
o Incremental Backup - only backs up the files and software that have
been added since the last backup
Application Software
• This is designed to carry out a specific task the user would need for complet-
ing a variety of tasks. These are the applications that the operating system
would process and allow end users to complete their vital day to day tasks.
Examples are:
• Word Processing Software
o This allows users to create written documents
o e.g. letters, reports etc
• Spreadsheet Software
o This allows users to perform numerical calculations and function to
create automation for all mathematical elements
o e.g. budgeting, accounting, stock counts etc
• Presentation Software
o This allows users to create interactive and multimedia presentations
to show to an audience
o e.g. sales pitches, launching of products etc
• Multimedia Software
o This is used to create multimedia and interactive content for a num-
ber of purposes, it explores text, audio, images, video, sound and ani-
mations
o e.g. image manipulation, editing a video etc
• Web Browsers
o This allows the user to access the internet and use the world wide
web
Exam Tip
• Make sure you use the names given above and not brand names e.g. Mi-
crosoft as this will cost you marks
Distribution Methods
Freeware software is where:
• The user is not allowed to access the source code so, they cannot tailor the
software to their needs or fix any bugs in it
• The software is still covered by copyright and the user must get the owner’s
permission to do anything beyond using it
Free software is where:
• The user can access the source code so, they can tailor the software to their
needs and fix any bugs in it
• The source code could be studied for educational purposes
• The user can redistribute the software but this must be done under the same
terms as the original software
Shareware is software which:
• Gives a trial version of the software for a limited time with limited features
free of charge
• Requires the user has to pay fee if the full version is needed
• Is protected by copyright
• Is a type of software licence
There are many ethical considerations when distributing software:
• Accessibility of software
• Age appropriation
• Copyright
• Distribution of malware
• Environmental impact of distribution media e.g. CDs
• Following guidelines of professional bodies e.g. ACM/IEEE/BCS
• Intellectual property theft
• Offensive materials
• Plagiarism
• Privacy of data
• Security of software
Exam Tip
• Make sure you apply your answer to the context given in the question
The Operating System
What does the Operating System do?
• Managing Files:
o The file manager controls all of the different files on the system, e.g.
text files, graphic files, and program files. It controls file permis-
sions such as the user's ability to see or open a file, write a file or de-
lete a file.It helps to organise and control files so that they are as easy
to use as possible for the user. It can help to protect the user from ac-
cidental mistakes too
• Handling Interrupts:
o An interrupt is a signal from a device or software to the processor.
This will stop the processor temporarily from fulfilling this request
immediately, some examples could be:
o Software errors - e.g. files not found, or software not responding
o The user initiating Ctrl Alt Delete to lock, log off etc
o Files stop copying as the name of the file is already in the folder
o Once this interrupt is received by the CPU it either carries on or com-
pletes the action desired
o Whenever an interrupt is initiated the status of this task is saved to
the interrupt service routine.
o Once the interruption has been completed the system continues back
to normal before the interruption even happened
• Providing an Interface:
o Users must interact with the operating system through a user inter-
face. The user interface is a system which converts what the user in-
puts to a form that the computer can understand and vice versa
o Many computer or database operating systems use complex program-
ming languages which are not easy to use
o A user interface is created to allow easier control of the operating sys-
tem by the system user. A good interface should be easy to use
o e.g.: consistent menu structures; consistent operations from actions
like clicking the right mouse button
• Managing Peripherals and Drivers:
o The overall intention of this is to handle all the devices that are con-
nected to the computer system. This includes input devices such as a
keyboard and mouse, it also includes output devices such as a moni-
tor and printer
o It communicates with the devices through software called drivers.
These translate the instructions by the device manager into one the
devices can understand Peripherals like a mouse, keyboard and
printer all need drivers so that they can communicate with the soft-
ware
• Managing Memory:
o Memory management is in charge of the RAM. Programs
use RAM throughout their operation. Some programs will be large
and complex and use the RAM extensively whereas some are very
small programs and won’t use it as much
o Memory management checks all requests from programs are valid
and allocates accordingly. It will deallocate space and swap out data
to virtual memory. It will ensure overall that different programs can
be open at the same time
• Manage Multitasking:
o Multitasking allows for software tasks to be completed at the same
time to ensure multiple elements can be completed immediately, it
uses a system called time slicing which splits different tasks into small
segments
o They can all be run one after the other, giving the element of multiple
tasks being completed at the same time, instead of waiting for one
operation to complete before moving on to the next task

• Providing a Platform for Running Applications:


o Application programs and the hardware will communicate through a
system within the operating system called an application programs
interface(API)
o This API is a library interface which will share data between software
to allow elements to process
o If any application is installed on the system, the Operating System will
manage this process, it will allocate memory space and will control
the application's data or devices, user access will also be manage

• Providing a System Security:


o System security is just about how the operating system can stay pro-
tected and ensure that elements are monitored and actioned to en-
sure the system is secure. Some areas of security are:
▪ Creating/Deleting users for the system
▪ Providing access level rights, e.g. administrator rights over in-
stalling, modifying a system or accessing files or folders. This is
compared to standard rights of just accessing and using soft-
ware/files on the system.
▪ Auditing - this is keeping a log of file edits, deleted files, crea-
tion of files etc
▪ Protecting from threats, viruses, worms, malware or remote
hacker attacks
▪ Security updates to fix patches in the operating system
• Managing User Accounts:
o Each user is provided with an account for access to the system. They
will be provided with their username and then will need to create a
password based on rules set out initially
o Each account will then be granted different levels of access, depend-
ent on needs and level of security. This will also monitor login activity
and even log users out if they have been inactive for a while
Hardware, Firmware & the OS
• Application Software must talk to the operating system, this will then allow it
to interact with the hardware
• The hardware will then process and send the information to the operating
system which then directly talks back to applications software in a continuous
loop
• Firmware
o This process is in between the Operating System and Hardware
o When a computer initially first loads up, it has to explore the ROM for
its initial boot-up instructions These are contained in a Bootstrap
loader
o The initial process is handled by the basic input/output system
(BIOS) which is known as firmware. This will provide some low-level
control for all devices
o Once complete these are sent to RAM to be processed by the operat-
ing system
o Overall this creates an extra layer which is to ensure that initially the
hardware devices e.g. keyboard are available and can be communi-
cated directly with the operating system
• E.g. - If you were to type on a word processing document, this would talk
with the operating system initially to request the key presses. It would send it
to the firmware to check whether the keyboard is available. Once the con-
nection is established with the hardware it communicates directly with the
keyboard back through firmware, the key instructions are passed up to the
operating system and finally displayed on the word processing software

Exam Tip
• Ensure you have the understanding of how the four areas work together. An
exam question would focus on how these four key areas would communi-
cate.
Interrupts
• We know that computers use the fetch-decode execute cycle within the CPU
to run instructions over and over. However, while this is occurring other de-
vices may need to signal to the CPU to tell it to stop temporarily (interrupt)
so that it can do the dedicated specific task
• E.g. a user has initiated ctrl alt delete to run task manager or a user wants a
document printing
• Interrupts will need to ensure that the CPU can stop executing its current
program to run code for the overall interruption. Interrupts need to be
added to an area called the interrupt service routine
• Two types of interrupt:
o Hardware Interrupt - this is caused by a hardware device such as a
hardware failure e.g.
▪ pressing a key on the keyboard
▪ moving the mouse
o Software Interrupt - this occurs when an application stops or requests
services from the OS e.g.
▪ a program is not responding
▪ division by zero
▪ two processes trying to access the same memory location
• However, the CPU currently contains registers that are holding data currently
being handled: These include:
o Program Counter - The location of the next instruction which will
need to be fetched
o Current Instruction Register - holds the current instruction being exe-
cuted
o Memory Address Register - stores the location of where the data is
being stored in RAM or where in RAM the data will be sent
o Memory Data Register - stores the actual data from the location in
the RAM or that will be sent to RAM
• The interrupt service routine is simply added to a particular area where a
certain set of instructions are sent that will need to be fetched, decoded and
executed to complete the commands of the interrupt
• As a result, it’s clear that the current registers will need to be changed at this
point to accommodate the interrupt
• The interrupt will be executed instead of the original instructions
• When the interrupt is received the current values that were held in the regis-
ters are copied back to the RAM in an area known as a stack
• These values are pushed onto the stack and are added to the top of the stack
frame, which will save them for later retrieval when the interrupt is complete
• There is a possibility that an interrupt can also be interrupted which is known
as a division by zero. Due to the system in RAM with stack frames, the cur-
rent interrupt would be moved to the bottom of the stack frame to complete
the main interrupt initially
Exam Tip
• Focus on the interrupt service routine and its importance with sending the
instructions to a stack frame to process the interrupted instruction, the previ-
ous instructions can be accessed at the top of the stack frame to continue
processing afterwards.
There are common interrupt priorities for different categories, these are:
• Hardware
o Power supply may have failed
o Power button may have been pressed
• User
o Moving the mouse
o Clicking an icon to open a new program
o Keyboard presses e.g. ctrl, alt, delete
• Software
o Illegal instruction encountered
o Overflow
o Login request
o Crashing
• Timer
o Data logging programs which reads sensors continuously
o Screen recording applications
• Input/output devices

o Signaling of data transfer been completed


o Printer ink supply notifications
o Input devices not responding
Types of Programming Language,
Translators & IDEs
High & Low Level Languages
Low Level Languages
• Low Level Languages are languages that sit close to a computer’s instruction
set. These are basic instructions that the CPU will understand
• For instance an assembly language which allows programmers to focus on
programming simple commands, which in turn is converted into ma-
chine code This element is needed for the core hardware to be able to work
with the software
• These languages are written for specific processors to ensure they embed the
correct machine architecture
• Assembly Language - The code is written using mnemonics, abbreviated text
commands such as LDA (Load), STO(Store) Using this language programmers
can write human-readable programs that correspond almost exactly to ma-
chine code.
• Machine code – is at the hardware level and is written in binary (1’s and 0’s)

Advantages Disadvantages

It gives programmers complete control over Difficult to write and under-


the system components so it can control stand
hardware components.
Efficient code can be written for the proces- Machine dependent and can-
sor so it will occupy less memory and exe- not be added to different
cute faster specification machines
They provide direct manipulation of hard- More prone to errors
ware which means it will be more efficient
Communicates directly with hardware Knowledge of computer ar-
chitecture is key to program
effectively
High Level Languages
• High Level Languages are programming languages which use English-like
statements which allow users to program with easy to use code, allow for
clear debugging and once programs are created they become easier to main-
tain
• High level languages were needed more due to the development of processor
speeds and memory capacity increasing
• Examples of these languages are Python, C#, Java etc

Advantages Disadvantages

It is easier to read and write


The user is not able to directly manipulate the
and the programmer is less
hardware
likely to make mistakes
It is easier to debug so it will Needs to be translated to machine code before
save time running
The code is portable so can
The program may be less efficient
be used on any computer
One line of code can perform
multiple commands

Exam Tip
• You will be asked about the advantages and disadvantages of high or low
level languages or you will be asked to compare and contrast between the
two types of language
Assembly Language
• The first languages were actually direct machine language, where program-
mers had to program it with direct binary numbers of 1’s and 0’s. It was quite
clear to see that this method was incredibly difficult to program, which al-
lowed the introduction of Assembly languages

• Programmers who use assembly language do so for the following reasons:


o Need to make use of specific hardware or parts of the hardware
o To complete specific machine dependent instructions
o To ensure that too much space is not taken up in RAM
o To ensure code can completed much faster
• Assembly languages allow programmers to program with mnemonics. e.g.
o LDA Load - this will ensure a value is added to the accumulator
o ADD Addition - this will add the value input or loaded from memory to
the value in the accumulator
o STO, Store - stores the value in the accumulator in RAM
• This is used rather than binary code which allowed continuation of working
directly with the hardware but removed an element of complexity
• A mnemonic is received by the computer and it is looked up within a specific
table
• An assembler is needed here to check the word so that it can be converted
into machine code
• If a match from the word is found e.g. STO the word is replaced with the rele-
vant binary code to match that sequence

Exam Tip
• A question will focus more directly on how the assembler converts to work
with the hardware. You must focus on mnemonics being converted from a
table and into the corresponding binary code
Translators
Compilers & Interpreters
• Programmers will write program source code using high-level languages e.g.
Python, Java, C# etc. As programmers, we can understand source code as it is
descriptive, easy to read, maintain and debug. However this is not good for
the hardware as it needs to be converted into binary to allow the hardware
to understand and execute it, this is known as machine code. For this to work
it needs to pass through a translator first. There are two types of translators -
a compiler and an interpreter
Compiler
• This method will translate a program into machine code. Compilers convert
the source code in one go into an executable file ready for distribution. This
method is used mainly when a program is finished with no syntax or logical
errors
• Compiling may take time to be processed, however, this can be used over
without needing to be recompiled every time, bearing in mind that the pro-
gram contains no errors
• Error reports are produced after a program has been translated. Common er-
rors in code will allow the computer to crash and not respond, it’s important
to be aware that if there are errors the source code must be changed to com-
pile again
Interpreter
• This is the method that directly sends the source code to the machine code.
This will translate each line of code individually, if an error occurs the pro-
gram will stop and an error message will occur. Once the error message is
fixed, the program can carry on running from where the error occurred
• This is equrie to interpreate
• Translate code line by line
Exam Tip
• You will need to have a good understanding of the difference between a
compiler and an interpreter. You will need to focus on features of compilers
and interpreters or focusing on an overall comparison between the two
• Although both translators find errors in code, they do not debug the errors -
this is done by the programmer

Differences:
• compiler produces object code / interpreter doesn’t produce object code
• compiler translates whole program in one go / interpreter translates and executes
line at a time
• compiler produces list of all errors / interpreter produces error message each time
an error encountered
• compiler produces “stand alone code” / interpreter doesn’t produce “stand alone
code”;
• compilation process is slow but resultant code runs very quickly / interpreted code
runs slowly
Advantages & Disadvantages
Compiler

Advantages Disadvantages

Due to all code being compiled at the same time


Run quickly as the program as
there must be enough memory space to handle
the source code has been
this, if not and virtual memory is used it can be
stored to be translated
much slower
Compilers optimise the code, If there are errors in the code the compiler will
this code will run quicker and not identify directly where the error lies, making
take up less memory space it difficult to debug
Original source code will not
be seen, which is ideal for
It is designed solely for one specific processor
programmers to stop work
being copied
If the program is changed it must be recompiled

Interpreter

Advantages Disadvantages

Each line of code has to be interpreted


Program will always run, it will just stop when it
separately by the CPU, which can lead to
finds a specific syntax error in the code
slower execution
Every time the program is run it has to be
It is easier to debug and understand where
translated, due to no instructions being
particular code has gone wrong
stored
Interpreters do not store instructions and are not
They cannot optimise code, it is
stored for later use, this means they require less
translated and executed as it is
RAM to process the code
IDE
An integrated development environment (IDE) is software that consolidates basic
tools required to write and test software to make a programmer's journey effective
and useful, this will ensure they have key features to improve programming code
and ensure it does as instruct. Some features are:
• Basic code formatting - changing the font, size of the font, making text bold
etc
• Coloured keywords in source code - e.g. Python code print, input etc turn
purple, if turns orange. This makes it easy to see keywords
• Code Editing - this will allow users to write and manipulate source code, it in-
cludes features such as auto-completion and auto-correction of code, bracket
matching, syntax checks etc
• Commenting code - this allows sections of code to be commented out easily
to stop it from being run or as comments on what the program is doing
• Identifying errors - highlight particular areas of code or provide direct error
messages where the error may have appeared e.g. indentation errors etc
• Run-Time environment - to allow the program to run and see its correspond-
ing output
• Debugger - this will identify and remedy errors within the source code. This
can provide a step through command also which provides step by step in-
structions and shows what is happening to the code line by line. This method
is amazing for catching logical errors
• Libraries - extra modules that are not included in the main programming lan-
guage e.g. math in Python for extra mathematical commands
• Graphical User Interface Builder - will create a graphical design rather than
working with source code
• Translator - which compiles or interprets the code
Exam Tip
• You could be asked to Identify or Describe different features within an Inte-
grated Development Environment (IDE) this number could range from 2-5
The internet
and
Its Uses
The internet and Its Uses
The Internet & WWW
The internet and the world wide web are often used interchangeably, but they
are not the same thing.

The Internet
• The internet refers to the global network of computers and other electronic
devices connected together through a system of routers and servers
• It is the infrastructure that allows us to send and receive information, includ-
ing email, instant messaging, and file transfers
• The internet also provides access to other services such as online gaming,
video streaming, and cloud computing

The World Wide Web


• The world wide web, or simply the web, is a collection of websites and web
pages that are accessed using the internet
• It was created in 1989 by Tim Berners-Lee, who envisioned it as a way to
share and access information on a global scale
• The web consists of interconnected documents and multimedia files that
are stored on web servers around the world
• Web pages are accessed using a web browser, which communicates with
web server to retrieve and display the content
URL
What is a URL?
• The URL is a text-based address that identifies the location of a resource on
the internet
• It is the address of a web page, image, video, or any other resource available
on the internet

Components of a URL
• A URL can contain three main components:
o Protocol
o Domain name
o Web page / file name
• The protocol is the communication protocol used to transfer data between
the client and the server
o E.g. HTTP, HTTPS, FTP, and others
• The domain name is the name of the server where the resource is located
o It can be a name or an IP address
• The web page / file name is the location of the file or resource on the server
o It can contain the name of the file or directory where the resource is
located
• A URL looks like this:
o protocol://domain/path
o E.g. https://www.example.com/index.html is a URL that consists of
the HTTPS protocol, the domain name "www.example.com", and the
file name is "/index.html".
Ip addresses
• Needed to send / receive data on a network
• Stands for Internet Protocol
• When packets of data are sent onto a network the network hardware looks
at the IP address to send the packet down a particular pathway
• Devices are assigned IP addresses by a DHCP server
• There are 2 types of IP address:
o Dynamic IP
▪ A divice is a allocated the next free IP address as seen below of
what your home wifiwould do

o Static IP
▪ When a device connects to a network, it always assigned the
same IP address
IP addresses + locations

This diagram above shows the different buildings in the school and their unique IP
addresses
Ip Location break down:
The diagram above shows how

• Restricting IP address allocation means you can stop devices from sending
malicious content
• The DHP server checks the MAC address of a connecting device and allocates
an IP address if it is not black listed
Protocols

Protocols – a rule / action that we follow when communicating over a network

Hypertext Transfer Protocol (HTTP) and Hypertext Transfer Protocol Secure (HTTPS)
are the two most common protocols used for transferring data between clients and
servers on the internet.

Hypertext Transfer Protocol (HTTP)


• HTTP is the protocol used for transferring data between a client and a
server on the internet
• It is a stateless protocol, meaning it does not store any information about
previous requests or responses
• HTTP operates on port 80 by default and sends data in plain text format,
making it vulnerable to interception and manipulation

Hypertext Transfer Protocol Secure (HTTPS)


• HTTPS is a secure version of HTTP that uses encryption to protect data trans-
ferred between a client and a server
• It operates on port 443 by default and uses Transport Layer Security (TLS) or
Secure Socket Layer (SSL) to encrypt data
• HTTPS ensures that data transferred between the client and server is secure,
making it harder for unauthorised users to intercept or manipulate data

SSL & TLS


• They both use a combination of symmetric and asymmetric encryption to se-
cure data and ensure data integrity
• SSL operates at the transport layer of the OSI model, ensuring that data is en-
crypted before it is sent over the network
• The TLS (transport layer security) protocol is made up of 2 layers:
o Handshake Layer
▪ This is used to establish a secure connection between two
endpoints
o Record Layer
▪ This is responsible for transmitting data securely between the
client and the server

• The client/browser requests secure connection to the server


• The client/browser requests the server to identify itself
• The server provides a digital certificate
• The client/browser validates the certificate
• The client/browser sends a signal back to the server to begin data transmis-
sion
• The encryption method will be agreed & a session key is generated
Describe the process of SSL and how it provides a secure connection (in case of
buying from an art gallery):
1. SSL is an security protocol
2. Encrypts the data that’s being sent
3. It uses digital certificates
a. Sent to the user’s browser
b. It contains the public key of the (seller)
c. Key used to authenticate the seller
4. One authenticated the purchase occurs

Requesting a webpage:
1. A user enters a URL into their web browser
2. URL for that website sent to the DNS
3. DNS searches database for equivalent IP, if not found the next one searches
its database, until it is found
4. DNS sends the IP back to the web browser, or returns 'Site not found'.
5. Browser sends request to the server associated with the IP address.
6. The protocol is HTTP
7. The server process request + sends back the webpage (HTML, CSS)
8. This is rendered the page is displayed in the browser

Exam Tip
YOU WILL ONLY BE ASKED TO NAME THE LAYERS OF TLS
Web Browser
A web browser is a piece of software used to access and display information on the
internet.

Purpose of a Web Browser


• The main purpose of a web browser is to render hypertext markup language
(HTML) and display web pages
• Web browsers interpret the code in HTML documents and translate it into a
visual display for the user

Functions of a Web Browser


• Render HTML
o This will display the webpage
• Storing bookmarks and favourites
o Web browsers allow users to save links to frequently visited websites
and access them easily using bookmarks or favourites
• Recording user history
o Web browsers record the user's browsing history, allowing them to
quickly revisit recently viewed pages
• Allowing use of multiple tabs
o Web browsers allow users to open multiple tabs and switch between
them quickly and easily
• Storing cookies
o Web browsers store cookies, which are small files that contain user
preferences and login information for websites
• Providing navigation tools
o Web browsers provide navigation tools, such as back and forward
buttons and a home button, to help users move between pages
• Providing an address bar
o Web browsers provide an address bar, which allows users to enter a
URL or search term and navigate to a website or search for
information
• Homepage
o This is the initial page that appears when the browser is launched
o The homepage can be customised to display frequently visited web-
sites or specific content
• Runs Active Scripts
o These are small programs embedded in web pages that allow interac-
tive content such as animations, videos, and pop-up windows to be
displayed
• Download Files
o A web browser allows files to be downloaded from the internet, such
as documents, images, and software
• Request Web Pages
o When you enter a web address in the address bar, the web browser
sends a request to the web server to obtain the contents of the web
page
o The server responds by sending the web page to the browser, which
displays it on the screen
• DNS
o The web browser sends the URL to the DNS, which translates the URL
into an IP address, which is used to locate the web server
• Manages Protocols
o Web browsers manage the HTTP and HTTPS protocols, which are used
to transfer data between web servers and browsers
o HTTP is used for regular web pages, while HTTPS is used for secure
pages that require encryption, such as online banking or shopping
sites
Web Pages

• When you type in a URL / click on a link the browser sends the URL to the
DNS using HTTP
• The DNS finds the matching IP addresses for the URL and sends the IP ad-
dress to the web browser
• The web browser sends a request to the web server for web pages
• The web pages are sent from the web server to the browser
• The browser renders HTML to display web pages
• Any security certificates are exchanged
• SSL/HTTPS is used to secure the data which will encrypt any data that is sent

Worked example
Describe how the web pages for the website are requested and displayed on a user’s
computer
[4]
• The browser sends the URL to the DNS [1]
• The DNS returns the IP address to the browser [1]
• The browser sends a request to the web server [1]
• The browser interprets and renders the HTML to display web pages [1]
Structure & Presentation
Websites can be separated into structure and presentation.
HTML is:
• A language used to create the structure/layout of a website
• Written in plain text
• Used in the content layer
• Made up of a set of markup codes
• Used to tell the browser how to display the page
E.g.
• Where text is placed
• Margins of page
• Line break
• Padding
CSS is:
• A language used to create the presentation / formatting of the page
• Written in plain text
• Used in the presentation layer
• Used by web pages to produce a consistent format between different web
pages
E.g.
• Font size
• Font colour
• Background colour
Why are they kept separately?
• The presentation of the page can be changed without needing to alter the
structure so regular updates can be made without needing to check the
structure
• The formatting document (written in CSS) can be used again for a different
website
• If further content and web pages are added to the website, the necessary for-
matting can be easily applied so this can save time when developing a web-
site
• CSS to standardise formatting so CSS only needs to be created once and be
applied to each webpage
• One person can develop the structure and one can develop the presentation
so this can save time when developing and updating a website

Exam Tip
• Make sure you know the definition for structure and presentation and know
at least one example of each
• You also need to have a greater understanding of the reasons for the separa-
tion of structure and presentation
Cookies

What are cookies?

Cookies are small files that are stored on a user's device by a website. They are used
for various functions, including:
• Saving Personal Details
o Cookies can save personal details which can be used to personalise
the user experience. This can include
▪ Name
▪ Email address
▪ Other preferences
• Tracking User Preferences
o Cookies can track user preferences such as language settings, font
size, and colour scheme, which can be used to customise the website
experience
• Holding Items in an Online Shopping Basket
o Cookies can hold items in an online shopping cart, so that users can
continue shopping or return later without losing their selected items
• Storing Login Details
o Cookies can store login details such as usernames and passwords,
which can be used to remember users' login credentials and make it
easier for them to log in
• Storing Relevant Purchases
• Displaying Relevant Adverts
• Tracking Visitor Statistics
o Determining whether a visitor to a website is a new visitor or repeat
visitor

There are two types of cookies: session cookies and persistent cookies.
• Session Cookies
o These are temporary and are stored only during a user's browsing ses-
sion
o They are used to maintain a user's state or activity during a single ses-
sion, such as when filling out a form or navigating through a website
• Persistent Cookies
o These are stored on a user's device for a longer period, usually for a
few weeks to several years
o They are used to remember user preferences and settings, such as
language preferences, login details, and shopping cart items

Cookies enhance the user experience and make it more convenient for users to in-
teract with websites. However, cookies can also raise privacy concerns and should be
used responsibly by website owners.
Digital Currency
Digital Currency

A digital currency is a type of currency that exists only in electronic form and is not
backed by any physical commodity or government.

• Only Exists Electronically


o Digital currencies are purely electronic, meaning they do not exist in
physical form like traditional currencies such as cash or coins. They
are stored in digital wallets or accounts and can be transferred elec-
tronically between individuals or businesses
• Decentralised
o Many digital currencies operate on a decentralised network; meaning
that they are not controlled by any central authority like a govern-
ment or financial institution
o Instead, transactions are verified and recorded on a public ledger
known as a blockchain
• Used for Transactions
o Digital currencies can be used for various transactions, including pur-
chasing goods and services online or transferring money internation-
ally
o They can also be used for investments or as a store of value
• Volatile
o Digital currencies can be highly volatile; meaning their value can fluc-
tuate rapidly over short periods of time
o This can make them risky investments and can also make it difficult to
use them as a stable store of value
• Examples include Bitcoin, Ethereum, Litecoin, and Ripple

Blockchain
• Blockchain is a digital ledger that records every transaction made with a par-
ticular digital currency
o Each transaction is time-stamped and added to the blockchain in a
permanent and unalterable way
• Blockchain is a decentralised technology, meaning that it is not controlled by
a single entity or authority
o Instead, every participant in the network has a copy of the ledger and
can verify the transactions independently
• The blockchain is made up of "blocks" of transactions that are linked together
in a "chain" using cryptographic algorithms
o This creates a secure and tamper-proof record of every transac-
tion made with the digital currency
• Each transaction in the blockchain must be verified by multiple partici-
pants in the network
o This verification process ensures that the transaction is legitimate
and prevents any fraudulent activity
Cyber Security
Cyber Security Threats

Cybersecurity threats pose a major challenge for individuals and organisations that
rely on digital technology to store and transmit sensitive information.
Brute-Force Attack

• A brute-force attack is a trial-and-error method used to crack passwords or


encryption keys by trying every possible combination until the correct one is
found
• The aim of a brute-force attack is to gain unauthorised access to a system or
network

Data Interception
• Data interception involves eavesdropping on communication channels to in-
tercept and steal sensitive information, such as passwords, credit card num-
bers, or personal data
• The aim of data interception is to steal sensitive information for personal gain
or to use it for further cyber attacks

Distributed Denial of Service (DDoS) Attack


• A DDoS attack is where multiple computers are used as bots
• They flood a server with lots of requests at the same time which the server
can’t respond to; causing it to crash or become unavailable to users
• The aim of a DDoS attack is to disrupt the normal functioning of a system or
network by denying users access

Hacking
• Hacking involves gaining unauthorised access to a system or network to steal
or manipulate data, disrupt services, or cause damage
• The aim of hacking can vary from personal gain to activism or cyber espio-
nage
Malware
Malware is malicious software designed to harm or gain unauthorised access to a
system or network. Types of malware include:
• A virus is a piece of code that attaches itself to a legitimate program or file
and then replicates itself to spread to other programs or files on the com-
puter. It can cause damage to the system, including deleting data or damag-
ing hardware
• A worm is similar to a virus but is a standalone program that can spread and
replicate itself over computer networks. It can take up storage space or band-
width
• A Trojan horse is a program that disguises itself as a legitimate program or
file, but when installed, it can delete data or damage hardware
• Spyware is software that records all key presses and transmits these to a
third party
• Adware is a type of software that displays unwanted advertisements on the
computer without the user's consent. Some of these may contain spyware
and some may link to viruses when clicked
• Ransomware is a type of malware that encrypts the user's files and demands
a ransom payment to decrypt them. It can cause data loss, and financial dam-
age and disrupt business operations
The aim of malware attacks can range from data theft to extortion or disruption of
services

Phishing
• Phishing involves the user is sent an email which looks legitimate
• This contains a link to a fake website where the user is encouraged to enter
their details
• The aim of phishing is to steal sensitive information for personal gain or to
use it for further cyber attacks

Pharming
• Pharming involves malware being downloaded without the user’s knowledge
• This redirects the user to a fake website where they’re encouraged to enter
their personal details
• The aim of pharming is to steal sensitive information for personal gain or to
use it for further cyber attacks

Exam Tip
• A user needs to click on a link or an attachment to open the fake web page or
trigger a download of malicious code, and not just open the email
Social Engineering
• Social engineering involves manipulating individuals to gain access to confi-
dential information or to perform an action that benefits the attacker
• This can include techniques such as:
o This involves posing as someone else to gain trust or access to sensi-
tive information
o Attackers might pretend to be a co-worker, IT support personnel, or a
law enforcement officer to get people to divulge sensitive information
or perform an action they wouldn't otherwise do
o Baiting is a social engineering technique that involves enticing a victim
with a desirable item or promise to extract sensitive information or
gain access to a system
o Attackers might leave a USB drive with a tempting label, like "salary
information," in a public place and wait for someone to pick it up and
plug it into a computer
o Once the drive is connected to the computer, the attacker can access
sensitive information or install malware
o Pretexting involves creating a fake scenario to extract sensitive infor-
mation
o The attacker might pose as a bank representative and ask for personal
information to "verify your account”
o Impersonation
o Baiting
o Pretexting
• The aim of social engineering is to exploit human behaviour and vulnerabili-
ties to gain unauthorised access to a system or network
Accidental Damage
Data could also be accidentally damaged in many ways:
Example Prevention
Loss of power Use a UPS
Liquids being spilt Don’t have water near the device
Keep device in a waterproof box when not
Flooding
is use
Use electrics safety and keep device in a
Fire
fireproof box when not is use
Hardware failure Correct care and maintenance of hardware
Software failure Making sure it is always up to date
Human error:
• Pressing delete by mistake Add verification method for data deletion
• Not saving data Set access levels for data to limit who can
• Not shutting down the computer delete the data
correctly
Making sure device is ejected before re-
Incorrect use of storage device
moving
Exam Tip
• If you are given context in a question, you should apply your answer to the
scenario
• Back-up of data is not a method to help prevent the data being damaged. It
can replace the data if it is damaged, but it does not stop the data being dam-
aged
Keeping Data Safe

Access Levels
• Access levels are used to restrict access to sensitive information to only au-
thorised personnel
• This helps to prevent unauthorised access, which is one of the main security
threats to data
• Access levels can be set based on a user's role, responsibility, or clearance
level
o This allows the user to open, create, edit & delete files
o This only allows the user to open files without editing or deleting
o This hides the file from the user
o Full access
o Read-only access
o No access

Anti-Virus
• Anti-malware solutions are used to prevent and remove malware, which is a
common type of security threat to data
• Anti-malware software includes anti-virus and anti-spyware programs, which
help to detect and remove malicious software from a computer system
• This software works by scanning the computer’s files and any files being
downloaded and comparing them to a list of known malware
• If any malware is found, it is quarantined to prevent the spread
• The malware is then deleted
Authentication
• Authentication is used to ensure that only authorised users can access data
• There are several methods of authentication:
o Passwords are used to protect sensitive data by preventing unauthor-
ised access. A strong password should be complex, unique, and not
easily guessed. Passwords should be changed regularly, and users
should avoid reusing passwords across multiple accounts.
o Biometrics uses biological data for authentication by identifying
unique physical characteristics of a human such as fingerprints, facial
recognition, or iris scans. Biometric authentication is more secure
than using passwords as:
▪ A biometric password cannot be guessed
▪ It is very difficult to fake a biometric password
▪ A biometric password cannot be recorded by spyware
▪ A perpetrator cannot shoulder surf to see a biometric pass-
word
o Two-factor authentication (2FA) requires users to provide two forms
of authentication before accessing data, such as a password and a
verification code sent to a mobile device. This provides an extra layer
of security and reduces the risk of unauthorised access. 2FA is widely
used to protect online accounts, such as email or banking.
• These methods help to prevent unauthorised access and protect sensitive
data
Automating Software Updates
• Automating software updates ensures that software systems are up-to-
date with the latest security patches, which helps to prevent security threats
• This is especially important for operating systems and software that are fre-
quently targeted by hackers
• It does this by scanning the Internet for known updates to software which
are installed on the computer
• If any updates are found, these can either install automatically or notify the
user to install them

Communications
• Checking the spelling and tone of communications is important to prevent
phishing attacks

URL
• Checking the URL attached to a link is another way to prevent phishing at-
tacks.
• Hackers often use fake URLs to trick users into visiting fraudulent websites
o e.g. http://amaz.on.co.uk/ rather than http://amazon.co.uk/
Firewalls
• A firewall can be software or hardware based
• It monitors incoming and outgoing traffic between the computer and the
network and keeps a log of the traffic
• The user sets criteria for the traffic (this is called the whitelist/blacklist) and
the traffic is compared with this
• The firewall will accept or reject the traffic based on this and an alert can be
sent to the user
• It can help prevent hacking and malicious software that could be a threat to
the security of the data

Privacy Settings
• Privacy settings are used to control the amount of personal information that
is shared online
• They are an important measure to prevent identity theft and other forms of
online fraud
• Users should regularly review their privacy settings and adjust them as
needed

Proxy-Servers
• Proxy-servers are used to hide a user's IP address and location, making it
more difficult for hackers to track them
• They act as a firewall and can also be used to filter web traffic by setting cri-
teria for traffic
• Malicious content is blocked and a warning message can be sent to the user
• Proxy-servers are a useful security measure for protecting against external
security threats as it can direct traffic away from the server

Secure Socket Layer


• SSL is a security protocol which is used to encrypt data transmitted over the
internet
• This helps to prevent eavesdropping and other forms of interception
• SSL is widely used to protect online transactions, such as those involving
credit card information or other sensitive data
• It works by sending a digital certificate to the user’s browser
• This contains the public key which can be used for authentication
• Once the certificate is authenticated, the transaction will begin

Physical Methods
o Physical methods are used to physically protect hardware that stores
sensitive data
o This can include:
▪ Locked rooms needing a key or card access
▪ CCTV
▪ Bodyguards
Backup
• This is the process of making a copy of files in case something happens to the
original ones
• Backing up data is important to protect against data loss due to hardware
failure, cyber-attacks, or other disasters
• Backups should be stored in a secure location, and multiple copies should be
made
• Regular backups ensure that data can be recovered in the event of a security
breach or data loss
Ethics
There are a number of ethical concerns when using the Internet:
• Addiction
o Aspects of the internet e.g. social media can cause this
• Breaching copyright
o Breaking the law by copying someone’s work
• Cyber bullying
o Using the internet to bully people
• Data protection
o A person’s data is not used according to the law
• Environmental effects
o Increased use of the internet increases the use of electrical power
• Fake news
o News stories that could be very misleading or harmful
• Inappropriate materials
o Materials that could cause harm/offence to people e.g. children
• Intellectual property theft
o Stealing other people's work
• Piracy
o Using piracy websites to gain content for free that should have been
paid for
• Plagiarism
o The copying of other people’s work without their permission
o Claiming someone else’s work as your own
• Privacy
o A person’s data could be leaked
Automated
and
Emerging
Technologies
Automated Systems
Automated Systems
• Automated systems use sensors, a microprocessor and actuators
o Sensors detect changes in the environment and convert them into
electrical signals that can be processed by a microprocessor
o Microprocessors analyse the signals from the sensors and make deci-
sions based on pre-programmed logic
o Actuators receive signals from the microprocessor and perform ac-
tions such as opening a valve or turning on a motor
• By combining sensors, microprocessors, and actuators, automated systems
can be created that respond to changes in the environment without human
intervention
Scenario Advantages Disadvantages
Industry • Reduced labour costs • High initial investment
• Improved efficiency and • Limited flexibility to changes in
accuracy production processes
• Increased production rate • Maintenance costs can be high
Transport • Improved safety and reli- • High initial investment
ability • May not be suitable for all
• Reduced labour costs types of transportation
• Improved fuel efficiency • Maintenance costs can be high
Agricul- • Increased efficiency in • High initial investment
ture planting and harvesting • May not be suitable for all
crops types of crops or terrain
• Improved crop yield and • Maintenance costs can be high
quality
• Reduced labour costs
Weather • Improved accuracy in • May be affected by external fac-
weather prediction tors like interference or equip-
• Ability to issue warnings ment failure
in a timely manner • May not be 100% accurate all
• Ability to collect large the time
amounts of data quickly • May require continuous
monitoring and calibration
Gaming • Improved speed and effi- • May not be suitable for all
ciency in game develop- types of games or game devel-
ment opment
• Ability to create complex • May require significant pro-
and interactive games gramming expertise
• Reduced labour costs • May be affected by technical
glitches or bugs
Lighting • Improved energy • High initial investment
efficiency • May not be suitable for all
• Ability to program lighting types of lighting needs
to suit different needs • Maintenance costs can be high
• Reduced labour costs
Science • Improved speed and • High initial investment
accuracy in data • May not be suitable for all
collection and analysis types of experiments
• Ability to carry out • May require significant
complex experiments technical expertise
• Reduced labour costs
Worked example
A theme park has a game where a player tries to run from the start to the finish
without getting wet. The system for the game uses sensors and a microprocessor to
spray water at a player as they run past each sensor. Describe how the sensors and
the microprocessor are used in this system

[8]
• A motion sensor collects analogue data [1]
• This data is converted to digital using ADC [1]
• The sensor sends data to the microprocessor [1]
• where the data is compared to stored data [1]
• If the value is outside range water will be sprayed [1]
• A signal is sent to the actuator to spray water [1]
• If the value is within range no action is taken [1]
• This runs in a continuous loop [1]

Exam Tip
THE WAY MARKS ARE AWARDED ON THESE QUESTIONS IS VERY SIMILAR.
MAKE SURE YOU RELATE YOUR ANSWER SPECIFICALLY TO THE SCENARIO IN
THE QUESTION
Robotics
Robotics
Robotics is an area of computer science that deals with the creation, design, and op-
eration of robots.
• Design and Construction:
o Robotics involves the design and construction of robots for various
applications
o Robots are designed using a combination of mechanical, electrical,
and computer engineering
o Robotic design can be customised to meet specific needs, such as fac-
tory automation or household tasks
• Operation:
o Once a robot is built, it needs to be programmed to carry out specific
tasks
o Programming involves creating a set of instructions that tell the robot
what actions to perform in a specific sequence
o The robot's sensors are used to detect and respond to changes in its
environment
o Robots can also be operated remotely using a controller
• Examples:
o Factory equipment: Robots perform tasks such as welding, painting,
and assembling products
o Domestic robots: These are robots designed to perform household
chores such as vacuuming or mowing the lawn
o Drones: Drones are unmanned aerial vehicles that can be used for
tasks such as aerial photography, delivery, and surveillance

Characteristics
• A robot is a machine that can be programmed to carry out a range of
tasks autonomously or semi-autonomously
• Robots have a mechanical structure or framework, which gives them a physi-
cal body that can move and interact with the environment
• Electrical components, such as sensors, microprocessors and actuators, allow
robots to receive information from their surroundings and respond to it
• Robots are programmable, which means they can be designed to follow a set
of instructions or algorithms, allowing them to complete a variety of tasks
and respond to changing situations
Roles
Robots can perform various tasks in different areas, such as:
• Industry
o Robots can be used in manufacturing and assembly lines to increase
productivity and accuracy
• Transport
o Robots can be used in warehouses and logistics to move
and transport goods
• Agriculture
o Robots can be used for tasks such as planting, harvesting, and spray-
ing crops
• Medicine
o Robots can be used in surgical procedures to increase precision and
reduce risk of errors
• Domestic
o Robots can be used for tasks such as vacuuming, lawn mowing, and
cleaning
• Entertainment
o Robots can be used as toys or in amusement parks to provide enter-
tainment

Advantages Disadvantages
Increased productivity: robots can High initial investment: purchasing
work continuously without breaks and setting up robots can be expen-
or fatigue sive
Consistency and accuracy: robots Maintenance costs: robots require
can perform tasks with a high level regular maintenance and repairs,
of precision and accuracy which can add to the overall cost.
Lack of flexibility: robots are pro-
Safety: robots can perform tasks
grammed for specific tasks and can-
that are dangerous or hazardous for
not adapt easily to new situations or
humans
tasks.
Unemployment: increased use of
Cost-effective: robots can help re-
robots can lead to job loss in certain
duce labour costs in the long run
industries.
Artificial Intelligence
AI
• Artificial Intelligence is a branch of computer science that involves creating
computer systems that can perform tasks that would normally require hu-
man intelligence
• The goal of AI is to simulate intelligent behaviour in machines, including:
o problem-solving, decision-making, natural language processing
• AI is often used in areas such as:
o Robotics
o Natural language processing
o Expert systems
o Machine learning
• Machine learning is a subset of AI that focuses on giving computers the abil-
ity to learn and improve from data, without being explicitly programmed
• There are different types of AI, including weak AI, strong AI, and superintelli-
gence
o Weak AI, also known as narrow AI, is designed to perform a specific
task or set of tasks
o Strong AI, also known as artificial general intelligence (AGI), is de-
signed to perform any intellectual task that a human can do
o Superintelligence is a hypothetical AI that would surpass human intel-
ligence in all areas
• AI has advantages such as increased efficiency, accuracy, and scalability
• However, AI also has disadvantages such as the potential for job loss, biassed
decision-making, and ethical concerns around its use

Characteristics
• Collection of data and rules
o AI systems require large amounts of data to perform tasks
o The data is processed using rules or algorithms that enable the sys-
tem to make decisions and predictions
• Ability to reason
o AI systems can use logical reasoning to evaluate information
and make decisions based on that information
• Ability to learn and adapt
o This will mean it can change its own rules and data
AI systems can be designed to learn from past experiences and adjust their behav-
iour accordingly.
Components
There are two main types of AI systems:
Expert Systems:
• Have a knowledge base
o A database of facts to generate rules that are used to solve problems
and make decisions
• Have a rule base
o A set of rules or logic that is used to apply the knowledge in the
knowledge base to specific problems
• Have an inference engine
o A program that applies the rules in the rule base to the facts in the
knowledge base to solve problems
• Have an interface
o A way for users to interact with the system and provide input
Machine Learning:
• The program has the ability to automatically adapt its own processes and/or
data
• Uses algorithms to analyse data and identify patterns or relationships
• The system can learn from the data and improve its performance over time
• Can be supervised or unsupervised:
o Supervised machine learning uses labelled data to train the system
o Unsupervised machine learning uses unlabelled data
Algorithm
design
and
problem
solving
Development Life Cycle
Abstraction
This is the act of removing unimportant details of the problem to focus on important
elements. An example of abstraction would be the London underground train route
map; travellers do not need to know the geographical layout of the routes, only that
getting on at stop A will eventually transport you to stop B

Figure 1: London Underground train route map


Figure 2: The geographical London underground train map
Requirements
• Identification of the problem: Before tackling a problem, it needs to be
clearly understood by everyone working on it. The overall goal of the solution
needs to be agreed as well as any constraints such as limited resources or re-
quiring a platform specific solution
• Requirements: To create a solution, a requirements document is created to
define the problem and break it down into clear, manageable, understanda-
ble parts by using abstraction and decomposition. A requirements document
labels each requirement, gives it a description as well as success criteria
which state how we know when the requirement has been achieved
Program Development Life Cycle - Design
Decomposition
• This is the act of breaking down a large problem into smaller, clear, managea-
ble and understandable sub-parts. Sub-parts can be divided until they are
easily solvable and cannot be broken down any further. An example of de-
composition could be getting ready in the morning to go to school
o Step 1: Wake up
o Step 2: Get breakfast
o Step 3: Brush teeth
o Step 4: Put clothes on
o Step 5: Make sure the bag and school supplies are ready
o Step 6: Find transport to school e.g. walk, bus, car, bike, etc

• These steps could be further subdivided, for example, “Step 2: Get breakfast”
would entail:
o Step 2.1 Get a bowl
o Step 2.2 Get cereal
o Step 2.3 Get milk
o Step 2.4 Get a spoon
o Step 2.5 Put cereal in a bowl
o And so on…

• Once the requirements document has been created, developers need to de-
sign the structure and algorithms to solve the problem:
o Structure charts are created to show the breakdown of tasks in a hier-
archy
o Flowcharts may be created to visually show how tasks should be car-
ried out
o Pseudocode is created, sometimes from flowcharts, to allow program-
mers to easily translate task instructions into programming code

• The design of a solution identifies what tasks need completing, how to com-
plete the tasks and how each task works together with other tasks

• A computer system includes several components that work together: soft-


ware, hardware, data, networking and people
• Systems can be broken down into sub-systems that can be further broken
down into more sub-systems, until each sub-system has a single purpose.
This decomposition is known as top-down design
Decomposing a system
• To create an overall system and solve a problem, it must first be broken
down into subsystems that are easier to solve and create. The act of breaking
down the problem is known as stepwise refinement
• Decomposing the problem this way creates smaller, more manageable and
more easily understandable sub-parts
• Each sub-system can be assigned to a developer or group of developers who
create subroutines from these sub-systems. Each sub-system can then be cre-
ated at the same time, reducing development and testing time, especially on
large projects
• Decomposing the system using stepwise refinement requires developers to
think about four key areas:
o Inputs: data entered into the system
o Processes: subroutines and algorithms that turn inputs and stored
data into outputs
o Outputs: data that is produced by the system, such as information on
a screen or printed information
o Storage: data that is stored on a physical device, such as on a hard
drive
• To solve a problem all aspects must be thoroughly understood by the devel-
opers
• There are many methods used to design and construct solutions. Three such
methods are illustrated below:
Structure Diagrams
• Structure diagrams show hierarchical top-down design in a visual form. Each
problem is divided into sub-problems and each sub-problem divided into fur-
ther sub-problems. At each level the problem is broken down into more de-
tailed tasks that can be implemented using a single subroutine

Figure 1: A structure diagram

Figure 2: A structure diagram for a mobile application


Worked example
A satellite navigation system is an example of a computer system that is made up of
subsystems. Part of a satellite navigation system: allows the user to enter details for
a new destination or select a previously saved destination and displays directions in
the form of a visual map or as a list. Draw a structure diagram for this part of the sat-
ellite navigation system.
[4]
• [1] for a hierarchical structure
• [1] for suitable names for the sub-systems
• [1] for identifiable inputs
• [1] for identifiable outputs

Flowcharts
• Flowcharts show how algorithms can be represented visually in a diagram-
matic format
• Each flowchart has a start and an end with arrows showing the order each
task or instruction needs to be carried out in
• Flowcharts are made of several symbols:
o Terminator symbols: Also known as Begin/End symbols. These indi-
cate where a flowchart starts and stops
o Process symbols: These show simple actions being performed such as
assigning values or performing arithmetic operations on values
▪ Processes can also represent other flowcharts or summarised
actions. For example, searching or sorting a list is a complex
process which would require its own flowchart. A process sym-
bol could be used to represent sorting or searching in a sepa-
rate flowchart. This is represented by a process with an addi-
tional bar on either side of the symbol
o Input/Output symbols: These show the input of data and output of
data
o Decision symbols: These symbols are used to decide whether to take
one of two routes by answering a true/false or yes/no question. They
can be used for selection and iteration
o Flow lines: Flow lines use arrows to show the direction of flow and
what task to perform next. Usually these are top to bottom and left to
right
Figure 3: Flowchart symbols: terminator, input/output, process, decision (left to
right)
Figure 4: Flowchart for finding the largest of ten numbers
Pseudocode
• Pseudocode is a programming-like language that does not have syntax. It can
be considered “fake” code.
• It uses english words and phrases to represent instructions and is very similar
to programming code but does not and cannot run on any computer
• The purpose of pseudocode is to allow developers to understand how to cre-
ate a program regardless of the programming language used to implement
the solution
• While pseudocode has no specific syntax, it is important to stick to a con-
sistent style. This will make it easier and quicker for programmers to read and
create programs from the pseudocode
o Examples of a consistent style can include:
▪ Keywords are written in capital letters e.g. INPUT, OUTPUT, IF,
THEN, ELSE
▪ Variable and subroutine names start with capital letters e.g.
Age, Name, Date, Calculate Area, Shortlist
▪ Indentation can be used for iteration and selection
Program Development Life Cycle – Coding
• Developers begin programming modules in a suitable programming language
that works together to provide an overall solution to the problem
• As each developer programs, they perform iterative testing. Iterative testing
is where each module is tested and debugged thoroughly to make sure it in-
teracts correctly with other modules and accepts data without crashing or
causing any errors. Developers may need to retest modules as new modules
are created and changed to make sure they continue to interact correctly and
do not cause errors
Program Development Life Cycle - Testing
• Once the overall program or set of programs is created, they are run many
times using varying sets of test data. This ensures the program or programs
work as intended as outlined in the initial requirements specification and de-
sign and rejects any invalid data that is input
• Examples of test data include alphanumeric sequences to test password vali-
dation routines. Such validation routines could be:
o A password must be between 8-20 characters
▪ Test data would be passwords of less than 8 characters or
greater than 20 characters
o A password must include only alphanumeric characters
▪ Test data would be passwords including non-alphanumeric
symbols such as @, ?, #, !, $ or %, etc
Algorithms
Explaining Algorithms
• Algorithms can be written using flowcharts, pseudocode or high-level pro-
gramming language code such as Python
• The purpose of an algorithm is to achieve some goal. It isn’t always initially
clear what the goal may be. By following the algorithm instructions, the pur-
pose can become clear
Exam Tip
• Comments in an algorithm or program usually describe why something has
been done or provide useful information to the reader. Each line of code
should otherwise be self-explanatory
• The purpose of the algorithm below is to add ten user-entered numbers to-
gether and output the total. The processes are:
o initializing three variables (Count, Number, Total)
o inputting a user number
o adding to two variables (Total, Count)
o repeating nine more times
o outputting the final Total value
Count ← 1
Number ← 0
Total ← 0
REPEAT
INPUT Number
Total ← Total + Number
Count ← Count + 1
UNTIL Count > 10

OUTPUT Total
Worked example
The Pseudocode Algorithm shown has been written by a teacher to enter marks for
the students in her class and then to apply some simple processing.
Count ← 0
REPEAT
INPUT Score[Count]
IF Score[Count] >= 70
THEN
Grade[Count] ← "A"
ELSE
IF Score[Count] >= 60
THEN
Grade[Count] ← "B"
ELSE
IF Score[Count] >= 50
THEN
Grade[Count] ← "C"
ELSE
IF Score[Count] >= 40
THEN
Grade[Count] ← "D"
ELSE
IF Score[Count] >= 30
THEN
Grade[Count] ← "E"
ELSE
Grade[Count] ← "F"
ENDIF
ENDIF
ENDIF
ENDIF
ENDIF
Count ← Count + 1
UNTIL Count = 30
Describe what happens in this algorithm.
[3]
Any 3 of:
• Inputted marks are stored in the array Score[] [1]
• Marks are then checked against a range of boundaries [1]
• A matching grade is assigned to each mark that has been input [1]
• The grade is then stored in the array Grade[] [1]
• At the same index as the inputted mark [1]
• The algorithm finishes after 30 marks have been input [1]
Standard methods
Linear Search
• The linear search is a standard algorithm used to find elements in an unor-
dered list. The list is searched sequentially and systematically from the start
to the end one element at a time, comparing each element to the value being
searched for
o If the value is found the algorithm outputs where it was found in the
list
o If the value is not found it outputs a message stating it is not in the list
• An example of using a linear search would be looking for a specific student
name in a list or searching for a supermarket item in a shopping list

OUTPUT “Enter a value to find”


INPUT Number
Found ← FALSE
Index ←1

REPEAT
IF Number = Mylist[Index]
THEN
Found ← TRUE
ELSE
Counter ← Counter + 1
ENDIF
UNTIL Found =TRUE OR Counter > LENGTH(Mylist)

IF Found = TRUE
THEN
OUTPUT Number, “ found at position “, Counter
ELSE
OUTPUT Number, “ not found”
ENDIF
Bubble Sort
• Bubble sort sorts items into order, smallest to largest, by comparing pairs of
elements and swapping them if they are out of order
• The first element is compared to the second, the second to the third, the
third to the fourth and so on, until the second to last is compared to the last.
Swaps occur if each comparison is out of order. This overall process is called a
pass
• Once the end of the list has been reached, the value at the top of the list is
now in order and the sort resets back to the start of the list. The next largest
value is then sorted to the top of the list
• More passes are completed until all elements are in the correct order
• A final pass checks all elements and if no swaps are made then the sort is
complete
• An example of using a bubble sort would be sorting into alphabetical order an
array of names, or sorting an array of student marks from a test
Mylist ← [5, 9, 4, 2, 6, 7, 1, 2, 4, 3]
FirstElement ← 1
LastElement ← LENGTH(Mylist)
REPEAT
Swap ← FALSE
For Index ← FirstElement TO LastElement - 1
IF Mylist[Index] > Mylist[Index + 1]
THEN
Temp ← Mylist[Index]
Mylist[Index] ← Mylist[Index + 1]
Mylist[Index + 1] ← Temp
Swap ← TRUE
ENDIF
NEXT Index
LastElement ← LastElement - 1
UNTIL Swap = FALSE OR LastElement = 1
OUTPUT “Your sorted list is:”, Mylist
Totalling & Counting
Totalling
• Totalling involves keeping a running total of values entered into the algo-
rithm. An example may be totalling a receipt for purchases made at a shop
• The Total below starts at 0 and adds up the user inputted value for each item
in the list. For example, if the user has a receipt for four items: an apple
(£0.50), a drink (£1), a sandwich (£2) and a bar of chocolate (£1). The algo-
rithm will total the cost for each item one at a time. The output Total will be
4.50
Total ← 0
FOR Count ← 1 TO ReceiptLength
INPUT ItemValue
Total ← Total + itemValue
NEXT Count
OUTPUT Total

Counting
• Counting works similarly to totalling except the count is incremented or dec-
remented by a fixed value, usually 1, each time it iterates. Counting keeps
track of the number of times an action has been performed. Many algorithms
use counting, including the linear search and binary search to track which ele-
ment is currently being considered
• The count is incremented and each pass number is output until fifty outputs
have been produced
Count ← 0
DO
OUTPUT “Pass number”, Count
Count ← Count + 1
UNTIL Count >= 50
• The count is decremented from fifty until the count reaches zero. An output
is produced for each pass
Count ← 50
DO
OUTPUT “Pass number”, Count
Count ← Count - 1
UNTIL Count <= 0
Maximum, Minimum & Average
• Finding the largest and smallest values in a list is a frequently used method in
algorithms. Examples could include the maximum and minimum student
grades or scores in a game
Max ← Score[1]
Min ← Score[1]

FOR Count ← 2 TO ScoreSize


IF ScoreSize[Count] > Max
THEN
Max ← ScoreSize[Count]
ENDIF
IF ScoreSize[Count] < Min
THEN
Min ← ScoreSize[Count]
ENDIF
Next Count

• In the above algorithm, the initial max and min are set to the first value in the
list and the for loop starts at the second element instead of the first as the
first value is the benchmark to compare all other items to
• If no value is larger than the initial max, then Max doesn’t change. If no value
is smaller than the initial min, then Min doesn’t change
• The algorithm loops over each element asking whether the current value is
larger than Max and whether it is smaller than Min. Max and Min adjust their
values throughout the program depending on these conditions
• The program will eventually output the smallest and largest value in Min and
Max respectively
• Average values (also known as the mean) involve totalling all the list values
and then dividing by the number of values in the list
Total ← 0
FOR Count ← 1 TO ScoreSize
Total ← Total + ScoreSize[Count]
NEXT Count
Average ← Total / ScoreSize
Validation and Testing
Validation
• Validation and verification are used to ensure input data is correct, reasona-
ble and accurate
• Validation generally is about making sure data follows a set of specified rules
created by the programmer. Verification is about double-checking input data
to make sure it's what the user intended to enter
Validation
• Validation is the method of checking input data so that it is of an expected
value and therefore accepted by the system
• Programmers create rules using code that automatically checks user input
data to make sure the data is reasonable. If it is not reasonable then the data
is rejected, usually with a message explaining why it was rejected and allow-
ing the user to re-enter the data
• The different types of validation rules or checks are as follows:
o Range checks
o Length checks
o Type checks
o Presence checks
o Format checks
o Check digits
• Each piece of data may require multiple different checks to be fully valid

Range check
• Range checks make sure the input data is a value between a user-defined
minimum and maximum value, for example, a percentage being between 0
and 100 inclusive or a date in April is between 1 and 30 inclusive
OUTPUT “Enter a number between 0 and 100”
REPEAT
INPUT Number
IF Number < 0 OR Number > 100
THEN
OUTPUT “Number is not between 0 and 100, please try again”
ENDIF
UNTIL Number >= 0 AND Number <= 100
Length check
• Length checks check either that the input data is of an exact number of char-
acters or in a user specified number range of characters
• A bank 4-digit PIN number may be an example of an exact number of charac-
ters. If it is not 4 digits in length it should be rejected
OUTPUT “Please enter your 4 digit bank PIN number”
REPEAT
INPUT Pin
IF LENGTH(Pin) <> 4
THEN
OUTPUT “Your pin number must be four characters in length,
please try again”
ENDIF
UNTIL LENGTH(Pin) = 4
• Passwords usually have a specified range, for example, eight to twenty char-
acters in length. If it does not fall within this range, it should be rejected
OUTPUT “Please enter a password between 8 and 20 characters”
REPEAT
INPUT Password
IF LENGTH(Password) < 8 OR LENGTH(Password) > 20
THEN
OUTPUT “Your password must be between 8 and 20 charac-
ters in length, please try again”
ENDIF
UNTIL LENGTH(Password) >= 8 AND LENGTH(Password) <= 20
Type checks
• Type checks make sure the input data is of the correct data type. For exam-
ple, someone's age should be an integer (a whole number) whereas their
name should be a string (a bunch of characters)
OUTPUT “Enter an integer number”
REPEAT
INPUT Number
IF Number <> DIV(Number, 1)
THEN
OUTPUT “Not a whole number, please try again”
ENDIF
UNTIL Number = DIV(Number , 1)
Presence check
• Presence checks make sure that input data has been entered and that the in-
put box has not been left empty
• A login system requires presence checks as both a username and password
are required for authentication
OUTPUT “Enter your username”
REPEAT
INPUT Username
IF Username = “”
THEN
OUTPUT “No username entered, please try again”
ENDIF
UNTIL Username <> “”

Format check
• Format checks make sure that input data is of a predefined pattern
• Identification codes e.g. AP1234 and dates are examples of patterns
• Format checks are done using pattern matching and string handling
• The algorithm below checks a six digit identification number against the for-
mat “XX9999” where X is an uppercase alphabetical letter and 9999 is a four
digit number
• The first two characters are checked against a list of approved characters.
The first character is compared one at a time to each valid character in the
ValidChars array. If it finds a match it stops looping and sets ValidChar to
True. The second character is then compared one at a time to each valid
character in the ValidChars array. If it finds a match then it also stops looping
and sets ValidChar to True
• Casting is used on the digits to turn the digit characters into numbers. Once
the digits are considered a proper integer they can be checked to see if they
are in the appropriate range of 0-9999
• If any of these checks fail then an appropriate message is output
INPUT IDNumber
IF LENGTH(IDNumber) <> 6
THEN
OUTPUT “ID number must be 6 characters long”
END IF
ValidChars ← “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
FirstChar ← SUBSTRING(IDNumber, 1, 1)
ValidChar ← False
Index ← 1
WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO
IF FirstChar = ValidChars[Index]
THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False
THEN
OUTPUT “First character is not a valid uppercase alphabetical charac-
ter”
ENDIF
SecondChar ← SUBSTRING(IDNumber, 2, 2)
ValidChar ← False
Index ← 1
WHILE Index <= LENGTH(ValidChars) AND ValidChar = False DO
IF SecondChar = ValidChars[Index]
THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False
THEN
OUTPUT “Second character is not a valid uppercase alphabetical char-
acter”
ENDIF
Digits ← INT(SUBSTRING(IDNumber, 3, 6))
IF Digits < 0000 OR Digits > 9999
THEN
OUTPUT “Digits invalid. Enter four valid digits in the range 0000-9999”
ENDIF
Check digits
• Check digits are numerical values that are the final digit of a larger code such
as a barcode or an International Standard Book Number (ISBN). They are cal-
culated by applying an algorithm to the code and are then attached to the
overall code
• Check digits help to identify errors in data entry such as mistyping, miscan-
ning or misspeaking
o Such errors include missing or additional digits, swapped digits, mis-
pronunciation of digits or simply an incorrect digit
Barcode ← “9780201379624”
Total ← 0
FOR Index = 1 to LENGTH(Barcode) - 1
IF Index MOD 2 = 0
THEN
Total ← Total + CAST_TO_INT(Barcode[Index])*3
ELSE
Total ← Total + CAST_TO_INT(Barcode[Index])*1
ENDIF
NEXT Index
CheckDigit ← 10 - Total MOD 10

IF CheckDigit = Barcode[LENGTH(Barcode)]
THEN
OUTPUT “Valid check digit”
ELSE
OUTPUT “Invalid check digit”
ENDIF
Verification
• Verification is the act of checking data is accurate when entered into a sys-
tem
• Mistakes such as creating a new account and entering a password incorrectly
mean being locked out of the account immediately
• Verification methods include: double entry checking and visual checks

Double entry checking


• Double entry checking involves entering the data twice in separate input
boxes and then comparing the data to ensure they both match. If they do
not, an error message is shown
REPEAT
OUTPUT “Enter your password”
INPUT Password
OUTPUT “Please confirm your password”
INPUT ConfirmPassword
IF Password <> ConfirmPassword
THEN
OUTPUT “Passwords do not match, please try again”
ENDIF
UNTIL Password = ConfirmPassword

Visual check
• Visual checks involve the user visually checking the data on the screen. A
popup or message then asks if the data is correct before proceeding. If it isn’t
the user then enters the data again
REPEAT
OUTPUT “Enter your name”
INPUT Name
OUTPUT “Your name is: “, Name, “. Is this correct? (y/n)”
INPUT Answer
UNTIL Answer = “y”
Worked example
Describe the purpose of validation and verification checks during data entry. Include
an example for each.
[4]
Validation check
[1] for description:
• To test if the data entered is possible / reasonable / sensible
• A range check tests that data entered fits within specified values
[1] for example:
• Range / length / type / presence / format
Verification check
[1] for description:
• To test if the data input is the same as the data that was intended to be input
• A double entry check expects each item of data to be entered twice and com-
pares both entries to check they are the same
[1] for example:
• Visual / double entry
Test Data
Suggesting and applying suitable test data
• Before a system is used, each sub-system must be tested to ensure it works
correctly and interacts correctly with other sub-systems
• Programs are tested by running them on a computing device while pseudo-
code and flowcharts must be dry run manually. Both require suitably chosen
and different sets of test data. The outputs are then compared to the ex-
pected output to check if the algorithm works as intended
• Test data comes in several generic types:
o Normal
▪ Normal test data is data that a system would be expected to
handle on a day-to-day basis, be accepted by the algorithm
and produce expected results
▪ Examples could include entering people's names and ad-
dresses, phone numbers, student grades as a percentage, etc
▪ Student percentage grades could involve test data such as: 34,
41, 56, 78, 12, 92
o Abnormal
▪ Also known as erroneous data, abnormal data is data that is
expected to fail and should be rejected by the system. This is
used to prove that the system works correctly by rejecting in-
correct data
▪ Examples of abnormal data would be entering numbers in-
stead of someone's name, or entering text instead of numbers
▪ Student percentage grades abnormal data could involve test
data such as: abc, 7&n, Harry, £300, <!%, etc
o Extreme
▪ Extreme test data is the maximum and minimum values of
normal data that are accepted by the system
▪ Examples could include percentages (0 and 100), days in April
(1 and 30) or the number of characters in a passwords range
▪ For an 8-20 character range password, a password of 8
characters and another of 20 characters would be
tested
o Boundary
▪ Boundary test data is similar to extreme data except that the
values on either side of the maximum and minimum values are
tested
▪ The largest and smallest acceptable value is tested as well as
the largest and smallest unacceptable value
▪ For example, a percentage boundary test would be 0 and -1
(for 0) and 100 and 101 (for 100). For the days in April, 1 and 0
(for day 1) and 30 and 31 (for day 30) would be tested. For an
8-20 length password, an 8 and 7 character password would
be tested as well as a 20 and 21 character password

Worked example
A programmer has written an algorithm to check that prices are less than $10.00
These values are used as test data: 10.00 9.99 ten
State why each value was chosen as test data.
[3]
10.00 is boundary or abnormal data and should be rejected as it is out of range [1]
9.99 is boundary, extreme and normal data and should be accepted as it is within the
normal range [1]
Ten is abnormal data and should be rejected as it is the wrong value type [1]
Trace Tables
• Trace tables are used to follow algorithms and make sure they perform the
required task correctly. Test data is usually used in conjunction with a trace
table to ensure the correctness of the algorithm. Manually tracing an algo-
rithm with test data in this way is known as a dry run
• Trace tables can be used with flowcharts or pseudocode or even real code if
necessary
• Trace tables can also be used to discover the purpose of an algorithm by
showing output data and intermediary steps
• Trace tables record the state of the algorithm at each step or iteration. The
state includes all variables that impact the algorithms output as well as the
output itself
• A trace table is composed of columns where each variable and the output is a
column
• Whenever a value changes or an output is produced the relevant column and
row is updated to reflect the change
Trace Table Walkthrough
• Below is a flowchart to determine the highest number of ten user entered
numbers
• The algorithm prompts the user to enter the first number which automati-
cally becomes the highest number entered
• The user is then prompted to enter nine more numbers. If a new number is
higher than an older number then it is replaced
• Once all ten numbers are entered, the algorithm outputs which number was
the highest
• Example test data to be used is: 4, 3, 7, 1, 8, 3, 6, 9, 12, 10
Figure 1: A flowchart to determine the highest of ten user entered numbers

Trace table for Figure 1: Highest number


High- Num-
Count Output
est ber
1 Enter ten numbers

4 Enter your first number

2 3 Enter your next number

3 7 7

4 1

5 8 8

6 3

7 6

8 9 9

9 12 12
12 is your highest num-
10 10
ber
Exam Tip
• When asked to identify the purpose of an algorithm in the exam, the varia-
bles listed will often be a single letter rather than a meaningful identifier
Worked example
The flowchart represents an algorithm. The algorithm will terminate if –1 is entered.

Complete the trace table for the input data: 50, 75, 99, 28, 82, 150, –1, 672, 80

[4]
Value Diff1 Diff2 Output

[1] for each correct column


Value Diff1 Diff2 Output
50 50 0 Accept: Extreme
75 25 25 Accept: Normal
99 1 49 Accept: Normal
28 Reject: Abnormal
82 18 32 Accept: Normal
150 Reject: Abnormal
-1
Identifying Errors
Identifying Errors
Errors can be identified in algorithms using trace tables as well as scanning and de-
bugging code manually
Two types of errors are as follows:
• Syntax error
▪ Syntax refers to the grammar of language, that is, are the
words in the right order and is everything spelled correctly
▪ Unlike programs written on computers, syntax errors in
flowcharts and pseudocode do not cause the algorithm to fail
however they do make the code more difficult to read and un-
derstand
▪ Transcribing flowcharts and pseudocode to real programming
code may cause problems if it is difficult to read and under-
stand said flowcharts and pseudocode
• Logical error
o Logical errors occur when the program finishes but produces the
wrong output during or after
o Flowcharts and pseudocode, unlike real programs, do not crash when
dry run, however may still produce logic errors by producing incorrect
output
o Logical errors are the most difficult error to fix as developers must re-
consider their logic and processes. If they do not understand the
problem they cannot produce an accurate solution
• Below is an algorithm that asks the user to enter their age to determine what
rated movie they could watch at the cinema
• There are syntax and logical errors with this pseudocode
OUTPUT Age
INPUT “Enter an age”
IF Age > 18
THEN
OUTPUT “You can watch an 18 movie”
ELSE
IF Age > 15
THEN
OUTPUT “You can watch a 15 movie
ELSE
IF Age > 12
THEN
OUTPUT “You can watch a 12 movie”
ELSE
IF Age < 9
THEN
OUTPUT “You can watch a PG movie”
ELSE
OUTPUT “You can watch a U movie”
END IF
ENDIF
• Syntax and logic: OUTPUT Age and INPUT “Enter an age” are both syntax and
logical errors
o Syntax: Age does not yet have a value so OUTPUT cannot display it
while INPUT does not have a variable to store the data as strings can-
not store data
o Logical: Both are the wrong way around. OUTPUT Age should be OUT-
PUT “Enter an age” and INPUT “Enter an age” should be INPUT Age
• Syntax: THEN is missing from the first IF statement
• Syntax: A quote is missing from the OUTPUT “You can watch a 15 movie”
• Logic: Age < 9 should be Age > 9 so that it follows the other IF statement logic
• Syntax: ENDIF is missing from the first IF statement

Worked example
1. An algorithm has been written in pseudocode to input some numbers. It only
outputs any numbers that are greater than or equal to 100. The number 999
is not output and stops the algorithm.
INPUT Number
WHILE Numbers <> 999 DO
IF Number > 100
THEN
OUTPUT Number
ENDIF
ENDWHILE
OUTPUT Number

(a) Identify the four errors in the pseudocode and suggest corrections.
[4]
Numbers should be Number [1]
IF Number > 100 should be IF Number >= 100 [1]
INPUT Number is missing from inside the loop, insert INPUT Number after the ENDIF
statement [1]
The final OUTPUT Number is not needed, remove it [1]
(b) Write a pseudocode statement to change the corrected algorithm to output all
numbers between 100 and 200 inclusive. You do not need to rewrite the whole algo-
rithm
[2]
[1] for both ends of the range and correct inequality symbols
[1] for the AND

IF Number >= 100 AND Number <= 200


THEN
OUTPUT Number
ENDIF
Writing & Amending Algorithms
• To create algorithms for a given problem several stages must be followed:
1. The problem must be sufficiently analysed and understood. The require-
ments and purpose of the algorithm must be clearly stated
2. The problem must be sufficiently decomposed into sub-problems. A complex
problem may require many sub-problems with each sub-problem requiring
their sub-problems and algorithms. When determining an algorithm for a
sub-problem developers need to consider inputs, outputs, processes and long
term data storage (if necessary)
3. Consideration must be given to how data is going to be gathered, stored and
processed as well as how output is going to be displayed to the user
o For example, will data be entered via input boxes or file upload/open-
ing? Is data to be stored in a file? What overall processes will be per-
formed on the data? Will the data be displayed on a form, a web page
or output into a file?
4. The structure of the problem and subproblems should be illustrated by creat-
ing a structure diagram which details the breakdown and hierarchy of sub-
problems
5. Once each sub-problem is specified, an algorithm can be created using
flowcharts or pseudocode. The algorithm should be clear, easy to read and as
simple as possible
o Meaningful variable names help readers understand what data is be-
ing stored and their purpose
o Mathematical symbols such as “=” or “<=” are quicker and simpler to
read than “equal to “ or “less than or equal to”. “Percentage < 0 OR
Percentage > 100” is clearer than “Percentage under zero or Percent-
age over one-hundred”. Be concise
6. Sets of predetermined test data should be dry run on the algorithm, including
normal, abnormal, extreme and boundary data. The results should be dis-
played in a trace table, with clear outputs to allow errors to be detected
7. Encountered errors should be fixed and the algorithm retested to make sure
it functions as intended
Exam Tip
• Writing algorithms in an exam can be challenging and time consuming. It's
important to allocate your time carefully to not spend too little or too long
writing an algorithm
• You will likely make mistakes and rewrite your algorithm a few times. Use
scrap paper or the back of your exam paper if possible to sketch out your
ideas before committing to your answer. This will make your answer clearer,
neater and easier to read, follow and understand
• You may wish to chunk your algorithm into parts initially, for example, “This
part will enter the grades”, “this part will calculate the total”, and “This part
will allocate grades”. You can then put the whole algorithm together in order
later
• Make a plan before you start answering the question and writing your algo-
rithm. A plan can be simple but allows you to order your thoughts, for exam-
ple:
o Part 1: Declare and initialise variables
o Part 2: Allocate marks for each subject
o Part 3: Allocate grades for each student's subject
o Part 4: Include a loop
o Part 5: Output all necessary data
• Pseudocode does not have a syntax, therefore you can write an algorithm in
any way which is easily understandable. Caution is advised to stick to iGCSE
specification standards to ensure your answer is consistent and easy for ex-
aminers to follow
• Be sure to use variable names and data provided in the question as given.
Failure to do so will lose you marks
• Remember to comment on your code. It helps both you and the examiner un-
derstand your answer and also awards marks in the mark scheme!
Programming
Programming Concepts
Data Types
• A data type is a classification of data into groups according to the kind of data
they represent
• Computers use different data types to represent different types of data in a
program
• The basic data types include:
o Integer: used to represent whole numbers, either positive or negative
▪ Examples: 10, -5, 0
o Real: used to represent numbers with a fractional part, either positive
or negative
▪ Examples: 3.14, -2.5, 0.0
o Char: used to represent a single character such as a letter, digit or
symbol
▪ Examples: 'a', 'B', '5', '$'
o String: used to represent a sequence of characters
▪ Examples: "Hello World", "1234", "@#$%
o Boolean: used to represent true or false values
▪ Examples: True, False
We can declare variables as follows:

Python Java Visual Basic

Syn- variable_name data_type varia- Dim variable_name As


tax = value ble_name; data_type
Ex-
am- x=5 int x Dim x As Integer
ple
It is important to choose the correct data type for a given situation to ensure accu-
racy and efficiency in the program.
Worked example
Name and describe the most appropriate programming data type for each of the ex-
amples of data given. Each data type must be different
[6]
Data: 83
Data type name: Integer [1]
Data type description: The number is a whole number [1]

Data: myemail@savemyexams.co.uk
Data type name: String [1]
Data type description: It is a group of characters [1]

Data: True
Data type name: Boolean [1]
Data type description: The value is True (or could be False) [1]
Variables & Constants

Variables and constants are used to store a single item of data in a program. This
can be accessed through the identifier. Variables can be changed during program ex-
ecution while constants remain the same.

Declaring Variables and Constants


• Variables are declared using a data type, a name and a value (optional)
• Constants are declared using the 'const' keyword, a name and a value
• In all programming languages, variable names should follow certain rules,
such as:
o Starting with a letter
o Not containing spaces
o Can contain letters, numbers, _ or $
o Not using reserved words (like if, while, for etc.)
• Examples of data types include integer, float, boolean, and string

Examples in Pseudocode:
Declare a variable called 'score' with a value of 10

score ← 10

Declare a constant called 'PI' with a value of 3.14

const PI ← 3.14

Examples in Python:
Declare a variable called 'score' with a value of 10

score = 10

Declare a constant called 'PI' with a value of 3.14

PI = 3.14

Examples in Java:

Declare a variable called 'score' with a value of 10

int score = 10;

Declare a constant called 'PI' with a value of 3.14

final double PI = 3.14;


Examples in Visual Basic:

Declare a variable called 'score' with a value of 10

Dim score As Integer = 10

Declare a constant called 'PI' with a value of 3.14

Const PI As Double = 3.14

Exam Tip
• Exam questions will ask you to write pseudocode statements, rather than in a
specific language
Worked example
The variables 'name' and 'age' are used to store data in a program:
• name stores the user’s name
• age stores the user’s age
Write pseudocode statements to declare the variables name and age.
[2]
DECLARE name: STRING [1]
DECLARE age : INTEGER [1]
Input & Output
Output

Output refers to the process of displaying or saving the results of a program to the
user.

Pseudocode example:
OUTPUT "Hello, ", name

Python example:
print("Hello, ", name)

Java example:
System.out.println("Hello, " + name);

Visual Basic example:


Console.WriteLine( "Hello, " & name)

Input

Input refers to the process of providing data or information to a program.


'User Input' is data or information entered by the user during program execution.

Pseudocode example:
OUTPUT "Enter your name"
INPUT name

Python example:
name = input("Enter your name: ")

Java example:
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = input.nextLine();

Visual Basic example:


Console.WriteLine("Enter your name")
name = Console.Readline()

Exam Tip
• Remember to prompt the user for input clearly, and format the output to
make it readable and understandable.
Sequence

What is Sequence?
• Sequence is a concept that involves executing instructions in a particular or-
der
• It is used in programming languages to perform tasks in a step-by-step man-
ner
• Sequence is a fundamental concept in computer science and is used in many
programming languages

Pseudocode example:
PRINT "Hello, World!"
x←5
y←10
z← x + y
PRINT z

Python example:
print("Hello, World!")
x=5
y = 10
z=x+y
print(z)

Java example:
System.out.println("Hello, World!");
int x = 5;
int y = 10;
int z = x + y;
System.out.println(z);

Visual Basic example:


Console.WriteLine("Hello, World!")
Dim x As Integer = 5
Dim y As Integer = 10
Dim z As Integer = x + y
Console.WriteLine(z)
Exam Tip
• Always remember to write your instructions in the order in which you want
them to be executed

Selection
What is selection?

Selection is a programming concept that allows you to execute different sets of in-
structions based on certain conditions. There are two main types of selection state-
ments: IF statements and CASE statements.

If Statements

IF statements allow you to execute a set of instructions if a condition is true. They


have the following syntax:

IF condition
THEN
instructions
ENDIF

Pseudocode example:
x← 5
IF x > 0
THEN
PRINT "x is positive"
ENDIF

Python example:
x=5
if x > 0:
print("x is positive")
Java example:
int x = 5;
if (x > 0) {
System.out.println("x is positive");
}
Visual Basic example:
Dim x As Integer = 5
If x > 0 Then
Console.WriteLine("x is positive")
End If
IF ELSE Statements
If else statements are used to execute one set of statements if a condition is true
and a different set of statements if the condition is false. They have the following
syntax:

IF condition
THEN
Instructions
ELSE
Instructions
ENDIF

Pseudocode example:
x←5
IF x > 0
THEN
PRINT "x is positive"
ELSE
PRINT “x is negative”
ENDIF

Python example:
x=5
if x > 0:
print("x is positive")
else:
print("x is negative")

Java example:
int x = 5;
if (x > 0) {
System.out.println("x is positive");
} else {
System.out.println("x is negative");
}

Visual Basic example:


Dim x As Integer = 5
If x > 0 Then
Console.WriteLine("x is positive")
Else
Console.WriteLine("x is negative")
End If
IF ELSE IF Statements

If else if statements are used to test multiple conditions and execute different state-
ments for each condition. They have the following syntax:

IF condition
THEN
Instructions
ELSE IF condition
THEN
Instructions
ELSE
Instructions
ENDIF

Pseudocode example:
x← 5
IF x > 0
THEN
PRINT "x is positive"
ELSE IF x < 0
THEN
PRINT “x is negative”
ELSE
PRINT “x is 0”
ENDIF

Python example:
x=5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is 0")

Java example:
int x = 5;
if (x > 0) {
System.out.println("x is positive");
} else if (x < 0) {
System.out.println("x is negative");
} else {
System.out.println("x is 0");
}
Visual Basic example:
Dim x As Integer = 5
If x > 0 Then
Console.WriteLine("x is positive")
ElseIf x < 0 Then
Console.WriteLine("x is negative")
Else
Console.WriteLine("x is 0")
End If
Worked example
Write an algorithm using pseudocode that:
• Inputs 3 numbers
• Outputs the largest of the three numbers
[3]
INPUT a, b, c

IF a > b AND a > c THEN PRINT a [1]

ELSE IF b > c THEN PRINT b [1]

ELSE PRINT c [1]


Case Statements

CASE statements allow you to execute different sets of instructions based on the
value of a variable. They have the following syntax:

CASE OF variable
value1: instructions
value2: instructions
...
OTHERWISE instructions
END CASE

Pseudocode example:
CASE OF number
1: PRINT "Monday"
2: PRINT "Tuesday"
3: PRINT “Wednesday”
4: PRINT “Thursday”
5: PRINT “Friday”
6: PRINT “Saturday”
7: PRINT “Sunday”
OTHERWISE PRINT "Invalid number"
END CASE

Python example:
match (number)
case 1:
print "Monday";
case 2:
print "Tuesday";
case 3:
print "Wednesday";
case 4:
print "Thursday";
case 5:
print "Friday";
case 6:
print "Saturday";
case 7:
print "Sunday";
case _:
print "Invalid number";
Java example:
switch (number) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
return "Invalid number";
}

Visual Basic example:


Select Case number
Case 1
Return "Monday"
Case 2
Return "Tuesday"
Case 3
Return "Wednesday"
Case 4
Return "Thursday"
Case 5
Return "Friday"
Case 6
Return "Saturday"
Case 7
Return "Sunday"
Case Else
Return "Invalid number"
End Select
Exam Tip
• Make sure to include all necessary components in the selection statement:
the condition, the statement(s) to execute when the condition is true, and
any optional statements to execute when the condition is false
• Use proper indentation to make the code easier to read and understand
• Be careful with the syntax of the programming language being used, as it may
differ slightly between languages
• Make sure to test the selection statement with various input values to ensure
that it works as expected
Iteration

What is iteration?
Iteration is the process of repeating a set of instructions until a specific condition is
met. It is an important programming concept and is used to automate repetitive
tasks.

There are three main types of iteration:


• Count-controlled loops
• Precondition loops
• Postcondition loops

Count-controlled Loops
• A count-controlled loop is used when the number of iterations is known be-
forehand
• It is also known as a definite loop
• It uses a counter variable that is incremented or decremented after each it-
eration
• The loop continues until the counter reaches a specific value

Example in Pseudocode:
count ← 1
FOR i <= 10
OUTPUT count
NEXT i

Example in Python:
for count in range(1, 11):
print(count)

Example in Java:
for(int count=1; count<=10; count++){
System.out.println(count);
}

Example in Visual Basic:


For count = 1 To 10
Console.WriteLine(count)
Next count
Pre-condition Loops
• A precondition loop is used when the number of iterations is not known be-
forehand and is dependent on a condition being true
• It is also known as an indefinite loop
• The loop will continue to execute while the condition is true and will stop
once the condition becomes false
Example in Pseudocode:
INPUT temperature
WHILE temperature > 37 DO
OUTPUT "Patient has a fever"
INPUT temperature
END WHILE

Example in Python:
temperature = float(input("Enter temperature: "))
while temperature > 37:
print("Patient has a fever")
temperature = float(input("Enter temperature: "))

Example in Java:
Scanner input = new Scanner(System.in);
float temperature = input.nextFloat();
while (temperature > 37) {
System.out.println("Patient has a fever");
temperature = input.nextFloat();
}

Example in Visual Basic:


temperature = InputBox("Enter temperature")
Do While temperature > 37
Console.WriteLine( "Patient has a fever")
Console.WriteLine("Enter temperature")
temperature=Console.ReadLine()
Loop
Postcondition Loops
• A post-condition loop is used when the loop must execute at least once, even
if the condition is false from the start
• The condition is checked at the end of the loop

Example in Pseudocode:
REPEAT
INPUT guess
UNTIL guess = 42

Example in Python:
Postcondition loops don’t exist in Python and would need to be restructured to a
precondition loop

Example in Java:
Scanner input = new Scanner(System.in);
int guess = 0;
do {
System.out.print("Enter guess: ");
guess = input.nextInt();
} while (guess != 42);

Example in Visual Basic:


Do
Console.WriteLine("Enter guess")
guess = Console.ReadLine()
Loop Until guess = 42
Totalling & Counting
Totalling
• Totalling involves adding up values, often in a loop
• A total variable can be initialised to 0 and then updated within a loop, such
as:

Pseudocode example:
total ← 0
for i ← 1 to 10
input num
total ← total + num
next i
output total

Python example:
total = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
total += num
print("Total:", total)

Java example:
int total = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
total += num;
}
System.out.println("Total: " + total);

Visual Basic example:


Dim total As Integer = 0
For i As Integer = 1 To 10
Console.Write("Enter a number: ")
Dim num As Integer = Integer.Parse(Console.ReadLine())
total += num
Next i
Console.WriteLine("Total: " & total)
Counting
• Counting involves keeping track of the number of times a particular event oc-
curs
• A count variable can be initialised to 0 and then updated within a loop, such
as:

Pseudocode example:
count ← 0
for i ← 1 to 10
input num
if num > 5 then
count ← count + 1
end if
next i
output count

Python example:
count = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
if num > 5:
count += 1
print("Count:", count)

Java example:
int count = 0;
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num > 5) {
count++;
}
}
System.out.println("Count: " + count);

Visual Basic example:


Dim count As Integer = 0
For i As Integer = 1 To 10
Console.Write("Enter a number: ")
Dim num As Integer = Integer.Parse(Console.ReadLine())
If num > 5 Then
count += 1
End If
Next i
Console.WriteLine("Count: " & count)

Worked example
Write an algorithm using pseudocode that:
• Inputs 20 numbers
• Outputs how many of these numbers are greater than 50
[3]
FOR x ← 1 TO 20 [1]
INPUT Number
IF Number > 50 THEN Total
[1]
← Total + 1
NEXT x
PRINT total [1]
String Handling
• Strings are a sequence of characters, such as letters, numbers, and symbols
• They are used to represent text in a computer program
• String handling refers to the various operations that can be performed on
strings

Length
• The length of a string is the number of characters it contains
• In Python, the len() function is used to find the length of a string
• In Java, the length() method is used to find the length of a string
• In Visual Basic, the Len() function is used to find the length of a string

Substring
• A substring is a portion of a string
• In Python, the substring can be obtained using the slicing operator [:]
• In Java, the substring() method is used to obtain a substring
• In Visual Basic, the Mid() function is used to obtain a substring

Upper
• The upper() method converts all characters of a string to uppercase
• In Python, the upper() method is used to convert a string to uppercase
• In Java, the toUpperCase() method is used to convert a string to uppercase
• In Visual Basic, the UCase() function is used to convert a string to uppercase

Lower
• The lower() method converts all characters of a string to lowercase
• In Python, the lower() method is used to convert a string to lowercase
• In Java, the toLowerCase() method is used to convert a string to lowercase
• In Visual Basic, the LCase() function is used to convert a string to lowercase

Pseudocode example:
string phrase ← "Save my exams"
length ← LENGTH(phrase)
substring ← SUBSTRING(phrase, 5, 2)
upper ← TO_UPPER(phrase)
lower ← TO_LOWER(phrase)

Python example:
phrase = "Save my exams"
length = len(phrase)
substring = phrase[4:6]
upper = phrase.upper()
lower = phrase.lower()
Java example:
String phrase = "Save my exams";
int length = phrase.length();
String substring = phrase.substring(4, 6);
String upper = phrase.toUpperCase();
String lower = phrase.toLowerCase();

Visual basic example:


Dim phrase As String = "Save my exams"
Dim length As Integer = phrase.Length
Dim substring As String = phrase.Substring(4, 2)
Dim upper As String = phrase.ToUpper()
Dim lower As String = phrase.ToLower()

Position of First Character


• The first character of a string can be at position zero or one, depending on
the programming language
• In Python and Java, the first character of a string is at position zero
• In Visual Basic, the first character of a string is at position one

Worked example
The function Length(x) finds the length of a string x. The function substring(x,y,z)
finds a substring of x starting at position y and z characters long. The first character
in x is in position 1.
Write pseudocode statements to:
• Store the string “Save my exams” in x
• Find the length of the string and output it
• Extract the word exams from the string and output it
[6]
[1] for storing string
X ← "Save my exams"
in X.
[1] for calling the func-
tion length. [1] for using
OUTPUT Length(X)
the correct parame-
ter X.
Y←9
Z←5
[1] for using the sub-
string function. [1] for
OUTPUT Sub- correct parameters.
String(X,Y,Z) [1] for outputting length
and substring return
values.
Exam Tip
• Remember that the length of a string is not the same as the index of the last
character in the string
• Be careful when counting positions in a string, as the first character can be at
position zero or one depending on the programming language
Arithmetic, Logical & Boolean Operators

Arithmetic Operators
• Addition (+): Adds two values together
• Subtraction (-): Subtracts one value from another
• Division (/): Divides one value by another
• Multiplication (*): Multiplies two values together
• Exponentiation (^): Raises a number to a power
• Modulo (MOD): Returns the remainder of a division operation
• Integer Division (DIV): Returns the whole number of a division operation

Pseudocode example:
a←5
b←3
c←a+b
d←a-b
e←a*b
f←a/b
g ← a MOD b
h←a^b
i ← a DIV b

Python example:
a=5
b=3
c=a+b
d=a-b
e=a*b
f=a/b
g=a%b
h = a ** b
i = a // b

Java example:
int a = 5;
int b = 3;
int c = a + b;
int d = a - b;
int e = a * b;
double f = (double) a / b;
int g = a % b;
double h = Math.pow(a, b);
int i = a / b;

Visual Basic example:


Dim a As Integer = 5
Dim b As Integer = 3
Dim c As Integer = a + b
Dim d As Integer = a - b
Dim e As Integer = a * b
Dim f As Double = a / b
Dim g As Integer = a Mod b
Dim h As Double = Math.Pow(a, b)
Dim i As Integer = a \ b
Logical Operators
• Equal to (=): Returns true if two values are equal
• Less than (<): Returns true if the first value is less than the second value
• Less than or equal to (<=): Returns true if the first value is less than or equal
to the second value
• Greater than (>): Returns true if the first value is greater than the second
value
• Greater than or equal to (>=): Returns true if the first value is greater than or
equal to the second value
• Not equal to (<>): Returns true if two values are not equal

Pseudocode example:
a←5
b←3
c ← (a = b)
d ← (a < b)
e ← (a <= b)
f ← (a > b)
g ← (a >= b)
h ← (a <> b)

Python example:
a=5
b=3
c = (a == b)
d = (a < b)
e = (a <= b)
f = (a > b)
g = (a >= b)
h = (a != b)

Java example:
int a = 5;
int b = 3;
boolean c = (a == b);
boolean d = (a < b);
boolean e = (a <= b);
boolean f = (a > b);
boolean g = (a >= b);
boolean h = (a != b);
Visual Basic example:
Dim a As Integer = 5
Dim b As Integer = 3
Dim c As Boolean = (a = b)
Dim d As Boolean = (a < b)
Dim e As Boolean = (a <= b)
Dim f As Boolean = (a > b)
Dim g As Boolean = (a >= b)
Dim h As Boolean = (a <> b)

Boolean Operators
Boolean operators are logical operators that can be used to compare two or more
values and return a Boolean value (True or False) based on the comparison. There
are 3 you need to know:
• AND: Returns True if both conditions are True
• OR: Returns True if one or both conditions are True
• NOT: Returns the opposite of the condition (True if False, False if True)

Boolean Operators in Pseudocode:


IF (condition1 AND condition2) THEN
// code to execute if both conditions are True
END IF
IF (condition1 OR condition2) THEN
// code to execute if one or both conditions are True
END IF
IF NOT(condition) THEN
// code to execute if the condition is False
END IF

Boolean Operators in Python:


if condition1 and condition2:
# code to execute if both conditions are True
if condition1 or condition2:
# code to execute if one or both conditions are True
if not condition:
# code to execute if the condition is False
Boolean Operators in Java:
if (condition1 && condition2) {
// code to execute if both conditions are True
}
if (condition1 || condition2) {
// code to execute if one or both conditions are True
}
if (!condition) {
// code to execute if the condition is False
}
Boolean Operators in Visual Basic:
If condition1 And condition2 Then
' code to execute if both conditions are True
End If
If condition1 Or condition2 Then
' code to execute if one or both conditions are True
End If
If Not condition Then
' code to execute if the condition is False
End If

Exam Tip
• Boolean operators are often used in conditional statements such as if, while,
and for loops
• Boolean operators can be combined with comparison operators such as ==
(equal to), != (not equal to), < (less than), > (greater than), <= (less than or
equal to), and >= (greater than or equal to)
• Be careful when using the NOT operator, as it can sometimes lead to unex-
pected results. It is always a good idea to test your code with different inputs
to ensure that it works as expected
Nested Statements
• Nested statements involve including one statement within another state-
ment. This can be done with both selection (if/else) and iteration (for/while)
statements
• In programming languages like Python, Java, and Visual Basic, nested state-
ments are often indicated by indenting the inner statement(s) relative to the
outer statement(s)
Exam Tip
• You will not be required to write more than three levels of nested statements

Nested Selection
• Nested selection is an if statement inside an if statement
• If the first if statement is true, it will run the if statement which is nested in-
side
• Otherwise, it will skip to the "else if" or "else" which is part of that if state-
ment

Pseudocode example:
if a > b then
if b > c then
output “a is the largest”
else
output “c is the largest”
else
if a > c then
output “b is the largest”
else
output “c is the largest”

Python example:
if a > b:
if b > c:
print("a is the largest")
else:
print("c is the largest")
else:
if a > c:
print("b is the largest")
else:
print("c is the largest")
Java example:
if (a > b) {
if (b > c) {
System.out.println("a is the largest");
} else {
System.out.println("c is the largest");
}
} else {
if (a > c) {
System.out.println("b is the largest");
} else {
System.out.println("c is the largest");
}
}

Visual Basic example:


If a > b Then
If b > c Then
Console.WriteLine("a is the largest")
Else
Console.WriteLine("c is the largest")
End If
Else
If a > c Then
Console.WriteLine("b is the largest")
Else
Console.WriteLine("c is the largest")
End If
End If

Exam Tip
• Indentation is key so make sure it's clear in your answer which if statement
line is part of which. It's more clear when you use end if in the appropriate
places, too.
Nested Iteration
Nested iteration refers to a loop inside another loop.

Pseudocode example:
FOR i ← 1 TO 10
FOR j ← 1 TO 5
OUTPUT "i = ", i, " j = ", j
END FOR
END FOR

Python example:
for i in range(1, 11):
for j in range(1, 6):
print("i = ", i, " j = ", j)
Java example:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 5; j++) {
System.out.println("i = " + i + " j = " + j);
}
}

Visual Basic example:


For i As Integer = 1 To 10
For j As Integer = 1 To 5
Console.WriteLine("i = " & i & " j = " & j)
Next j
Next i

Exam Tip
• Nested iteration is useful when we need to perform a task for a specific range
of values
• It is important to keep track of the number of nested statements
• It is important to keep nested statements organized and clear. Use consistent
indentation and avoid going too many levels deep, as this can make the code
difficult to read and understand
Procedures & Functions

Subroutines
Procedures and functions are types of subroutines. They are a sequence of instruc-
tions that perform a specific task or set of tasks
• Subroutines are often used to simplify a program by breaking it into smaller,
more manageable parts. They can be used to:
o Avoid duplicating code and can be reused throughout a program,
o Improve the readability and maintainability of code,
o Perform calculations, to retrieve data, or to make decisions based on
input.
• Parameters are values that are passed into a subroutine. They can:
o Be used to customise the behaviour of a subroutine,
o Be of different types,
o Have default values, which are used if no value is passed in,
o Be passed by value or by reference.
▪ When a parameter is passed by value, a copy of the parameter
is made and used within the subroutine
▪ When a parameter is passed by reference, the original param-
eter is used within the subroutine, and any changes made to
the parameter will be reflected outside of the subroutine
• Subroutines can have multiple parameters

What's the difference between a procedure and function?


• Functions return a value whereas a procedure does not.
• Defining and Calling a Subroutine
• A subroutine only needs to be defined once to set it up. After this you can call
it as many times as needed to use it.
Procedures
• Procedures are defined using the PROCEDURE keyword in pseudocode, def
keyword in Python, and Sub keyword in Visual Basic and Java
• Procedures can be called from other parts of the program using their name

Pseudocode example:
PROCEDURE calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
OUTPUT "The area is " + area
END PROCEDURE
To call the procedure you would use the following pseudocode:
calculate_area(5,3)

Python example:
def calculate_area(length, width):
area = length * width
print("The area is ", area)
calculate_area(5,3)

Java example:
public static void calculateArea(int length, int width) {
int area = length * width;
System.out.println("The area is " + area);
}
calculateArea(5, 3);

Visual Basic example:


Sub CalculateArea(length As Integer, width As Integer)
Dim area As Integer = length * width
Console.WriteLine("The area is " & area)
End Sub
CalculateArea(5, 3)
Functions

• Functions are defined using the FUNCTION keyword in pseudocode, def key-
word in Python, and Function keyword in Visual Basic and Java
• Functions return a value using the RETURN keyword in pseudocode, return
statement in Python, and function name in Visual Basic and Java
• Functions can be called from other parts of the program using their name,
and their return value can be stored in a variable

Pseudocode example:
FUNCTION = calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
RETURN area
END FUNCTION

To output the value returned from the function you would use the following pseudo-
code:
OUTPUT(calculate_area(5,3))

Python example:

def calculate_area(length, width):


area = length * width
return area
print(calculate_area(5,3))

Java example:
public static void calculateArea(int length, int width) {
int area = length * width;
return area;
}
System.out.println(calculateArea(5, 3));

Visual Basic example:


CalculateArea(5, 3)
Sub CalculateArea(length As Integer, width As Integer)
Dim area As Integer = length * width
Return area
End Sub
Local & Global Variables
• A local variable is a variable that is declared inside a subroutine and can only
be accessed from within that subroutine
• A global variable is a variable that is declared outside of a subroutine and can
be accessed from anywhere in the program
• Global variables can be used to pass data between different subroutine
• Overuse of global variables can make a program difficult to understand and
debug and is therefore discouraged as it’s considered bad practice

Pseudocode example:
global total_score
FUNCTION calculate_average(num1: INTEGER, num2: INTEGER)
average ← (num1 + num2) / 2
RETURN average
END FUNCTION
total_score ← 0
PROCEDURE add_score(score: INTEGER)
total_score ← total_score + score
END PROCEDURE

Python example:
def calculate_average(num1, num2):
average = (num1 + num2) / 2
return average
total_score = 0
def add_score(score):
global total_score
total_score = total_score + score

Java example:
static int totalScore = 0;
public static void main(String args[]) {
double average = calculateAverage(5, 7);
System.out.println("Average: " + average);
addScore(10);
System.out.println("Total score: " + totalScore);
}
public static double calculateAverage(int num1, int num2) {
double average = (num1 + num2) / 2.0;
return average;
}
public static void addScore(int score) {
totalScore = totalScore + score;
}
Visual Basic example:
Dim totalScore As Integer = 0
Dim average As Double = CalculateAverage(5, 7)
Console.WriteLine("Average: " & average)
AddScore(10)
Console.WriteLine("Total score: " & totalScore)
Function CalculateAverage(num1 As Integer, num2 As Integer) As Double
Dim average As Double = (num1 + num2) / 2.0
Return average
End Function
Sub AddScore(score As Integer)
totalScore = totalScore + score
End Sub
Library Routines

Library routines are pre-written code that can be used in programs to perform spe-
cific tasks.
• Using library routines saves time by not having to write code from scratch
• Library routines are also tested and proven to work, so errors are less likely
• Some commonly used library routines include:
o Input/output routines
o Maths routines
• Libraries can be included in programs by importing them
• The specific syntax for importing a library may vary depending on the pro-
gramming language being used
• It is important to check the documentation for a library to understand its us-
age and available functions

Maths routines
• MOD: a function that returns the remainder when one number is divided by
another number
o Pseudocode example: x MOD y
o Python example: x % y
o Java example: x % y
o Visual Basic example: x Mod y
• DIV: a function that returns the quotient when one number is divided by an-
other number
o Pseudocode example: x DIV y
o Python example: x // y
o Java example: x / y
o Visual Basic example: x \ y
• ROUND: a function that rounds a number to a specified number of decimal
places
o Pseudocode example: ROUND(x, n)
o Python example: round(x, n)
o Java example: Math.round(x * 10^n) / x;
o Visual Basic example: Math.Round(x, n)
• RANDOM: a function that generates a random number between x and n
o Pseudocode example: RANDOM(x,n)
o Python example: random.randint(x,n)
o Java example: rand.nextInt(x)
o Visual Basic example: rand.next(x,n)

Exam Tip
• Remember to import or include the appropriate library before using the rou-
tines in your code
Maintaining Programs
Why is it important to create a maintainable program?
• Improve program quality:

o A maintainable program is easier to understand and modify, which


leads to fewer bugs and better program quality
• Reduce development time and costs:
o A maintainable program requires less time and effort to modify,
which reduces development time and costs
• Enables collaboration:
o A maintainable program makes it easier for multiple developers to
work together on the same project, as it's easier to understand and
modify
• Increase program lifespan:
o A maintainable program is more likely to be updated and maintained
over time, which increases its lifespan and usefulness
• Adapt to changing requirements:
o A maintainable program is easier to modify to adapt to changing re-
quirements or new features
How do you create a well maintained program?
• Use meaningful identifiers:
o Identifiers are names given to variables, constants, arrays, procedures
and functions
o Use descriptive and meaningful identifiers to make your code easier
to understand and maintain
o Avoid using single letters or abbreviations that may not be clear to
others
• Use the commenting feature provided by the programming language:
o Comments are used to add descriptions to the code that help readers
understand what the code is doing
o Use comments to explain the purpose of variables, constants, proce-
dures, functions and any other parts of the code that may not be im-
mediately clear
o Use comments to document any assumptions or limitations of the
code
• Use procedures and functions:
o Procedures and functions are reusable blocks of code that perform
specific tasks
o Using procedures and functions allows you to modularise your code
and make it easier to understand, debug and maintain
o Procedures and functions should have descriptive names that clearly
indicate what they do
• Relevant and appropriate commenting of syntax:
o Commenting of syntax is used to explain the purpose of individual
lines or blocks of code within the program
o Use commenting of syntax to describe complex algorithms, or to pro-
vide additional information on the purpose or behaviour of code
Arrays
Array
1D Arrays
A one-dimensional (1D) array is a collection of items of the same data type.
• To declare an array in pseudocode, use the syntax:
DECLARE arrayName[n] OF dataType
• To declare an array in Python, use the syntax:
array_name = [0] * n
• In Java, use the syntax:
dataType[] arrayName = new dataType[n];
• In Visual Basic, use the syntax:
Dim arrayName(n) As datatype

To access elements in a 1D array, use the index, which can start at 0 or 1.

2D Arrays
A two-dimensional (2D) array is an array of arrays, creating a grid-like structure.
• To declare a 2D array in pseudocode using the syntax:
DECLARE arrayName[n][m] OF dataType
• In Python, use the syntax:
array_name = [[0] * m for _ in range(n)]
• In Java, use the syntax:
dataType[][] arrayName = new dataType[n][m];
• In Visual Basic, use the syntax:
Dim arrayName(n, m) As datatype

To access elements in a 2D array, use two indices: the row index and the column in-
dex.
The syntax for accessing elements is similar across languages, using square brackets:
• [i] for 1D arrays,
• and [i][j] for 2D arrays.
Using Arrays

• Arrays are used to store and manage multiple values of the same data type
efficiently
• They can be used for tasks such as storing student scores, calculating aver-
ages, and managing inventory data

Using variables in arrays


• Variables can be used as indexes in arrays to access and modify elements by
repeatedly checking every element
• This is useful when iterating through the array using loops or performing cal-
culations based on user input

What is the first index value?


• The first index can be either 0 or 1, depending on the programming language
and personal preference
• Most programming languages, such as Python, Java, and Visual Basic, use 0 as
the first index

Exam Tip
• In pseudocode, the first index can be either 0 or 1, so it is crucial to read the
question to find out

Pseudocode example:
DECLARE scores[5] OF INTEGER
FOR i FROM 0 TO 4
INPUT scores[i]
ENDFOR

Python example:
scores = [0] * 5
for i in range(5):
scores[i] = int(input())

Java example:
int[] scores = new int[5];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 5; i++) {
scores[i] = scanner.nextInt();
}
Visual Basic example:
Dim scores(5) As Integer
For i As Integer = 0 To 4
console.Writeline("Enter score: ")
scores(i) = Console.ReadLine())
Next

Worked example
Declare an array to store customer names
[1]

CustomerNames[1:30] [1]
Declare the arrays to store each customer's date of birth, telephone number, email
address and balance

[2]
• CustomerDOB[1:30]
• CustomerTelNo[1:30]
• CustomerEmail[1:30] [1]
• CustomerBalance[1:30] [1]
Using Iteration
• Loops can be used to write values into arrays, iterating through each element
and assigning a value
• Iteration can also be used to read values from arrays, traversing through each
element and performing operations or outputting the value
• Nested iteration is useful for working with multi-dimensional arrays, such as
2D arrays, where you need to iterate through rows and columns

Pseudocode example:
DECLARE scores[3][3] OF INTEGER
FOR i FROM 0 TO 2
FOR j FROM 0 TO 2
INPUT scores[i][j]
ENDFOR
ENDFOR
FOR i FROM 0 TO 2
FOR j FROM 0 TO 2
OUTPUT scores[i][j]
ENDFOR
ENDFOR

Python example:
scores = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
scores[i][j] = int(input())
for i in range(3):
for j in range(3):
print(scores[i][j])

Java example:
int[][] scores = new int[3][3];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scores[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(scores[i][j] + " ");
}
System.out.println();
}
Visual Basic example:
Dim scores(2, 2) As Integer
For i As Integer = 0 To 2
For j As Integer = 0 To 2
Console.Writeline("Enter score: ")
scores(i, j) = Console.ReadLine())
Next
Next
For i As Integer = 0 To 2
For j As Integer = 0 To 2
Console.Write(scores(i, j) & " ")
Next
Console.WriteLine()
Next

Exam Tip
• Keep track of your loop variables to avoid confusion and errors - it's best to
give these clear names (row and column) rather than i and j

Worked example
Write the pseudocode to output the contents of the arrays Balance[ ] and Email [
] along with suitable messages
[3]
Count ← 0
REPEAT
[3]
PRINT "Customer: ", Count, " Balance: ", Balance[Count], " Email:
",Email[Count]
Count ← Count + 1
UNTIL Count = 30 [1]
You could also answer with a WHILE or FOR loop
File handling
File handling

Why Use Files?


• Files provide a way to store data permanently, allowing programs to access
and manipulate it later
• Files allow for organised storage of data, making it easier to find, access, and
update
• They enable sharing of data between different programs and users
• They support data backup, ensuring data is not lost when a program or com-
puter system shuts down
• They allow for large amounts of data to be stored and managed efficiently
• Data can be transported from one system to another

Opening & Closing Files


• Common file operations include:
o Opening: creates a connection between the file and the program
o Reading: retrieves data from a file
o Writing: saves new data to a file, overwriting existing content
o Appending: adds new data to the end of a file without overwriting ex-
isting content
o Closing: ends the connection between the file and the program, re-
leasing system resources
• Single items of data can be numbers, characters, or other simple data types
• A line of text typically ends with a newline character or an end-of-line marker

Pseudocode example:
OPEN "file.txt"
filedata = READ data
PRINT filedata
CLOSE file
OPEN "file.txt"
WRITE data
CLOSE file

Python example:
with open("file.txt", "r") as file:
data = file.read()
print(data)
with open("file.txt", "w") as file:
file.write(data)
Java example:
public static void main(String[] args) {
String path = ("file.txt");
try {
FileReader f = new FileReader(path);
BufferedReader reader = new BufferedReader(f);
String data = reader.readLine();
reader.close();
BufferedWriter out = new BufferedWriter(f);
out.write(data);
out.close();
} catch (Exception e) {
System.err.println("No file found");
}
}

Visual Basic example:


Dim File As New System.IO.StreamReader("file.txt")
Console.WriteLine(File.ReadLine())
File.Close()
Dim fileWrite As New System.IO.StreamWriter("file.txt")
fileWrite.WriteLine(data)
fileWrite.Close()
Exam Tip
• Remember to close files after using them
Database
Database Theory
Databases
Single Table Databases
• A database is a structured collection of data so it can be searched, sorted,
filtered and analysed quickly
o Data in a database can be any type of data including text, images, vid-
eos, sound
• Databases use tables to store data
• Tables have records of data represented by one row
o In the example below, each row represents the data stored about a
single customer (the customer’s record)
o In the customer table there are 3 records
o Each record is divided into fields (CustomerID, FirstName, LastName,
DOB and Phone Number)
o
A Database Table Containing Customer Details

Cus-
First- Last- Pho-
tom- DOB
Name Name neNumber
erID

1 Andrea Bycroft 05031976 0746762883

2 Melissa Langler 22012001 0756372892

3 Amy George 22111988 0746372821


• Fields are represented by the columns in a table
o There are 5 fields in the customer table
o The first row in a table contains the field names which is the heading
for the data stored in that field
o Each field in a table has a data type which defines what data can be
entered into that field
Worked example
A Database Table Containing Pet Details

Do- Gen-
Name Breed Age
gID der

DG12 Smokey Poodle 12 M


Springer
DG34 Harvey 10 M
Spaniel
Labra-
DG48 Maisie 3 F
doodle
Labra-
DG49 Maggie 3 F
doodle
Win-
DG88 Bulldog 7 M
ston
Golden
DG95 Shona Re- 6 F
triever

How many fields are there in the Dogs table shown above?
[1]

5 [1]

How many records are there in the Dogs table?


[1]
6 [1]

Exam Tip
• It is very likely you will be presented with an example database table and
identify either how many fields there are or how many records there are so
make sure you remember a record is row and a field is a column
Validation and Verification
• Verification checks check whether the data that has been entered is the cor-
rect data and is accurate
o This is often completed by getting data entered by one person is then
checked by another person
• When a table is created, validation rules can be assigned to the different
fields
o A validation rule controls what data can be entered into that field
o There are different types of validation checks used to limit what data
can be entered into each field

The different types of validation check

Type Description

This type of validation checks the number of characters that have been en-
Length
tered into a field. For example, you might make phone numbers entered
Check
have to be eleven characters long
For- This type of validation checks data entered meets an exact format. For ex-
mat ample, a product code might have to be two letters followed by five num-
Check bers
A range check will check the number entered is within a specific range. For
Range
example, the age of a dog would be between 0 - 40. Any other number
Check
would be disallowed
Pres-
ence A presence check can be added to fields which cannot be left blank
Check
A type check will allow data with a specific data type to be entered into a
Type
field. For example, if text was entered into a field which is supposed to con-
Check
tain the date of birth of a person it would not be allowed
Check digit validation is a process used to verify the accuracy of numbers
such as credit card numbers. A check digit is a single digit added to the end
Check of the number, which is calculated based on a specific algorithm applied to
Digits the other digits in the number. When the data is re-entered the same algo-
rithm can be applied and if it produces a different result the code is incor-
rect
Worked example
A Database Table Containing Student Grades

Per-
Studen- First- Last- MarkSub-
cent-
tID Name Name mitted
age

Sha-
1483792 Giles Y 55
nay
1498378 Poppy Petit N 20
1500121 Diya Dinesh Y 74
1382972 Joe Swaile Y 68
1598264 Anton Smith Y 34
Felic-
1548282 Hall N 47
ity

Describe two validation checks that could be used to check data being inputted into
the table above

[4]

StudentID could have a length check to ensure 7 characters are entered [2]
FirstName and LastName could have a presence check to make a record cannot be
entered without entering the name of the student [2]

A type check of boolean could be applied to the Mark Submitted field so that only Y
or N are entered [2]

A range check could be assigned to the Mark column to ensure only numbers be-
tween 0 and 100 are entered [2]
Data Types
• Table fields are represented by columns in a table
• There are 5 fields in the customer table below
o These include CustomerID, FirstName, LastName, DOB and Pho-
neNumber
A Database Table Containing Customer Details

Cus-
First- Last- Pho-
tom- DOB
Name Name neNumber
erID

1 Andrea Bycroft 05031976 0746762883


2 Melissa Langler 22012001 0756372892
3 Amy George 22111988 0746372821
• Each field in a table, has a data type
o Common data types include text/alphanumeric, character, boolean,
integer, real and date/time
o Phone numbers have to be assigned the text/alphanumeric data type
because they begin with a 0
▪ If you assigned the data type Integer to a phone number it
would remove the initial 0

Database Data Types

Data Type Explanation Example

Text/Al- This data type allows letters, special characters


phanu- like spaces and punctuation and numbers to be NG321AE
meric entered into a field
This allows single characters to be entered into
Character a field. Characters can be any alphanumeric A
value and can be lowercase or uppercase
This data type can be used in fields where there
are only two possible options. Data is stored as
Boolean True/False
a 1 or 0 in the database but can be used to rep-
resent True/False or Yes/No
Integer Only whole numbers can be entered 15
Numbers including decimal numbers can be
Real 30.99
stored
Only dates or times can be entered into a field
Date/Time with this type. A format for the date/time can 180855
also be assigned to the field
Worked example
A Database Table Containing Dog Details

Do- Ag Gen
Name Breed
gID e der

DG1 Smoke
Poodle 12 M
2 y
Springe
DG3
Harvey r Span- 10 M
4
iel
DG4 Labra-
Maisie 3 F
8 doodle
DG4 Labra-
Maggie 3 F
9 doodle
DG8 Win-
Bulldog 7 M
8 ston
Golden
DG9
Shona Re- 6 F
5
triever

What data type should Age be?


[1]

Integer [1]

What data type should DogID be?


[1]
Text/Alphanumeric [1]

Primary Keys
• Each table has a primary key field which acts as a unique identifier
o Each item of data in this field is unique
o Duplicate data items would be blocked if they were entered into the
primary key field
• Because the items of data are unique within the primary key field they can be
used to identify individual records
A Database Table Containing Customer Details
Cus-
First- Last- Pho-
tom- DOB
Name Name neNumber
erID

1 Andrea Bycroft 05031976 0746762883

2 Melissa Langler 22012001 0756372892

3 Amy George 22111988 0746372821


• In the example customer table, the primary key would be the CustomerID be-
cause each customer’s ID is unique
• If there was a customer with the same name they could be identified cor-
rectly using the CustomerID
Worked example
A database table containing the details of dogs

Do- Gen-
Name Breed Age
gID der

DG12 Smokey Poodle 12 M


Springer Span-
DG34 Harvey 10 M
iel
DG48 Maisie Labradoodle 3 F
DG49 Maggie Labradoodle 3 F
Win-
DG88 Bulldog 7 M
ston
Golden Re-
DG95 Shona 6 F
triever

Which field would be suitable for the primary key? Explain why
[2]

DogID [1]

It is a unique identifier [1]

It does not contain any duplicate data items


SQL
SQL

• Records in a database can be searched and data can be manipulated us-


ing Structured Query Language (SQL)
• SQL statements can be written to query the data in the database and extract
useful information
• SQL statements follow this structure:
o SELECT the fields you want to display
o FROM the table/tables containing the data you wish to search
o WHERE the search criteria
A Database Table Containing Movie Details

Cer-
Mov- Rat-
Name Genre tifi-
ieID ing
cate

Fam-
M23 Moana U 8.1
ily
Shaun
Com-
M8 of the 18 8.7
edy
Dead
Die Ac-
M56 18 8.4
Hard tion
Fam-
M34 Big PG 8.5
ily
Example
SELECT Name, Rating
FROM Movie
WHERE Rating>8.4;
The results of this query would be:

Rat-
Name
ing

Shaun of the
8.7
Dead
Big 8.5
• The two fields - Name and Rating have been extracted from the Movie table
and then the records have been filtered by Rating
• This example uses the > operator to search for records where the rating
is greater than 8.4
• There are several other comparison operators which can be used to create
the filter criteria in the WHERE line of a SQL query
Comparison Operators

Oper-
Description
ator

> Greater than


>= Greater than or equal to
< Less than
<= Less than or equal to
= Equal to
<> Not equal to

Example
SELECT Name,Rating
FROM Movie
WHERE Genre=”Family” AND Certificate=”U”;
The results of this query would be:

Name Rating

Moana 8.1
• The two fields Name and Rating have been extracted from the Movie table
and the records have been filtered by both Genre and Certificate
• This query uses the AND logical operator to include multiple criteria in the
WHERE line of the SQL query
• Another logical operator which can be used in the WHERE statement is OR
o For example, WHERE Genre=”Comedy” OR Genre=”Family”
Worked example
A database table, Dogs2023, is used to keep a record of all dogs registered at a veter-
inary practice

Do- Gen-
Name Breed Age
gID der

DG12 Smokey Poodle 12 M


Springer
DG34 Harvey 10 M
Spaniel
Labra-
DG48 Maisie 3 F
doodle
Labra-
DG49 Maggie 3 F
doodle
Win-
DG88 Bulldog 7 M
ston
Golden
DG95 Shona Re- 6 F
triever
Complete the structured query language (SQL) to return the name and breed of all
Female dogs.
SELECT Name,Breed
________ Dogs2023
WHERE _______;
[2]
FROM [1]
Gender=”F” [1]
Write an SQL query to find out the name and breed of all dogs aged 10 years old or
older
[4]
SELECT Name, Breed [1]
FROM Dogs2023 [1]
WHERE Age>=10; [2]
ORDER BY
• You can enter a fourth line to the statement using the ORDER BY command,
followed by ASC or DESC
o If you enter ASC the results of the query will be sorted in ascend-
ing order
o If you enter DESC the results of the query are sorted in descending or-
der
Example
SELECT Name,Genre, Certificate, Rating
FROM Movie
ORDER BY Name ASC
• The results of this query would be:

Certif- Rat-
Name Genre
icate ing

Fam-
Big PG 8.5
ily
Ac-
Die Hard 18 8.4
tion
Fam-
Moana U 8.1
ily
Shaun of the Com-
18 8.7
Dead edy
• The query has returned four fields and all records because there were no
WHERE criteria. The records are sorted by Name alphabetically
o If numbers are sorted in ascending order they go from the lowest
number at the top of the table to the highest number at the bottom
o Descending order is the highest number to the lowest
SUM and COUNT commands
• The SUM command can be used to add numerical data
• The COUNT command can be used to count items of data

Product- Quan-
ProductID Price
Name tityInStock

Sau-
1 1.99 3
sages
2 Chips 2.99 2

3 Beans 2.50 5

4 Bananas 2.10 12

5 Avocado 1.00 3
Example
SELECT SUM(QuantityInStock)
FROM ProductTable;
• This query will add up all of the numbers in the QuantityInStock field
o The result of this query would be 25
Example
SELECT COUNT(*)
FROM ProductTable
WHERE Price>2;
• This query will count all the records with a price greater than 2
o The result of this query would be 3
o This is because there are three products with a price greater than £2
(Chips, Beans, Bananas)
Boolean
Logic
Logic Gates
Logic Gates
• A logic gate is a building block of a digital circuit. Logic gates perform a logical
operation on one or more binary inputs to produce a binary output
• An electrical signal entering the logic gate is represented by a 1
• No electrical signal is represented by a 0
• There are several types of logic gates, each performing a specific logical op-
eration
• Logic gates can be combined to carry out meaningful functions such as per-
forming calculations or checking if data meets certain conditions
A table showing the symbol used to represent each logic gate
Symbol Description
Gate

The NOT gate takes a single binary input and


NOT
outputs the opposite of the input

The AND gate takes two inputs and pro-


duces one output
Only two positive inputs (1 and 1) will result
AND
in a positive output of 1
If either of the inputs is a 0 the output will
be a 0

The OR gate takes two inputs and produces


one output
OR
If either of the inputs is positive (1) the out-
put will be 1

A NAND gate is a combination of an AND


gate followed by a NOT gate. If both inputs
NAND
are a 1 it will output a 0. Any other combina-
tion of inputs will result in an output of 1

A NOR gate is a combination of an OR gate


followed by a NOT gate. If both inputs are
NOR
0 it will output a 1. Any other combination of
inputs will result in an output of 0

An XOR gate (exclusive OR) will output a 1 if


XOR the inputs are different to one another (a 1
and a 0)
Exam Tip
• You will need to either draw a diagram of a logic circuit using these symbols,
or you will have to interpret an existing diagram. This is why it is important to
remember the symbol of each gate and the logic rules for each one
Logic Circuits
• Logic gates can be combined to produce different outputs
• The combination of two or more logic gates forms a logic circuit
• A logic diagram is a visual representation of combinations of logic gates
within a logic circuit
An example of Logic Circuit

• In this diagram, the inputs are represented by A and B


• P is the output of the OR gate on the left and becomes the input of the NOT
gate. This is called an intermediary output
• Q is the final output of the logic circuit

Exam Tip
• You may be asked to draw a logic circuit from a logic statement or a boolean
expression. Circuits must be drawn without simplification
• Logic circuits will be limited to a maximum of three inputs and one output
An example of Logic Circuit

• This logic circuit contains three inputs (A, B and C)


• It contains a NAND gate, a NOT gate, a NOR gate and finally an OR gate
• X is the final output
• This logic circuit can be represented as a logic expression as
X=((NOT(A NAND B) OR (B NOR C

Worked example
A sprinkler system switches on if it is not daytime (input A) and the temperature is
greater than 40 (input B)
Draw a logic circuit to represent the problem statement above
[2]

Exam Tip
• You may need to draw a logic circuit from a problem statement (as in the ex-
ample above), from a truth table or from a boolean expression
Truth Tables
NOT gate
• A NOT gate has one input and will invert it to produce an opposite output.
This is shown in the truth table below
• A is the input
• Z is the output

In- Out-
put put

A Z

0 1

1 0
AND gate
• An AND gate has two inputs

Out-
Input
put

A B Z
0 0 0
0 1 0
1 0 0
1 1 1
• The AND gate truth table shows the only combination of inputs which will re-
sult in a positive output is 1 and 1
OR gate
• An OR gate has two inputs

Out-
Input
put

A B Z

0 0 0

0 1 1

1 0 1

1 1 1
• The truth table shows an OR gate produces an output of 1 if any of the inputs
are a 1
NOR gate
• A NOR gate has two inputs

Out-
Input
put

A B Z

0 0 1

0 1 0

1 0 0

1 1 0
• The truth table shows a NOR gate works oppositely to an OR gate - the only
input combination which results in a 1 is two 0s
NAND gate
• A NAND gate has two inputs

Out-
Input
put

A B Z
0 0 1
0 1 1
1 0 1
1 1 0
• The truth table shows a NAND gate works in the opposite way to an AND
gate - the only input combination which does not result in a 1 is two positive
inputs (1 +1)
XOR gate
• An XOR gate has two inputs

Out-
Input
put

A B Z
0 0 0
0 1 1
1 0 1
1 1 0
• The truth table shows how an XOR gate works. It will only output a 1 if the
two inputs are different to one another
Worked example
A truth table for a two input (A and B) logic gate
A B X

0 0 0

0 1 1

1 0 1

1 1 1
Identify what logic gate the truth table is representing
[1]
OR [1]
What symbol is used to represent this logic gate?
[1]

[1]
• Truth tables can also be used to help work out the possible outputs of a logic
circuit containing more than one gate
Exam Tip
• You will only be asked to create truth tables for logic circuits with three in-
puts. The number of rows you should have in a three input truth table is 8
(not including the headings)
• When creating a truth table for multiple inputs, begin by entering the possi-
ble input combinations into the leftmost columns
A truth table for a three input (A, B and C) logic gate
A B C Z
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

• The column on the right contains the final output of the logic circuit (Z)
• Column(s) in between the inputs and the final output can be used to help
work out the final output by containing intermediary outputs
• Intermediary outputs are the output of gates found within the logic circuit
• In the logic circuit diagram below, D and E are intermediary outputs

• The fourth column labelled D represents the output of NOT A


D
A B C (NOT E Z
A)
0 0 0 1
0 0 1 1
0 1 0 1
0 1 1 1
1 0 0 0
1 0 1 0
1 1 0 0
1 1 1 0
• The next intermediary output is E which is the equivalent of ((NOT A) AND B)
this notation is called a logic expression
• The E intermediary output can be worked out by performing the AND logical
operation on columns B and D

E
D ((NOT
A B C (NOT A) Z
A) AND
B)

0 0 0 1 0

0 0 1 1 0

0 1 0 1 1

0 1 1 1 1

1 0 0 0 0

1 0 1 0 0

1 1 0 0 0

1 1 1 0 0
• The final output (Z) can be worked out by performing the OR logical opera-
tion on columns E and C

D
E ((NOT A) Z (((NOT A)
A B C (NOT
AND B) AND B) OR C)
A)

0 0 0 1 0 0

0 0 1 1 0 1

0 1 0 1 1 1
0 1 1 1 1 1

1 0 0 0 0 0

1 0 1 0 0 1

1 1 0 0 0 0

1 1 1 0 0 1

Exam Tip
• In the exam it is likely truth tables will just contain columns for the inputs and
the final output. You can still work out intermediary outputs to help you find
the final output answers
Worked example

Complete the Truth table for the logic circuit above


A B Q
0 0
0 1
1 0
1 1
[4]
A B Q
0 0 1
0 1 1
1 0 0
1 1 1
Logic Expressions
Logic Expressions
• A logic expression is a way of expressing a logic gate or logic circuit as
an equation
• The output appears on the left of the equals sign with the inputs and logic
gates on the right
Logic
Ex-
Gate Symbol Truth Table
pres-
sion

A Z Z=NOT
NOT
0 1 A
1 0

A B Z
0 0 0 Z=A
AND
0 1 0 AND B
1 0 0
1 1 1

A B Z
0 0 0 Z=A
OR
0 1 1 OR B
1 0 1
1 1 1

A B Z
0 0 1 Z=A
NAND NAND
0 1 1
B
1 0 1
1 1 0

A B Z
0 0 1 Z=A
NOR
0 1 0 NOR B
1 0 0
1 1 0
A B Z
0 0 0 Z=A
XOR
0 1 1 XOR B
1 0 1
1 1 0

• Logic circuits containing multiple gates can also be expressed as logic expres-
sions/statements
An example logic circuit containing two inputs

• The logic circuit above can be expressed as the logic expression Q= NOT(A OR
B)

An example logic circuit containing two inputs

• The logic circuit above can be expressed as the logic expression Q= (NOT A)
AND B

An example logic circuit containing three inputs


• The logic circuit above can be expressed as the logic expression P = ((NOT A)
OR B) NAND C

An example logic circuit containing three inputs

• This logic circuit above can be expressed as X = NOT (A NAND B) OR (B NOR


C)
Exam Tip
• You may be required to write a logic expression/statement from a truth ta-
ble or a logic circuit. You may also have to do the opposite - draw a logic cir-
cuit and complete a truth table for a logic expression
Worked example
Consider the logic statement: X = (((A AND B) OR (C AND NOT B)) XOR NOT C)
a. Draw a logic circuit to represent the given logic statement.
[6]

One mark per correct logic gate, with the correct input

You might also like