0% found this document useful (0 votes)
40 views115 pages

IGCSE Computer Science Algorithms

Uploaded by

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

IGCSE Computer Science Algorithms

Uploaded by

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

Compiled by : Shyam Subrahmanya

IGCSE Computer Science CIE


7. Algorithm design and problem-solving

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

iGCSE Computer Science(0478) - Paper-2 Page 1 of 115


Compiled by : Shyam Subrahmanya

7.2 Algorithms YOUR NOTES



Explaining 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

Total ← Total + Number

Count ← Count + 1

UNTIL Count > 10

OUTPUT Total

iGCSE Computer Science(0478) - Paper-2 Page 2 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 3 of 115


Compiled by : Shyam Subrahmanya

ENDIF YOUR NOTES


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]

iGCSE Computer Science(0478) - Paper-2 Page 4 of 115


Compiled by : Shyam Subrahmanya

7.3 Standard Methods YOUR NOTES



Standard Methods

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

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

iGCSE Computer Science(0478) - Paper-2 Page 5 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES

IF Found = TRUE

THEN

OUTPUT Number, “ found at position “, Counter

ELSE

OUTPUT Number, “ not found”

ENDIF

iGCSE Computer Science(0478) - Paper-2 Page 6 of 115


Compiled by : Shyam Subrahmanya

Bubble Sort YOUR NOTES


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

iGCSE Computer Science(0478) - Paper-2 Page 7 of 115


Compiled by : Shyam Subrahmanya

IF Mylist[Index] > Mylist[Index + 1] YOUR NOTES


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

iGCSE Computer Science(0478) - Paper-2 Page 8 of 115


Compiled by : Shyam Subrahmanya

Totalling & Counting YOUR NOTES


Totalling 
Totalling involves keeping a running total of values entered into the algorithm. 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 algorithm 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 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

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

iGCSE Computer Science(0478) - Paper-2 Page 9 of 115


Compiled by : Shyam Subrahmanya

Maximum, Minimum & Average YOUR NOTES


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

iGCSE Computer Science(0478) - Paper-2 Page 10 of 115


Compiled by : Shyam Subrahmanya

7.5 Identifying Errors YOUR NOTES



Identifying Errors

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

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

iGCSE Computer Science(0478) - Paper-2 Page 11 of 115


Compiled by : Shyam Subrahmanya

ELSE YOUR NOTES


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

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

iGCSE Computer Science(0478) - Paper-2 Page 12 of 115


Compiled by : Shyam Subrahmanya

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

IF Number >= 100 AND Number <= 200


THEN
OUTPUT Number
ENDIF

iGCSE Computer Science(0478) - Paper-2 Page 13 of 115


Compiled by : Shyam Subrahmanya

7.1 Development Life Cycle YOUR NOTES



Program Development Life Cycle - Analysis

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

iGCSE Computer Science(0478) - Paper-2 Page 14 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES

Figure 2: The geographical London undergroundtrain 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 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

iGCSE Computer Science(0478) - Paper-2 Page 15 of 115


Compiled by : Shyam Subrahmanya

7.4 Validation and Testing YOUR NOTES



Validation

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

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

iGCSE Computer Science(0478) - Paper-2 Page 16 of 115


Compiled by : Shyam Subrahmanya

Length check YOUR NOTES


Length checks check either that the input data is of an exact number of characters or in a 
user specified number range of characters
A bank 4-digit PIN number may be an example of an exact number of characters. 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 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

IF LENGTH(Password) < 8 OR LENGTH(Password) > 20

THEN

OUTPUT “Your password must be between 8 and 20 characters 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 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

IF Number <> DIV(Number, 1)

THEN

iGCSE Computer Science(0478) - Paper-2 Page 17 of 115


Compiled by : Shyam Subrahmanya

OUTPUT “Not a whole number, please try again” YOUR NOTES


ENDIF 

UNTIL Number = DIV(Number , 1)

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

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

OUTPUT “ID number must be 6 characters long”

iGCSE Computer Science(0478) - Paper-2 Page 18 of 115


Compiled by : Shyam Subrahmanya

END IF YOUR NOTES


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 character”

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 character”

iGCSE Computer Science(0478) - Paper-2 Page 19 of 115


Compiled by : Shyam Subrahmanya

ENDIF YOUR NOTES


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

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

iGCSE Computer Science(0478) - Paper-2 Page 20 of 115


Compiled by : Shyam Subrahmanya

Verification YOUR NOTES


Verification is the act of checking data is accurate when entered into a system 
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”

iGCSE Computer Science(0478) - Paper-2 Page 21 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 22 of 115


Compiled by : Shyam Subrahmanya

7.1 Development Life Cycle YOUR NOTES



Program Development Life Cycle - Design

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

iGCSE Computer Science(0478) - Paper-2 Page 23 of 115


Compiled by : Shyam Subrahmanya

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:

iGCSE Computer Science(0478) - Paper-2 Page 24 of 115


Compiled by : Shyam Subrahmanya

Structure Diagrams YOUR NOTES


Structure diagrams show hierarchical top-down design in a visual form. Each problem is 
divided into sub-problems and each sub-problem divided into further sub-problems. At
each level the problem is broken down into more detailed tasks that can be implemented
using a single subroutine

Figure 1: A structure diagram

Figure 2: A structure diagram for a mobile application

iGCSE Computer Science(0478) - Paper-2 Page 25 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 26 of 115


Compiled by : Shyam Subrahmanya

Flowcharts YOUR NOTES


Flowcharts show how algorithms can be represented visually in a diagrammatic 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:
Terminator symbols: Also known as Begin/End symbols. These indicate where a
flowchart starts and stops
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 symbol could be used to represent sorting or searching
in a separate flowchart. This is represented by a process with an additional bar on
either side of the symbol
Input/Output symbols: These show the input of data and output of data
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
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)

iGCSE Computer Science(0478) - Paper-2 Page 27 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES

Figure 4: Flowchart for finding thelargest 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 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

iGCSE Computer Science(0478) - Paper-2 Page 28 of 115


Compiled by : Shyam Subrahmanya

7.4 Validation and Testing YOUR NOTES



Test Data

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

iGCSE Computer Science(0478) - Paper-2 Page 29 of 115


Compiled by : Shyam Subrahmanya

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]

iGCSE Computer Science(0478) - Paper-2 Page 30 of 115


Compiled by : Shyam Subrahmanya

7.5 Identifying Errors YOUR NOTES



Writing & Amending Algorithms

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 requirements 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
For example, will data be entered via input boxes or file upload/opening? Is data to be
stored in a file? What overall processes will be performed 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 creating 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
Meaningful variable names help readers understand what data is being stored and
their purpose
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 Percentage 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 displayed 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

iGCSE Computer Science(0478) - Paper-2 Page 31 of 115


Compiled by : Shyam Subrahmanya

Exam Tip YOUR NOTES


 Writing algorithms in an exam can bechallenging and time consuming.It's

important to allocateyour time carefully to not spend too littleor too long
writing an algorithm
You will likely makemistakes and rewriteyour algorithm a few times. Use scrap
paper or the back of your exam paper if possibleto sketch out your ideas before
committing to your answer. This will makeyour answerclearer, 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 calculatethe total”, and “This part will
allocategrades”. You can then put the whole algorithm togetherin order later
Makea plan beforeyou start answering the question and writing your algorithm.
A plan can besimple but allows you to order your thoughts, for example:
Part 1: Declareand initialise variables
Part 2: Allocatemarks for each subject
Part 3: Allocategrades for each student's subject
Part 4: Includea loop
Part 5: Output all necessary data
Pseudocodedoes not have a syntax, therefore you can writean algorithm in
any way which is easily understandable.Caution is advisedto stick to iGCSE
specification standards to ensureyour answeris consistent and easy for
examiners to follow
Be sureto use variable names and data providedin the question as given.
Failureto doso will lose you marks
Remember to comment on your code. It helps both you and the examiner
understand your answerand also awards marks in the mark scheme!

iGCSE Computer Science(0478) - Paper-2 Page 32 of 115


Compiled by : Shyam Subrahmanya

7.1 Development Life Cycle YOUR NOTES



Program Development Life Cycle - Coding

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

iGCSE Computer Science(0478) - Paper-2 Page 33 of 115


Compiled by : Shyam Subrahmanya

7.4 Validation and Testing YOUR NOTES



Trace Tables

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

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

iGCSE Computer Science(0478) - Paper-2 Page 34 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES

Figure 1: A flowchart to determinethehighest of ten user enterednumbers

Trace table for Figure 1: Highest number


Count Highest Number Output
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

iGCSE Computer Science(0478) - Paper-2 Page 35 of 115


Compiled by : Shyam Subrahmanya

8 9 9 YOUR NOTES
9 12 12 

10 10 12 is your highest number

 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

iGCSE Computer Science(0478) - Paper-2 Page 36 of 115


Compiled by : Shyam Subrahmanya

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

[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

iGCSE Computer Science(0478) - Paper-2 Page 37 of 115


Compiled by : Shyam Subrahmanya

7.1 Development Life Cycle YOUR NOTES



Program Development Life Cycle - Testing

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

iGCSE Computer Science(0478) - Paper-2 Page 38 of 115


Compiled by : Shyam Subrahmanya

IGCSE Computer Science CIE


8. Programming

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

iGCSE Computer Science(0478) - Paper-2 Page 39 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 40 of 115


Compiled by : Shyam Subrahmanya

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

Visual Basic example:

iGCSE Computer Science(0478) - Paper-2 Page 41 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 42 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 43 of 115


Compiled by : Shyam Subrahmanya

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
PRINT "Customer: ", Count, " Balance: ", Balance[Count], " Email: ",Email[Count] [3 marks]
Count ← Count + 1
UNTIL Count = 30 [1 mark]

You could also answer with a WHILE or FOR loop

iGCSE Computer Science(0478) - Paper-2 Page 44 of 115


Compiled by : Shyam Subrahmanya

8.1 Programming Concepts

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:

Python Java Visual Basic

variable_name = data_type Dim variable_name As


Syntax
value variable_name; data_type

Example x=5 int x Dim x As Integer

It is important to choose the correct data type for a given situation to ensure accuracy and
efficiency in the program.

iGCSE Computer Science(0478) - Paper-2 Page 45 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 46 of 115


Compiled by : Shyam Subrahmanya

Variables & Constants

Variables & Constants


Variables and constants are used to store data in a program. Variables can be changed during
program execution 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 starting
with a letter and not containing spaces
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

iGCSE Computer Science(0478) - Paper-2 Page 47 of 115


Compiled by : Shyam Subrahmanya

 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 mark]


DECLARE age : INTEGER [1 mark]

iGCSE Computer Science(0478) - Paper-2 Page 48 of 115


Compiled by : Shyam Subrahmanya

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 promptthe userfor input clearly, and format the output to makeit
readable and understandable.

iGCSE Computer Science(0478) - Paper-2 Page 49 of 115


Compiled by : Shyam Subrahmanya

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

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

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

iGCSE Computer Science(0478) - Paper-2 Page 51 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 52 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 53 of 115


Compiled by : Shyam Subrahmanya

} 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 mark)
ELSE IF b > c THEN PRINT b (1 mark)
ELSE PRINT c (1 mark)

iGCSE Computer Science(0478) - Paper-2 Page 54 of 115


Compiled by : Shyam Subrahmanya

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

PRINT "Invalid number"

iGCSE Computer Science(0478) - Paper-2 Page 55 of 115


Compiled by : Shyam Subrahmanya

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

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:

iGCSE Computer Science(0478) - Paper-2 Page 56 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 57 of 115


Compiled by : Shyam Subrahmanya

 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

iGCSE Computer Science(0478) - Paper-2 Page 58 of 115


Compiled by : Shyam Subrahmanya

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

Example in Visual Basic:


For count = 1 To 10

Console.WriteLine(count)

Next count

iGCSE Computer Science(0478) - Paper-2 Page 59 of 115


Compiled by : Shyam Subrahmanya

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

WHILE temperature > 37

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

iGCSE Computer Science(0478) - Paper-2 Page 60 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 61 of 115


TotallingCompiled by : Shyam Subrahmanya
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)

iGCSE Computer Science(0478) - Paper-2 Page 62 of 115


Compiled by : Shyam Subrahmanya

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

if num > 5 then

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

iGCSE Computer Science(0478) - Paper-2 Page 63 of 115


Compiled by : Shyam Subrahmanya

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]
(1
FOR x ← 1 TO 20
mark)
INPUT Number

(1
IF Number > 50 THEN Total ← Total + 1
mark)
NEXT x

(1
PRINT total
mark)

iGCSE Computer Science(0478) - Paper-2 Page 64 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 65 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 66 of 115


Compiled by : Shyam Subrahmanya

 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

iGCSE Computer Science(0478) - Paper-2 Page 67 of 115


Compiled by : Shyam Subrahmanya

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;

iGCSE Computer Science(0478) - Paper-2 Page 68 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 69 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 70 of 115


Compiled by : Shyam Subrahmanya

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)

iGCSE Computer Science(0478) - Paper-2 Page 71 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 72 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 73 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 74 of 115


Compiled by : Shyam Subrahmanya

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

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 {

iGCSE Computer Science(0478) - Paper-2 Page 75 of 115


Compiled by : Shyam Subrahmanya

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.

iGCSE Computer Science(0478) - Paper-2 Page 76 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 77 of 115


Compiled by : Shyam Subrahmanya

Procedures & Functions

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

iGCSE Computer Science(0478) - Paper-2 Page 78 of 115


Compiled by : Shyam Subrahmanya

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)

iGCSE Computer Science(0478) - Paper-2 Page 79 of 115


Compiled by : Shyam Subrahmanya

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)

area ← length * width

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

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

iGCSE Computer Science(0478) - Paper-2 Page 80 of 115


Compiled by : Shyam Subrahmanya

Local & Global Variables

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

iGCSE Computer Science(0478) - Paper-2 Page 81 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 82 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 83 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 84 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
IGCSE Computer Science CIE 

9. Databases

CONTENTS
9.1 Database Theory
Databases
Primary Keys
9.2 SQL
SQL

iGCSE Computer Science(0478) - Paper-2 Page 85 of 115


Compiled by : Shyam Subrahmanya

9.1 Database Theory YOUR NOTES



Databases

Single Table Databases


A database is a structured collection of data so it can be searched, sorted, filtered and
analysed quickly
Data in a database can be any type of data including text, images, videos, sound
Databases use tables to store data
Tables have records of data represented by one row
In the example below, each row represents the data stored about a single customer
(the customer’s record)
In the customer table there are 3 records
Each record is divided into fields (CustomerID, FirstName, LastName, DOB and Phone
Number)
A Database Table Containing Customer Details

CustomerID FirstName LastName DOB PhoneNumber

1 Andrea Bycroft 05031976 0746762883


2 Melissa Langler 22012001 0756372892
3 Amy George 22111988 0746372821

Fields are represented by the columns in a table


There are 5 fields in the customer table
The first row in a table contains the field names which is the heading for the data stored
in that field
Each field in a table has a data type which defines what data can be entered into that
field

iGCSE Computer Science(0478) - Paper-2 Page 86 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 Worked Example

A Database Table Containing Pet Details

DogID Name Breed Age Gender

DG12 Smokey Poodle 12 M


Springer
DG34 Harvey 10 M
Spaniel
DG48 Maisie Labradoodle 3 F
DG49 Maggie Labradoodle 3 F
DG88 Winston Bulldog 7 M
Golden
DG95 Shona 6 F
Retriever

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

iGCSE Computer Science(0478) - Paper-2 Page 87 of 115


Compiled by : Shyam Subrahmanya

Validation and Verification YOUR NOTES


Verification checks check whether the data that has been entered is the correct data and is 
accurate
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
A validation rule controls what data can be entered into that field
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 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

iGCSE Computer Science(0478) - Paper-2 Page 88 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 Worked Example

A Database Table Containing Student Grades

StudentID FirstName LastName MarkSubmitted Percentage

1483792 Shanay Giles Y 55


1498378 Poppy Petit N 20
1500121 Diya Dinesh Y 74
1382972 Joe Swaile Y 68
1598264 Anton Smith Y 34
1548282 Felicity Hall N 47

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]

iGCSE Computer Science(0478) - Paper-2 Page 89 of 115


Compiled by : Shyam Subrahmanya

Data Types YOUR NOTES


Table fields are represented by columns in a table 
There are 5 fields in the customer table below
These include CustomerID, FirstName, LastName, DOB and PhoneNumber
A Database Table Containing Customer Details

CustomerID FirstName LastName DOB PhoneNumber

1 Andrea Bycroft 05031976 0746762883


2 Melissa Langler 22012001 0756372892
3 Amy George 22111988 0746372821

Each field in a table, has a data type


Common data types include text/alphanumeric, character, boolean, integer, real
and date/time
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

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

iGCSE Computer Science(0478) - Paper-2 Page 90 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 Worked Example

A Database Table Containing Dog Details

DogID Name Breed Age Gender

DG12 Smokey Poodle 12 M


Springer
DG34 Harvey 10 M
Spaniel
DG48 Maisie Labradoodle 3 F
DG49 Maggie Labradoodle 3 F
DG88 Winston Bulldog 7 M
Golden
DG95 Shona 6 F
Retriever

What data type should Age be?


[1]
Integer [1]
What data type should DogID be?
[1]
Text/Alphanumeric [1]

iGCSE Computer Science(0478) - Paper-2 Page 91 of 115


Compiled by : Shyam Subrahmanya

Primary Keys YOUR NOTES



Primary Keys
Each table has a primary key field which acts as a unique identifier
Each item of data in this field is unique
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

CustomerID FirstName LastName DOB PhoneNumber

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 because each
customer’s ID is unique
If there was a customer with the same name they could be identified correctly using the
CustomerID

iGCSE Computer Science(0478) - Paper-2 Page 92 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 Worked Example

A database table containing the details of dogs

DogID Name Breed Age Gender

DG12 Smokey Poodle 12 M


DG34 Harvey Springer Spaniel 10 M
DG48 Maisie Labradoodle 3 F
DG49 Maggie Labradoodle 3 F
DG88 Winston Bulldog 7 M
DG95 Shona Golden Retriever 6 F

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]

iGCSE Computer Science(0478) - Paper-2 Page 93 of 115


Compiled by : Shyam Subrahmanya

9.2 SQL YOUR NOTES



SQL

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

MovieID Name Genre Certificate Rating

M23 Moana Family U 8.1


Shaun of
M8 Comedy 18 8.7
the Dead
M56 Die Hard Action 18 8.4
M34 Big Family PG 8.5

Example
SELECT Name, Rating
FROM Movie
WHERE Rating>8.4;
The results of this query would be:

Name Rating

Shaun of the Dead 8.7


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

iGCSE Computer Science(0478) - Paper-2 Page 94 of 115


Compiled by : Shyam Subrahmanya

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

> 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
For example, WHERE Genre=”Comedy” OR Genre=”Family”

iGCSE Computer Science(0478) - Paper-2 Page 95 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 Worked Example

A database table, Dogs2023, is used to keep a record of all dogs registered at a
veterinary practice

DogID Name Breed Age Gender

DG12 Smokey Poodle 12 M


Springer
DG34 Harvey 10 M
Spaniel
DG48 Maisie Labradoodle 3 F
DG49 Maggie Labradoodle 3 F
DG88 Winston Bulldog 7 M
Golden
DG95 Shona 6 F
Retriever

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]

iGCSE Computer Science(0478) - Paper-2 Page 96 of 115


Compiled by : Shyam Subrahmanya

ORDER BY YOUR NOTES


You can enter a fourth line to the statement using the ORDER BY command, followed by 
ASC or DESC
If you enter ASC the results of the query will be sorted in ascending order
If you enter DESC the results of the query are sorted in descending order
Example
SELECT Name,Genre, Certificate, Rating
FROM Movie
ORDER BY Name ASC
The results of this query would be:

Name Genre Certificate Rating

Big Family PG 8.5


Die Hard Action 18 8.4
Moana Family U 8.1
Shaun of the Dead Comedy 18 8.7

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

iGCSE Computer Science(0478) - Paper-2 Page 97 of 115


Compiled by : Shyam Subrahmanya

SUM and COUNT commands YOUR NOTES


The SUM command can be used to add numerical data 
The COUNT command can be used to count items of data

ProductID ProductName Price QuantityInStock

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)

iGCSE Computer Science(0478) - Paper-2 Page 98 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
IGCSE Computer Science CIE 

10. Boolean logic

CONTENTS
10.1 Logic Gates
Logic Gates
Logic Circuits
Truth Tables
10.2 Logic Expressions
Logic Expressions

iGCSE Computer Science(0478) - Paper-2 Page 99 of 115


Compiled by : Shyam Subrahmanya

10.1 Logic Gates YOUR NOTES



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

Gate Symbol Description

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

The OR gate takes two inputs and produces one output


OR
If either of the inputs is positive (1) the output will be 1

iGCSE Computer Science(0478) - Paper-2 Page 100 of 115


Compiled by : Shyam Subrahmanya

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

A NOR gate is a combination of an OR gate followed by a


NOR NOT gate. If both inputs are 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 the inputs are


XOR
different to one another (a 1 and a 0)

 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

iGCSE Computer Science(0478) - Paper-2 Page 101 of 115


Compiled by : Shyam Subrahmanya

Logic Circuits YOUR NOTES



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 bedrawn without simplification
Logic circuits will belimitedto a maximum of threeinputs and one output

An example of Logic Circuit

iGCSE Computer Science(0478) - Paper-2 Page 102 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 103 of 115


Compiled by : Shyam Subrahmanya

Truth Tables YOUR NOTES



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

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

iGCSE Computer Science(0478) - Paper-2 Page 104 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 105 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 106 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 107 of 115


Compiled by : Shyam Subrahmanya

Exam Tip YOUR NOTES


 You will only beasked to createtruth tables for logic circuits with three inputs.

The number of rows you shouldhave in a three input truth table is 8 (not
including the headings)

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

The fourth column labelled D represents the output of NOT A


A B C D (NOT A) E Z
0 0 0 1

iGCSE Computer Science(0478) - Paper-2 Page 108 of 115


Compiled by : Shyam Subrahmanya

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

D (NOT E ((NOT A) AND


A B C Z
A) 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 operation on columns E
and C

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


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

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

iGCSE Computer Science(0478) - Paper-2 Page 109 of 115


Compiled by : Shyam Subrahmanya

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

iGCSE Computer Science(0478) - Paper-2 Page 110 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES
 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
[4]

iGCSE Computer Science(0478) - Paper-2 Page 111 of 115


Compiled by : Shyam Subrahmanya

10.2 Logic Expressions YOUR NOTES



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

Gate Symbol Truth Table Logic Expression

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

iGCSE Computer Science(0478) - Paper-2 Page 112 of 115


Compiled by : Shyam Subrahmanya

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)

An example logic circuit containing two inputs

iGCSE Computer Science(0478) - Paper-2 Page 113 of 115


Compiled by : Shyam Subrahmanya

YOUR NOTES

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)

iGCSE Computer Science(0478) - Paper-2 Page 114 of 115


Compiled by : Shyam Subrahmanya

Exam Tip YOUR NOTES


 You may be requiredto writea logic expression/statement from a truth table or

a logic circuit. You may also have to dothe opposite - draw a logic circuit 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

iGCSE Computer Science(0478) - Paper-2 Page 115 of 115

You might also like