IGCSE Computer Science Algorithms
IGCSE Computer Science Algorithms
CONTENTS
7.1 Development Life Cycle
Program Development Life Cycle - Analysis
Program Development Life Cycle - Design
Program Development Life Cycle - Coding
Program Development Life Cycle - Testing
7.2 Algorithms
Explaining Algorithms
7.3 Standard Methods
Standard Methods
7.4 Validation and Testing
Validation
Test Data
Trace Tables
7.5 Identifying Errors
Identifying Errors
Writing & Amending Algorithms
Explaining Algorithms
Algorithms can be written using flowcharts, pseudocode or high-level programming
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 purpose 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 codeshould
otherwise beself-explanatory
The purpose of the algorithm below is to add ten user-entered numbers together and
output the total. The processes are:
initializing three variables (Count, Number, Total)
inputting a user number
adding to two variables (Total, Count)
repeating nine more times
outputting the final Total value
Count ← 1
Number ← 0
Total ← 0
REPEAT
INPUT Number
Count ← Count + 1
OUTPUT Total
YOUR NOTES
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
Count ← Count + 1
UNTIL Count = 30
Linear Search
The linear search is a standard algorithm used to find elements in an unordered 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
If the value is found the algorithm outputs where it was found in the list
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
INPUT Number
Found ← FALSE
Index ←1
REPEAT
IF Number = Mylist[Index]
THEN
Found ← TRUE
ELSE
Counter ← Counter + 1
ENDIF
YOUR NOTES
IF Found = TRUE
THEN
ELSE
ENDIF
Mylist ← [5, 9, 4, 2, 6, 7, 1, 2, 4, 3]
FirstElement ← 1
LastElement ← LENGTH(Mylist)
REPEAT
Swap ← FALSE
Temp ← Mylist[Index]
Mylist[Index] ← Mylist[Index + 1]
Mylist[Index + 1] ← Temp
Swap ← TRUE
ENDIF
NEXT Index
LastElement ← LastElement - 1
INPUT ItemValue
NEXT Count
OUTPUT Total
Counting
Counting works similarly to totalling except the count is incremented or decremented 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 element is currently being considered
The count is incremented and each pass number is output until fifty outputs have been
produced
Count ← 0
DO
Count ← Count + 1
The count is decremented from fifty until the count reaches zero. An output is produced for
each pass
Count ← 50
DO
Count ← Count - 1
Min ← Score[1]
THEN
Max ← ScoreSize[Count]
ENDIF
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
NEXT Count
Identifying Errors
Errors can be identified in algorithms using trace tables as well as scanning and debugging 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 understand
Transcribing flowcharts and pseudocode to real programming code may cause
problems if it is difficult to read and understand said flowcharts and pseudocode
Logical error
Logical errors occur when the program finishes but produces the wrong output during
or after
Flowcharts and pseudocode, unlike real programs, do not crash when dry run,
however may still produce logic errors by producing incorrect output
Logical errors are the most difficult error to fix as developers must reconsider 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
IF Age > 18
THEN
ELSE
IF Age > 15
THEN
THEN
ELSE
IF Age < 9
THEN
ELSE
END IF
ENDIF
ENDIF
ENDIF
Syntax and logic: OUTPUT Age and INPUT “Enter an age” are both syntax and logical errors
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 cannot store data
Logical: Both are the wrong way around. OUTPUT Age should be OUTPUT “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
YOUR NOTES
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
algorithm
[2]
[1] for both ends of the range and correct inequality symbols
[1] for the AND
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
YOUR NOTES
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 requiring 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, understandable 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
Validation
Validation and verification are used to ensure input data is correct, reasonable 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 allowing the user to reenter the data
The different types of validation rules or checks are as follows:
Range checks
Length checks
Type checks
Presence checks
Format checks
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
THEN
ENDIF
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 characters 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
THEN
OUTPUT “Your password must be between 8 and 20 characters in length, please try again”
ENDIF
Type checks
Type checks make sure the input data is of the correct data type. For example, 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
THEN
Presence check
Presence checks make sure that input data has been entered and that the input 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
ENDIF
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 format “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
FirstChar ← SUBSTRING(IDNumber, 1, 1)
ValidChar ← False
Index ← 1
IF FirstChar = ValidChars[Index]
THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False
THEN
ENDIF
SecondChar ← SUBSTRING(IDNumber, 2, 2)
ValidChar ← False
Index ← 1
IF SecondChar = ValidChars[Index]
THEN
ValidChar ← True
ENDIF
Index ← Index + 1
ENDWHILE
IF ValidChar = False
THEN
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 calculated 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, miscanning or
misspeaking
Such errors include missing or additional digits, swapped digits, mispronunciation of
digits or simply an incorrect digit
Barcode ← “9780201379624”
Total ← 0
IF Index MOD 2 = 0
THEN
ELSE
ENDIF
NEXT Index
IF CheckDigit = Barcode[LENGTH(Barcode)]
THEN
ELSE
ENDIF
INPUT Password
INPUT ConfirmPassword
THEN
ENDIF
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
INPUT Name
INPUT Answer
YOUR NOTES
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
compares both entries to check they are the same
[1] for example:
Visual / double entry
Decomposition
This is the act of breaking down a large problem into smaller, clear, manageable and
understandable sub-parts. Sub-parts can be divided until they are easily solvable and
cannot be broken down any further. An example of decomposition could be getting ready
in the morning to go to school
Step 1: Wake up
Step 2: Get breakfast
Step 3: Brush teeth
Step 4: Put clothes on
Step 5: Make sure the bag and school supplies are ready
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:
Step 2.1 Get a bowl
Step 2.2 Get cereal
Step 2.3 Get milk
Step 2.4 Get a spoon
Step 2.5 Put cereal in a bowl
And so on…
Once the requirements document has been created, developers need to design the
structure and algorithms to solve the problem:
Structure charts are created to show the breakdown of tasks in a hierarchy
Flowcharts may be created to visually show how tasks should be carried out
Pseudocode is created, sometimes from flowcharts, to allow programmers to easily
translate task instructions into programming code
The design of a solution identifies what tasks need completing, how to complete the tasks
and how each task works together with other tasks
A computer system includes several components that work together: software, 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 YOUR NOTES
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 created 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:
Inputs: data entered into the system
Processes: subroutines and algorithms that turn inputs and stored data into outputs
Outputs: data that is produced by the system, such as information on a screen or
printed information
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 developers
There are many methods used to design and construct solutions. Three such methods are
illustrated below:
YOUR NOTES
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 satellite navigation system.
[4]
[1] for a hierarchical structure
[1] for suitable names for the sub-systems
[1] for identifiable inputs
[1] for identifiable outputs
YOUR NOTES
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 create 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 consistent style. This
will make it easier and quicker for programmers to read and create programs from the
pseudocode
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,
CalculateArea, Sortlist
Indentation can be used for iteration and selection
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 pseudocode and
flowcharts must be dry run manually. Both require suitably chosen and different sets of test
data. The outputs are then compared to the expected output to check if the algorithm
works as intended
Test data comes in several generic types:
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 addresses, phone
numbers, student grades as a percentage, etc
Student percentage grades could involve test data such as: 34, 41, 56, 78, 12, 92
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 incorrect data
Examples of abnormal data would be entering numbers instead 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
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
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
YOUR NOTES
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]
Writing Code
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 interacts 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
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 algorithm 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
YOUR NOTES
8 9 9 YOUR NOTES
9 12 12
Exam Tip
When asked to identify the purpose of an algorithm in the exam, the variables
listed will often bea single letterratherthan a meaningful identifier
YOUR NOTES
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
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 design and rejects any invalid data that
is input
Examples of test data include alphanumeric sequences to test password validation
routines. Such validation routines could be:
A password must be between 8-20 characters
Test data would be passwords of less than 8 characters or greater than 20
characters
A password must include only alphanumeric characters
Test data would be passwords including non-alphanumeric symbols such as @, ?,
#, !, $ or %, etc
CONTENTS
8.1 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
8.2 Arrays
Arrays
Using Arrays
8.2 Arrays
Arrays
1D Arrays
A one-dimensional (1D) array is a collection of items of the same data type, stored in a
contiguous block of memory
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
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 index
The syntax for accessing elements is similar across languages, using square brackets [i] for
1D arrays and [i][j] for 2D arrays
Using 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 averages, and
managing inventory data
Using variables in arrays
Variables can be used as indexes in arrays to access and modify elements dynamically
This is useful when iterating through the array using loops or performing calculations 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();
}
Worked Example
Declare an array to store customer names [1]
CustomerNames[1:30] [1 mark]
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 mark]
CustomerBalance[1:30] [1 mark]
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 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
PRINT "Customer: ", Count, " Balance: ", Balance[Count], " Email: ",Email[Count] [3 marks]
Count ← Count + 1
UNTIL Count = 30 [1 mark]
Data Types
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:
Integer: used to represent whole numbers, either positive or negative
Examples: 10, -5, 0
Real: used to represent decimal numbers, either positive or negative
Examples: 3.14, -2.5, 0.0
Char: used to represent a single character such as a letter, digit or symbol
Examples: 'a', 'B', '5', '$'
String: used to represent a sequence of characters
Examples: "Hello World", "1234", "@#$%
Boolean: used to represent true or false values
Examples: True, False
We can declare variables as follows:
It is important to choose the correct data type for a given situation to ensure accuracy and
efficiency in the program.
Worked Example
Name and describe the most appropriate programming data type for each of the
examples of data given. Each data type must be different
[6]
Data: 83
Data type name: Integer [1 mark]
Data type description: The number is a whole number [1 mark]
Data: myemail@savemyexams.co.uk
Data type name: String [1 mark]
Data type description: It is a group of characters [1 mark]
Data: True
Data type name: Boolean [1 mark]
Data type description: The value is True (or could be False) [1 mark]
Examples in Pseudocode:
Declare a variable called 'score' with a value of 10
score ← 10
Examples in Python:
Declare a variable called 'score' with a value of 10
score = 10
Examples in Java:
Declare a variable called 'score' with a value of 10
int score = 10;
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]
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);
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);
name = Console.Readline()
Exam Tip
Remember to promptthe userfor input clearly, and format the output to makeit
readable and understandable.
Sequence
Sequence
What is Sequence?
Sequence is a concept that involves executing instructions in a particular order
It is used in programming languages to perform tasks in a step-by-step manner
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);
Dim y As Integer = 10
Dim z As Integer = x + y
Console.WriteLine(z)
Exam Tip
Always remember to writeyour instructions in the order in which you want them to be
executed
iGCSE Computer Science(0478) - Paper-2 Page 50 of 115
Compiled by : Shyam Subrahmanya
Selection
Selection
Selection is a programming concept that allows you to execute di erent sets of instructions
based on certain conditions. There are two main types of selection statements: 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
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");
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
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");
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 statements 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 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")
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 mark)
ELSE IF b > c THEN PRINT b (1 mark)
ELSE PRINT c (1 mark)
Case Statements
CASE statements allow you to execute different sets of instructions based on the value of a
variable. They have the following syntax:
SELECT CASE variable
CASE value1
instructions
CASE value2
instructions
...
CASE ELSE
instructions
END SELECT
Pseudocode example:
SELECT CASE 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 ELSE
END SELECT
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 _:
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:
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
End Select
Exam Tip
Makesureto includeall necessary components in the selection statement: the
condition, the statement(s) to executewhen the condition is true, and any
optional statements to executewhen the condition is false
Use properindentation to makethe codeeasier to read and understand
Be careful with the syntax of the programming languagebeing used, as it may
di er slightly between languages
Makesureto test the selection statement with various input values to ensure
that it works as expected
Iteration
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 beforehand
It is also known as a definite loop
It uses a counter variable that is incremented or decremented after each iteration
The loop continues until the counter reaches a specific value
Example in Pseudocode:
count ← 1
FOR i <= 10
OUTPUT count
count ← count + 1
END FOR
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);
Console.WriteLine(count)
Next count
Pre-condition Loops
A precondition loop is used when the number of iterations is not known beforehand 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
INPUT temperature
END WHILE
Example in Python:
temperature = float(input("Enter temperature: "))
Example in Java:
Scanner input = new Scanner(System.in);
temperature = input.nextFloat();
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 {
guess = input.nextInt();
Console.WriteLine("Enter guess")
guess = Console.ReadLine()
for i ← 1 to 10
input num
next i
output total
Python example:
total = 0
total += num
print("Total:", total)
Java example:
int total = 0;
total += num;
For i As Integer = 1 To 10
total += num
Next i
Counting
Counting involves keeping track of the number of times a particular event occurs
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
ount ← count + 1
end if
next i
output count
Python example:
count = 0
if num > 5:
count += 1
print("Count:", count)
Java example:
int count = 0;
if (num > 5) {
count++;
For i As Integer = 1 To 10
count += 1
End If
Next i
Worked Example
Write an algorithm using pseudocode that:
Inputs 20 numbers
Outputs how many of these numbers are greater than 50
[3]
(1
FOR x ← 1 TO 20
mark)
INPUT Number
(1
IF Number > 50 THEN Total ← Total + 1
mark)
NEXT x
(1
PRINT total
mark)
String Handling
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";
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]
X ← "Save my exams" One mark for storing string in X.
OUTPUT Length(X) One mark for calling the function length. One mark for using the
correct parameter X.
Y ←9
Z ←4
OUTPUT SubString(X,Y,Z) One mark for using the substring function. One mark for
correct parameters.
One mark 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
characterin the string
Be careful when counting positions in a string, as the first charactercan beat
position zero or one depending on the programming language
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;
int i = a / b;
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 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 h = (a != b);
Dim b As Integer = 3
Dim c 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
END IF
END IF
IF NOT(condition) THEN
END IF
if condition1 or condition2:
if not condition:
if (condition1 || condition2) {
if (!condition) {
End If
End If
End If
Exam Tip
Boolean operators areoften usedin conditional statements such as if, while,
and for loops
Boolean operators can becombinedwith 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 NOToperator, as it can sometimes lead to
unexpectedresults. It is always a goodidea to test your codewith di erent
inputs to ensurethat it works as expected
Nested Statements
Nested Statements
Nested statements involve including one statement within another statement. This can be
done with both selection (if/else) and iteration (for/while) statements
In programming languages like Python, Java, and Visual Basic, nested statements 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
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 inside
Otherwise, it will skip to the else if or else which is part of that if statement
Pseudocode example:
if a > b then
if b > c then
else
else
if a > c then
else
Python example:
if a > b:
if b > c:
else:
else:
if a > c:
else:
Java example:
if (a > b) {
if (b > c) {
} else {
} else {
if (a > c) {
} else {
If b > c Then
Else
End If
Else
If a > c Then
Else
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.
Iteration
Nested iteration refers to a loop inside another loop.
Pseudocode example:
FOR i ← 1 TO 10
FOR j ← 1 TO 5
END FOR
END FOR
Python example:
for i in range(1, 11):
Java example:
for (int i = 1; i <= 10; i++) {
For j As Integer = 1 To 5
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
Subroutines
Procedures and functions are types of subroutines. They are a sequence of instructions 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
Subroutines can be used to avoid duplicating code and can be reused throughout a
program
Subroutines can be used to improve the readability and maintainability of code
Subroutines can be used to perform calculations, to retrieve data, or to make decisions
based on input.
Parameters are values that are passed into a subroutine
Parameters can be used to customise the behaviour of a subroutine
Subroutines can have multiple parameters
Parameters can be of different types
Parameters can have default values, which are used if no value is passed in
Parameters can 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 parameter is used within the
subroutine, and any changes made to the parameter will be reflected outside of the
subroutine
What's the difference between a procedure and function?
Functions return a value whereas a procedure does not
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)
END PROCEDURE
Python example:
def calculate_area(length, width):
calculate_area(5,3)
Java example:
public static void calculateArea(int length, int width) {
calculateArea(5, 3);
End Sub
CalculateArea(5, 3)
Functions
Functions are defined using the FUNCTION keyword in pseudocode, def keyword 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:
PROCEDURE calculate_area(length: INTEGER, width: INTEGER)
RETURN area
END PROCEDURE
To output the value returned from the function you would use the following pseudocode:
OUTPUT(calculate_area(5,3))
Python example:
def calculate_area(length, width):
return area
print(calculate_area(5,3))
Java example:
public static void calculateArea(int length, int width) {
return area;
System.out.println(calculateArea(5, 3));
Return area
End Sub
RETURN average
END FUNCTION
total_score ← 0
END PROCEDURE
Python example:
def calculate_average(num1, num2):
return average
total_score = 0
def add_score(score):
global total_score
Java example:
static int totalScore = 0;
addScore(10);
return average;
AddScore(10)
Return average
End Function
End Sub
Library Routines
Library Routines
Library routines are pre-written code that we can include in our programs to perform specific
tasks.
Using library routines saves us time by not having to write code from scratch
Library routines are also tested and proven to work, so we don't have to worry about errors
as much
Some commonly used library routines include:
Input/output routines
Maths routines
Libraries can be included in our programs by importing them
The specific syntax for importing a library may vary depending on the programming
language being used
It is important to check the documentation for a library to understand its usage and
available functions
Maths routines
MOD: a function that returns the remainder when one number is divided by another number
Pseudocode example: x MOD y
Python example: x % y
Java example: x % y
Visual Basic example: x Mod y
DIV: a function that returns the quotient when one number is divided by another number
Pseudocode example: x DIV y
Python example: x // y
Java example: x / y
Visual Basic example: x \ y
ROUND: a function that rounds a number to a specified number of decimal places
Pseudocode example: ROUND(x, n)
Python example: round(x, n)
Java example: Math.round(x * 10^n) / x;
Visual Basic example: Math.Round(x, n)
RANDOM: a function that generates a random number between x and n
Pseudocode example: RANDOM(x,n)
Python example: random.randint(x,n)
Java example: rand.nextInt(x)
Visual Basic example: rand.next(x,n)
Exam Tip
Remember to import or includethe appropriatelibrary beforeusing the routines in
your code
Maintaining Programs
Maintaining Programs
Why is it important to create a maintainable program?
Improve program quality:
A maintainable program is easier to understand and modify, which leads to fewer bugs
and better program quality
Reduce development time and costs:
A maintainable program requires less time and effort to modify, which reduces
development time and costs
Enables collaboration:
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:
A maintainable program is more likely to be updated and maintained over time, which
increases its lifespan and usefulness
Adapt to changing requirements:
A maintainable program is easier to modify to adapt to changing requirements or new
features
How do you create a well maintained program?
Use meaningful identifiers:
Identifiers are names given to variables, constants, arrays, procedures and functions
Use descriptive and meaningful identifiers to make your code easier to understand
and maintain
Avoid using single letters or abbreviations that may not be clear to others
Use the commenting feature provided by the programming language:
Comments are used to add descriptions to the code that help readers understand
what the code is doing
Use comments to explain the purpose of variables, constants, procedures, functions
and any other parts of the code that may not be immediately clear
Use comments to document any assumptions or limitations of the code
Use procedures and functions:
Procedures and functions are reusable blocks of code that perform specific tasks
Using procedures and functions allows you to modularise your code and make it easier
to understand, debug and maintain
Procedures and functions should have descriptive names that clearly indicate what
they do
Relevant and appropriate commenting of syntax:
Commenting of syntax is used to explain the purpose of individual lines or blocks of
code within the program
Use commenting on syntax to describe complex algorithms, or to provide additional
information on the purpose or behaviour of code
YOUR NOTES
IGCSE Computer Science CIE
9. Databases
CONTENTS
9.1 Database Theory
Databases
Primary Keys
9.2 SQL
SQL
YOUR NOTES
Worked Example
A Database Table Containing Pet Details
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 bepresented with an example database table and identify
eitherhow manfields there areor how many records there areso makesure
you remember a recordis row and a field is a column
Type Description
This type of validation checks the number of characters that have been entered into a
Length
field. For example, you might make phone numbers entered have to be eleven
Check
characters long
Format This type of validation checks data entered meets an exact format. For example, a
Check product code might have to be two letters followed by five numbers
Range A range check will check the number entered is within a specific range. For example,
Check the age of a dog would be between 0 - 40. Any other number would be disallowed
Presence
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 field. For
Type
example, if text was entered into a field which is supposed to contain the date of birth
Check
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 of the number,
Check
which is calculated based on a specific algorithm applied to the other digits in the
Digits
number. When the data is re-entered the same algorithm can be applied and if it
produces a different result the code is incorrect
YOUR NOTES
Worked Example
A Database Table Containing Student Grades
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
between 0 and 100 are entered [2]
This data type allows letters, special characters like spaces and
Text/Alphanumeric NG321AE
punctuation and numbers to be entered into a field
This allows single characters to be entered into a field.
Character Characters can be any alphanumeric value and can be A
lowercase or uppercase
This data type can be used in fields where there are only two
Boolean possible options. Data is stored as a 1 or 0 in the database but True/False
can be used to represent True/False or Yes/No
Integer Only whole numbers can be entered 15
Real Numbers including decimal numbers can be stored 30.99
Only dates or times can be entered into a field with this type. A
Date/Time 180855
format for the date/time can also be assigned to the field
YOUR NOTES
Worked Example
A Database Table Containing Dog Details
In the example customer table, the primary key would be the CustomerID because each
customer’s ID is unique
If there was a customer with the same name they could be identified correctly using the
CustomerID
YOUR NOTES
Worked Example
A database table containing the details of dogs
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 [1]
SQL
Records in a database can be searched and data can be manipulated using 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:
SELECT the fields you want to display
FROM the table/tables containing the data you wish to search
WHERE the search criteria
A Database Table Containing Movie Details
Example
SELECT Name, Rating
FROM Movie
WHERE Rating>8.4;
The results of this query would be:
Name Rating
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 YOUR NOTES
in the WHERE line of a SQL query
SQL Comparison Operators
Operator Description
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
For example, WHERE Genre=”Comedy” OR Genre=”Family”
YOUR NOTES
Worked Example
A database table, Dogs2023, is used to keep a record of all dogs registered at a
veterinary practice
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]
The query has returned four fields and all records because there were no WHERE criteria.
The records are sorted by Name alphabetically
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
Descending order is the highest number to the lowest
1 Sausages 1.99 3
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
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
The result of this query would be 3
This is because there are three products with a price greater than £2 (Chips, Beans,
Bananas)
YOUR NOTES
IGCSE Computer Science CIE
CONTENTS
10.1 Logic Gates
Logic Gates
Logic Circuits
Truth Tables
10.2 Logic Expressions
Logic Expressions
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 operation
Logic gates can be combined to carry out meaningful functions such as performing
calculations or checking if data meets certain conditions
A table showing the symbol used to represent each logic gate
The NOT gate takes a single binary input and outputs the
NOT
opposite of the input
The AND gate takes two inputs and produces one output
Only two positive inputs (1 and 1) will result in a positive
AND
output of 1
If either of the inputs is a 0 the output will be a 0
YOUR NOTES
A NAND gate is a combination of an AND gate followed
NAND by a NOT gate. If both inputs are a 1 it will output a 0. Any
other combination of inputs will result in an output of 1
Exam Tip
You will need to eitherdraw 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 gateand the logic rules for each one
Exam Tip
You may be asked to draw a logic circuit from a logic statement or a boolean
expression. Circuits must bedrawn without simplification
Logic circuits will belimitedto a maximum of threeinputs and one output
This logic circuit contains three inputs (A, B and C) YOUR NOTES
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
example above), from a truth table or from a boolean expression
Input Output
A Z
0 1
1 0
AND gate
An AND gate has two inputs
InputOutput
A B Z
0 0 0
0 1 0
1 0 0
1 1 1 YOUR NOTES
The AND gate truth table shows the only combination of inputs which will result in a positive
output is 1 and 1
OR gate
An OR gate has two inputs
Input Output
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
Input Output
A B Z
0 0 1
0 1 0 YOUR NOTES
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
Input Output
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
YOUR NOTES
Input Output
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
When creating a truth table for multiple inputs, begin by entering the possible 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
0 0 1 1 YOUR NOTES
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
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 operation on columns E
and C
0 0 0 1 0 0
0 0 1 1 0 1
0 1 0 1 1 1 YOUR NOTES
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
YOUR NOTES
Worked Example
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
A Z
NOT Z=NOT A
0 1
1 0
AB Z
000
AND Z=A AND B
0 1 0
1 00
1 1 1
A B Z
0 0 0
OR Z=A OR B
0 1 1
1 0 1
1 1 1
YOUR NOTES
A B Z
0 0 1
NAND Z=A NAND B
0 1 1
1 0 1
1 1 0
A B Z
0 0 1
NOR Z=A NOR B
0 1 0
1 0 0
1 1 0
A B Z
0 0 0
XOR Z=A XOR B
0 1 1
1 0 1
1 1 0
Logic circuits containing multiple gates can also be expressed as logic
expressions/statements
An example logic circuit containing two inputs
The logic circuit above can be expressed as the logic expression Q= NOT(A OR B)
YOUR NOTES
The logic circuit above can be expressed as the logic expression Q= (NOT A) AND B
The logic circuit above can be expressed as the logic expression P = ((NOT A) OR B) NAND
C
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