Computer Science o Level Edexcel Book
Computer Science o Level Edexcel Book
E
Series Editor: Ann Weidmann
PL
Pearson Edexcel International GCSE (9–1) Computer Science provides
comprehensive coverage of the new specification and is designed to supply
students with the best preparation possible for the examination:
M
• Signposted transferable skills
• Reviewed by a language specialist to ensure the book is written in a clear
and accessible style
• Glossary of key Computer Science terminology INFORMATION AND
• eBook included COMMUNICATION
COMPUTER SCIENCE
planning, teaching and assessment support.
SA
For Pearson Edexcel International GCSE (9–1) Computer Science specification
(4CP0) for first teaching 2017.
Student Book
David Waller, Chris Charles, Pete Dring, Alex Hadwen-Bennett, Jason Welch, Shaun Whorton
www.pearson.com/international-schools
Series Editor: Ann Weidmann
eBook
included
COMPUTER SCIENCE
Student Book
David Waller
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Chris Charles
Pete Dring
Alex Hadwen-Bennett
Jason Welch
Shaun Whorton
SERIES EDITOR
Ann Weidmann
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 1 23/05/20 5:28 PM
Published by Pearson Education Limited, 80 Strand, London, WC2R 0RL. Endorsement statement
In order to ensure that this resource offers high-quality support for the associated
https://www.pearson.com/international-schools Pearson qualification, it has been through a review process by the awarding
body. This process confirmed that this resource fully covers the teaching and
Copies of official specifications for all Pearson Edexcel qualifications may be found learning content of the specification at which it is aimed. It also confirms that it
on the website: https://qualifications.pearson.com demonstrates an appropriate balance between the development of subject skills,
knowledge and understanding, in addition to preparation for assessment.
Text © Pearson Education Limited 2020
Designed by Pearson Education Limited 2020 Endorsement does not cover any guidance on assessment activities or processes
Typeset by © SPi Global (e.g. practice questions or advice on how to answer assessment questions)
Edited by Hillary Coaster and Sarah Wright included in the resource, nor does it prescribe any particular approach to the
Original illustrations © Pearson Education Limited 2020 teaching or delivery of a related course.
Picture research by Integra
Cover design © Pearson Education Limited 2020 While the publishers have made every attempt to ensure that advice on the
With thanks to Sam Hartburn qualification and its assessment is accurate, the official specification and
associated assessment guidance materials are the only authoritative source of
The right of David Waller, Chris Charles, Pete Dring, Alex Hadwen-Bennett, Jason information and should always be referred to for definitive guidance.
Welch, Shaun Whorton to be identified as the authors of this work has been
asserted by him in accordance with the Copyright, Designs and Patents Act 1988. Pearson examiners have not contributed to any sections in this resource relevant to
examination papers for which they have responsibility.
First published 2020
Examiners will not use endorsed resources as a source of material for any
22 21 20 assessment set by Pearson. Endorsement of a resource does not mean that the
10 9 8 7 6 5 4 3 2 1 resource is required to achieve this Pearson qualification, nor does it mean that it
is the only suitable material available to support the qualification, and any resource
British Library Cataloguing in Publication Data lists produced by the awarding body shall include this and other appropriate
A catalogue record for this book is available from the British Library resources.
Copyright notice
All rights reserved. No part of this publication may be reproduced in any form or by
any means (including photocopying or storing it in any medium by electronic means
and whether or not transiently or incidentally to some other use of this publication)
without the written permission of the copyright owner, except in accordance with the
provisions of the Copyright, Designs and Patents Act 1988 or under the terms of a
licence issued by the Copyright Licensing Agency, 5th Floor, Shackleton House,
4 Battlebridge Lane, London, SE1 2HX (www.cla.co.uk). Applications for the copyright
owner’s written permission should be addressed to the publisher.
Acknowledgements
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Text Credits
Loon LLC: Extracts from Loon LLC, © Loon LLC, 256; McKinsey & Company:
Stefan Heck, Sri Kasa, Dickon Pinner, Creating Value in the Semiconductor
industry, © 2011, McKinsey & Company, 264.
Image Credits
(key: b-bottom; c-center; l-left; r-right; t-top)
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 2 22/05/20 6:00 PM
CONTENTS iii
COURSE STRUCTURE iv
ABOUT THIS BOOK vi
ASSESSMENT OVERVIEW viii
UNIT 1: PROBLEM SOLVING 2
UNIT 2: PROGRAMMING 32
UNIT 3: DATA 108
UNIT 4: COMPUTERS 158
UNIT 5: COMMUNICATION AND THE INTERNET 200
UNIT 6: THE BIGGER PICTURE 242
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 3 23/05/20 5:58 PM
iv COURSE STRUCTURE
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 4 20/05/20 7:25 PM
COURSE STRUCTURE v
EXAM
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
PREPARATION272
PAPER 1: PRINCIPLES
OF COMPUTER SCIENCE272
PAPER 2: APPLICATION
OF COMPUTATIONAL
THINKING283
APPENDICES291
APPENDIX 1
COMMAND WORDS291
APPENDIX 2
FLOWCHART SYMBOLS293
APPENDIX 3 PSEUDOCODE
COMMAND SET294
GLOSSARY299
INDEX 306
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 5 20/05/20 7:25 PM
vi ABOUT THIS BOOK
The course has been structured so that teaching and learning Paper 1 is Principles of Computer Science and Paper 2 is
can take place in any order, both in the classroom and in any Application of Computational Thinking. Knowing how to
independent learning. The book contains six units that match apply your learning to both of these will be critical for your
the six areas of content in the specification: Problem Solving,
success in the exam. There is a real applied focus to the
Programming, Data, Computers, Communication and the
book. You will be encouraged to put the theory you are
Internet, The Bigger Picture.
learning into context and apply what you have learned to
Each unit is split into multiple sections to break down your own practical activities.
content into manageable chunks and to ensure full
coverage of the specification.
Learning objectives
Each section starts with a list of
what you will learn from it. They Activity
are carefully tailored to address Each chapter includes activities
key assessment objectives to embed understanding through
central to the course. practical tasks and questions.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
12 BINARY This shape is filled with a colour named ‘Alice blue’ . In binary you would
have to enter 111100001111100011111111 every time you wanted to use it.
However, as mentioned on page 123, hexadecimal comes to our rescue. Using
hexadecimal, you would only have to enter #F0F8FF.
SUBJECT VOCABULARY Binary is a base-2 numeral system using only two digits: 0 and 1. It is a
positional notation where digits have place values, like the denary or decimal
binary information represented by only system that we are familiar with. For example, in the decimal system, each 1 in
two values (e.g. a voltage or no voltage; on the number 111 represents a different value i.e. from left to right they represent
or off). There are no communication errors FILE SIZES The file size for a bitmap image is calculated by finding the total number of pixels
100, 10 and 1.
or misunderstandings because there are no and multiplying that by the number of bits used to represent each pixel, or:
small differences
Width × Height × Colour depth
digital information represented by certain
LEARNING OBJECTIVES
fixed values (e.g. high, medium or low). Any The file size of the left-hand image on page 125 is:
signal between these values would be
◼ Understand that computers use binary to represent data (numbers, text,
meaningless and not used. Sending and 4288 (width) × 2848 (height) × 24 (bit colour depth) = 293 093 376 bits
receiving systems do not have to be as sound, graphics) and program instructions
accurate as for analogue communication That is, 36 636 672 bytes.
◼ Understand how computers represent and manipulate numbers (unsigned
analogue using signals or information integers, signed integers [sign and magnitude, two’s complement])
represented by a quantity (e.g. an electric
◼ Be able to convert between binary and denary whole numbers (0–255) SKILLS
REASONING,
voltage or current) that is continuously PROBLEM SOLVING ACTIVITY 11
variable. Changes in the information being ◼ Understand how to perform binary arithmetic (adds, shifts [logical and
represented are indicated by changes in arithmetic]) and understand the concept of overflow KEY POINT IMAGE FILE SIZES
voltage. This method requires very
accurate sending and receiving systems ◼ Understand why hexadecimal notation is used and be able to convert Calculators are not allowed in the Create expressions and calculate the file sizes of the following images.
between hexadecimal and binary exam so you will be asked to just Express the sizes in bits and bytes.
create an expression to calculate
◼ Understand that file storage is measured in bytes and be able to calculate a A 256-colour image with a size of 640 × 480 pixels.
file sizes without showing a final
file sizes value. b A true-colour image with a size of 640 × 480 pixels.
WHY BINARY? Binary is needed to represent data and program instructions because of the REPRESENTATION OF SOUND All sounds are caused by vibrations. As objects such as our vocal cords or
way in which computers work. guitar strings vibrate backwards and forwards, they push the air molecules
GENERAL VOCABULARY alongside them, sending a wave of compressed molecules through the air.
GENERAL VOCABULARY The processor, which processes all of the data and instructions, contains
vibrations quickly moving backwards When these compression waves, or sound waves, reach our ears they set up
billions of transistors which are connected together to form circuits.
manipulate to handle or control and forwards about a fixed point vibrations in tiny sensory hairs in the inner ear. This sends nerve impulses to
something in a skilful manner The transistors act as switches, similar to light switches. They have only two the brain, which interprets them as the sounds we hear.
compressed pressed into a smaller states: on or off; they either transmit an electric current or they do not. A
space system with separate states is said to be digital. If there are two states, the
transistor a device that controls system is binary. There are no in-between states with different levels of current
electronic current as there would be in a dimmer switch, which produces different levels of
▶◼Figure 3.5 Sound waves travelling through Sound wave High pressure Low pressure
brightness in a bulb. A system such as this, where there is a continuous range
intensity the strength of something that the air from a vibrating bell
between two values, is said to be analogue.
can be measured, e.g. light, sound, heat
frequency the number per time unit, e.g. As there are only two states, on or off, the states are represented by the
number per second digits of the binary number system, 1 and 0. All of the data and program
transmit cause something to move from instructions processed by a computer are nothing more than streams of
one place to another millions of 1s and 0s.
Numbers, text, graphics and sound are all represented in the same way, as a
series of 1s and 0s. The program instructions that the processor is following
allow it to interpret them in different ways.
M03 IGCSE Computer Science SB2 Global 10220 UNIT3.indd 110 09/05/20 11:16 AM M03 IGCSE Computer Science SB2 Global 10220 UNIT3.indd 131 09/05/20 11:16 AM
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 6 20/05/20 7:25 PM
ABOUT THIS BOOK vii
4 UNIT 1 PROBLEM SOLVING 1 UNDERSTANDING ALGORITHMS UNIT 1 PROBLEM SOLVING 1 UNDERSTANDING ALGORITHMS 5
SUCCESSFUL ALGORITHMS
1 UNDERSTANDING ALGORITHMS
There are three points to consider when deciding whether an algorithm is
successful or not.
GENERAL VOCABULARY ◼ Accuracy – it must lead to the expected outcome (e.g. create a route from
It is important to be able to construct algorithms and be able to read them Beijing to Shanghai).
GENERAL VOCABULARY outcome the final result of an action
and follow their logic in solving particular problems. ◼ Consistency – it must produce the same result each time it is run.
construct a command to control the consistency not changing; always the ◼ Efficiency – it must solve the problem in the shortest possible time, using
order/flow in which instructions are same as few computer resources as possible. In this example, the mapping
executed (e.g. sequences, selection, atlas a book of maps software is replacing a manual method. If it were no faster than looking in
repetition)
LEARNING OBJECTIVES an atlas, then it would not be an improvement on the older method. Later
in the unit there is a section on algorithms that are used to sort and search
◼ Understand what an algorithm is
data. Some of these algorithms are more efficient than others and will sort
◼ Understand what algorithms are used for the data far more quickly.
◼ Interpret algorithms as flowcharts, pseudocode and written descriptions
◼ Use and describe the purpose of arithmetic operators
THE RELATIONSHIP BETWEEN Algorithms and programs are closely related, but they are not the same. An
◼ Understand how to code an algorithm in a high-level language ALGORITHMS AND PROGRAMS algorithm is a detailed design for a solution; a program is when that design is
implemented.
SUBJECT VOCABULARY
This unit is all about algorithms. We look at how algorithms are implemented
AN EXAMPLE OF AN ALGORITHM high-level programming language in high-level programming languages in Unit 2.
An interactive map is a useful way to find a route between two locations.
a programming language that is similar to
Figure 1.1 shows a route between two cities that was calculated by a mapping
natural human language
program.
SUBJECT VOCABULARY
The route on this interactive map has been calculated using an algorithm.
unambiguous this means that the
instructions cannot be misunderstood. ◼ It is unambiguous in telling the driver exactly what to do, like ‘turn left’,
Simply saying ‘turn’ would be ambiguous ‘turn right’ or ‘go straight’. DISPLAYING AN ALGORITHM We carry out many everyday tasks using algorithms because we are following a
(i.e. unclear) because you could turn left or ◼ It is a sequence of steps. set of instructions to achieve an expected result, for example, making a cup of
right. All instructions given to a computer ◼ It can be used again and will always provide the same result. coffee. If we have performed the task many times before, we usually carry out
must be unambiguous or it won’t know ◼ It provides a solution to a problem, in this case, how to get from Beijing to the instructions without thinking. But if we are doing something unfamiliar, such
what to do Shanghai. as putting together a flat-pack chest of drawers, then we follow the instructions
sequence an ordered set of instructions very carefully.
algorithm a precise method for solving a A solution to a problem with these characteristics is called an algorithm. Most
problems have more than one solution, so different algorithms can be created An algorithm can be expressed in different ways.
problem
for the same problem.
WRITTEN DESCRIPTIONS
A written description is the simplest way of expressing an algorithm. Here is
DID YOU KNOW? an algorithm describing the everyday task of making a cup of instant coffee:
The computer program that created
the algorithm to map travel from
Beijing to Shanghai was following ALGORITHM FOR MAKING A CUP OF COFFEE
an algorithm of its own – an
Fill kettle with water.
algorithm ordering it how to create
Turn on kettle.
another algorithm!
Place coffee in cup.
Wait for water to boil.
Pour water into cup.
Add milk and sugar.
Stir.
▶ Figure 1.1 A route calculated by a mapping
program
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 4 09/05/20 8:53 AM M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 5 09/05/20 8:54 AM
Summary
Quickly recap the core content of
each section.
Checkpoint
UNIT 3 DATA UNIT QUESTIONS 155
Checkpoints help you to check
UNIT QUESTIONS and reflect on your learning at the
REASONING,
end of each section. Strengthen
SKILLS AO2 1 a Add together the following 8-bit numbers. (1)
PROBLEM SOLVING
01011001 questions help you to consolidate
11100111
b Identify the problem that this addition has created. (1)
basic knowledge and understanding.
SKILLS
DECISION MAKING,
AO2 2 a Carry out a three-place logical right shift on the following binary
Challenge questions are more
demanding and ask you to apply
CRITICAL THINKING
number. 10010011 (2)
b Explain the effect of performing a right shift on a binary number. (2)
c Describe the steps needed to convert the binary number 11101110
into a hexadecimal one and show the result. (2) your learning.
HINT
Skills 1 a This is a straightforward question. Carry out the calculation and
write the result in the space provided. Remember to carry over if the
Relevant exam questions have addition of each pair of digits is greater than 1.
b This just requires a one- or two-word answer.
been assigned the key skills that 2 a Again, carry out the shift and write the result.
you will gain from undertaking b Here you have to explain what effect the shift will have. You could say
that it is equivalent to multiplying the number by…
them, allowing for a strong focus on c A longer answer is required. You should show stage by stage how
the conversion is carried out. For example, you could start by saying
particular academic qualities. These what the 8-bit binary number is divided into. You should set out the
explanation clearly and it could be in the form of a diagram.
CRITICAL THINKING,
SKILLS PROBLEM SOLVING
AO2 4 The following diagram shows a black and white image consisting of 36 pixels.
a Explain why 36 bits are needed to represent the pixels in the image. (2)
b Write the bit pattern needed to represent these pixels. (4)
Unit questions
These exam-style questions are
found at the end of each unit. They
are tailored to the Pearson Edexcel
specification to allow for the practice
Assessment objectives ▲◼Figure 3.19 A 36-pixel image of the letter ‘E’ and development of exam writing
Questions are tagged with c State the number of bits per pixel that would be needed if the image
technique. They also allow for
the relevant assessment was 16 colours rather than 2. (1)
practice responding to the command
objectives that are being words used in the exams.
examined.
M03 IGCSE Computer Science SB2 Global 10220 UNIT3.indd 155 09/05/20 11:16 AM
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 7 20/05/20 7:26 PM
viii
viii ASSESSMENT
UNIT 1 THE MARKET
OVERVIEW SPECIFICATION 1.1.1
ASSESSMENT OVERVIEW
The following tables give an overview of the assessment for this course. You should study this information closely
to help ensure that you are fully prepared and know exactly what to expect in each part of the assessment.
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 8 20/05/20 7:26 PM
ASSESSMENT OVERVIEW UNIT 1 THE MARKET ixix
ASSESSMENT SUMMARY
ASSESSMENT
PAPER 1 DESCRIPTION MARKS
OBJECTIVES
Structure
Paper 1 contributes 50% of the total marks for the Computer Science qualification.
Students must answer all questions.
The paper consists of multiple-choice, short open-response, open-response and Questions will
extended open-response answer questions. test the following
PRINCIPLES The total Assessment
OF COMPUTER Content summary number Objectives:
SCIENCE of marks
This paper will primarily assess knowledge and understanding of the basic principles available AO1 – 21.5%
PAPER CODE
of computer science, including some coverage of how these principles are applied is 80 AO2 – 21%
4CP0/01
when solving problems that relate to a particular situation. AO3 – 7.5%
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Assessment
This is a single-tier exam paper and all questions cover the full ranges of grades from 9–1.
The assessment duration is 2 hours.
ASSESSMENT
PAPER 2 DESCRIPTION MARKS
OBJECTIVES
Structure
Paper 2 contributes 50% of the total marks for the Computer Science qualification.
Students must answer all questions.
The paper consists of multiple-choice, short open-response, open-response,
extended open-response answer and task-based questions.
The task-based questions will be carried out using a computer system under supervision.
All other questions requiring a written response will be answered in the paper.
Questions will
Content summary test the following
APPLICATION OF The total Assessment
COMPUTATIONAL This paper will primarily assess the practical application of computational thinking, number Objectives:
THINKING whereby learners will create, use and adapt existing algorithms to solve problems in a of marks
PAPER CODE particular situation. This paper will also test students’ knowledge and understanding available AO1 – 6%
of the topics. is 80 AO2 – 21.5%
4CP0/02
AO3 – 22.5%
Assessment
This is a single-tier exam paper and all questions cover the full ranges of grades
from 9–1.
The assessment duration is 3 hours.
A choice of three programming languages will be available (Python, C# or Java).
A pseudocode reference document will be available for learners to reference during
the assessment.
F01 IGCSE Computer Science SB2 Global 10220 Contents.indd 9 20/05/20 7:26 PM
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
UNIT 1
PROBLEM SOLVING
Assessment Objective 1 In this unit you will learn about algorithms, which are the basis
of computer programming, and how they can be presented as
Demonstrate knowledge and flowcharts and pseudocode. You will learn about the basic
understanding of the key constructs of an algorithm such as sequence, selection and
principles of computer iteration and how these are used to solve problems using
science computational thinking. You will also look at completing and
correcting algorithms in addition to algorithms to sort and search
Assessment Objective 2 data. In the next unit you will learn how to code these algorithms
using pseudocode and high-level programming languages.
Apply knowledge and
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
understanding of key
concepts and principles of
computer science
Assessment Objective 3
Analyse problems in
computational terms:
• to make reasoned
judgements
• to design, program, test,
evaluate and refine
solutions
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 3 09/05/20 8:50 AM
4 UNIT 1 PROBLEM SOLVING 1 Understanding algorithms
1 UNDERSTANDING ALGORITHMS
GENERAL VOCABULARY
It is important to be able to construct algorithms and be able to read them
and follow their logic in solving particular problems.
construct a command to control the
order/flow in which instructions are
executed (e.g. sequences, selection,
repetition)
LEARNING OBJECTIVES
AN EXAMPLE OF AN ALGORITHM An interactive map is a useful way to find a route between two locations.
Figure 1.1 shows a route between two cities that was calculated by a mapping
program.
SUBJECT VOCABULARY
The route on this interactive map has been calculated using an algorithm.
unambiguous this means that the
instructions cannot be misunderstood. ◼ It is unambiguous in telling the driver exactly what to do, like ‘turn left’,
Simply saying ‘turn’ would be ambiguous
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 4 09/05/20 8:53 AM
UNIT 1 PROBLEM SOLVING 1 Understanding algorithms 5
SUCCESSFUL ALGORITHMS There are three points to consider when deciding whether an algorithm is
successful or not.
GENERAL VOCABULARY ◼ Accuracy – it must lead to the expected outcome (e.g. create a route from
Beijing to Shanghai).
outcome the final result of an action
◼ Consistency – it must produce the same result each time it is run.
consistency not changing; always the ◼ Efficiency – it must solve the problem in the shortest possible time, using
same as few computer resources as possible. In this example, the mapping
atlas a book of maps software is replacing a manual method. If it were no faster than looking in
an atlas, then it would not be an improvement on the older method. Later
in the unit there is a section on algorithms that are used to sort and search
data. Some of these algorithms are more efficient than others and will sort
the data far more quickly.
THE RELATIONSHIP BETWEEN Algorithms and programs are closely related, but they are not the same. An
ALGORITHMS AND PROGRAMS algorithm is a detailed design for a solution; a program is when that design is
implemented.
SUBJECT VOCABULARY
This unit is all about algorithms. We look at how algorithms are implemented
high-level programming language in high-level programming languages in Unit 2.
a programming language that is similar to
natural human language
DISPLAYING AN ALGORITHM
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
We carry out many everyday tasks using algorithms because we are following a
set of instructions to achieve an expected result, for example, making a cup of
coffee. If we have performed the task many times before, we usually carry out
the instructions without thinking. But if we are doing something unfamiliar, such
as putting together a flat-pack chest of drawers, then we follow the instructions
very carefully.
WRITTEN DESCRIPTIONS
A written description is the simplest way of expressing an algorithm. Here is
an algorithm describing the everyday task of making a cup of instant coffee:
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 5 09/05/20 8:54 AM
6 UNIT 1 PROBLEM SOLVING 1 Understanding algorithms
REASONING,
SKILLS PROBLEM SOLVING ACTIVITY 1
GETTING TO SCHOOL
Produce a written description of an algorithm for getting to school.
It should start with leaving home and end with arriving at school. For
example, the algorithm could start with ‘Walk to bus stop’.
Check your algorithm with other members of the group. Would your
algorithm work for others? Are there any general statements that are
common to all algorithms?
Indicates the start or Indicates a process Indicates a decision Indicates an input Shows the logical
end of an algorithm to be carried out to be made or output flow of the algorithm
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
The flowchart in Figure 1.3 is an alternative way of showing the algorithm for
making a cup of coffee as a written description.
Fill kettle
with water Turn on kettle
This instruction is
unambiguous – the water
must be boiling. Wait for kettle Place coffee
Stating ‘wait for the water to to boil in cup
heat’ would be ambiguous.
How hot should it be?
End Stir
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 6 09/05/20 8:54 AM
UNIT 1 PROBLEM SOLVING 1 Understanding algorithms 7
GENERAL VOCABULARY The algorithms you have looked at so far are designed for humans to follow.
Algorithms also form the basis of computer programs. Computers are
basis an important idea or fact that mindless machines that simply do exactly what they are told. They follow a set
something is based on of instructions, but they can carry out these instructions far more quickly than
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
SKILLS RESEARCH
ACTIVITY 4
INVESTIGATING PSEUDOCODE
Different organisations or examination boards have their own unique
versions of pseudocode. Investigate the Pearson Edexcel pseudocode
that you will need for your International GCSE course and which will be
used in this book.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 7 09/05/20 8:54 AM
8 UNIT 1 PROBLEM SOLVING 1 Understanding algorithms
EXAMPLE OF A SIMPLE ALGORITHM To introduce the Pearson Edexcel pseudocode, here is a simple written
algorithm that asks the user to input two numbers and then outputs the result
of adding them together.
WRITTEN DESCRIPTION
ALGORITHM FOR ADDING TWO NUMBERS
Enter first number.
Enter second number.
Calculate total by adding first and second numbers.
Output total.
FLOWCHART
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 8 09/05/20 8:54 AM
UNIT 1 PROBLEM SOLVING 1 Understanding algorithms 9
ARITHMETIC OPERATORS
8 + 5 = 13
+ Addition: add the values together.
myScore1 + myScore2
17 – 4 = 13
– Subtraction: subtract the second value from the first.
myScore1 – myScore2
6 * 9 = 54
* Multiplication: multiply the values together.
numberBought * price
Real division: divide the first value by the second value 13 / 4 = 3.25
/
and return the result including decimal places. totalMarks/numberTests
3 ^ 3 = 27
^ Exponentiation: this is for ‘to the power of’.
It is the same as writing 33
VARIABLES AND CONSTANTS Variables play an important role in algorithms and programming. The value
stored by a variable can change as a program is running. Variables are
KEY POINT extremely useful in programming because they make it possible for the same
program to process different sets of data.
When you chose a variable
name, it should be descriptive of A constant is the opposite of a variable. It is a ‘container’ that holds a value
the data it will hold, e.g. distance that always stays the same. Constants are useful for storing fixed information,
or length. Long variable names such as the value of pi, the number of litres in a gallon or the number of
are easier to misspell! months in a year.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 9 09/05/20 8:54 AM
10 UNIT 1 PROBLEM SOLVING 1 Understanding algorithms
PROBLEM SOLVING,
SKILLS ANALYSIS ACTIVITY 5
WRITING ALGORITHMS IN PSEUDOCODE
Here is a written description of an algorithm:
KEY POINT Enter the first number.
Whichever method you use for Enter the second number.
naming conventions, you must The third number is equal to the first number multiplied by the second
use it consistently and not keep number.
switching between the different Display the third number.
methods.
Express this algorithm in pseudocode.
username
partner, research the PageRank
algorithm that Google uses to
rate the importance of websites
and write a short report about
your findings. Does NO
username
exist?
YES
Input
password
Is NO
password
correct?
YES
End
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 10 09/05/20 8:54 AM
UNIT 1 PROBLEM SOLVING 1 Understanding algorithms 11
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 Produce a written description of an algorithm for borrowing a book
from the library.
SKILLS DECISION MAKING S2 What is the function of each of the seven arithmetic operators?
SKILLS CRITICAL THINKING S4 What is the difference between a variable and a constant?
Challenge
CRITICAL THINKING,
SKILLS PROBLEM SOLVING
C1 Produce a flowchart describing an algorithm for making a cheese
sandwich.
SKILLS PROBLEM SOLVING C2 Write an algorithm expressed in pseudocode that receives three
numbers from the keyboard, then calculates and displays the average.
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try the following activities again.
◼ For S1 re-read ‘The relationship between algorithms and programs’.
◼ For S2 study Table 1.1.
◼ For S3 and S4 look again at ‘Variables and constants’.
SUMMARY
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 11 09/05/20 8:54 AM
12 UNIT 1 PROBLEM SOLVING 2 Creating algorithms
2 CREATING ALGORITHMS
In this section you will learn how to create algorithms to solve particular
problems using the constructs of sequence, selection and iteration. You will
also practise displaying algorithms in flowcharts and pseudocode.
LEARNING OBJECTIVES
ALGORITHMS FOR COMPUTERS There was an ambiguous statement in the algorithm for making a cup of
coffee. After filling the kettle with water and adding coffee to the cup, the next
SUBJECT VOCABULARY
instruction was ‘Wait for water to boil’.
construct a smaller part from which A human can understand that this instruction means they have to keep
something is built. Letters and numbers checking the kettle over and over again until the water is boiling, but a
(i.e. a to z and 0 to 9) are the constructs we computer is unable to understand an instruction like this in the same way. It
use to build our language and convey would just wait. And wait. Forever.
meaning. Bricks and cement are the basic
constructs of a building Even worse, the algorithm didn’t state clearly how to tell the water was boiling.
Through experience, we humans assume the water is boiling when there is
selection a construct that allows a lots of steam, sound and bubbles; or, even better, when the kettle turns itself
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
choice to be made between different off. An algorithm for a computer would have to state that it must wait until the
alternatives water reached 100°C.
iteration a construct that means a
process is repeated. An action is repeated A version of this part of the algorithm, suitable for a computer, is shown
until a condition is met or a particular in Figure 1.6. This example introduces two new constructs from which
outcome is reached. It is often referred to algorithms are created. We have already met the construct sequence –
as a ‘loop’ step-by-step instructions in the correct order. To add to this, we now have
selection and iteration.
GENERAL VOCABULARY
ambiguous when a statement or Start
command does not have one obvious
meaning but can be interpreted in different
ways
Fill kettle Turn on kettle
condition something that must happen with water
before something else can happen
Is NO
YES temperature of
water =
100°C?
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 12 09/05/20 8:54 AM
UNIT 1 PROBLEM SOLVING 2 Creating algorithms 13
YES
REASONING,
SKILLS PROBLEM SOLVING ACTIVITY 7
commands?
over again, learning more each time
until they know them all.
PROBLEM SOLVING,
SKILLS ANALYSIS ACTIVITY 8
CALCULATING GRADES
A school uses this algorithm to calculate the grade that students achieve
in end-of-topic tests.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 13 09/05/20 8:54 AM
14 UNIT 1 PROBLEM SOLVING 2 Creating algorithms
END IF
END IF
END IF
END IF
What would be the output of this algorithm for these test scores: 91, 56
and 78?
ITERATION
When writing programs, it is often necessary to repeat the same set of statements
several times. Instead of making multiple copies of the statements, you can
use iteration to repeat them. The algorithm for making a cup of coffee includes
an instruction to keep waiting until the water in the kettle boils.
CHECKPOINT
Strengthen
CRITICAL THINKING,
SKILLS DECISION MAKING
S1 How are sequence, selection and iteration used in algorithms? Give
examples to justify your answer.
Challenge
SKILLS PROBLEM SOLVING C1 Develop an algorithm using a flowchart that asks the user to enter
their height (in metres) and weight (in kilograms) and displays
their body mass index (BMI). The formula for calculating BMI is
weight/height2.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
SKILLS PROBLEM SOLVING C2 Develop an algorithm expressed as a flowchart to control the heating
in a house. A thermostat monitors the temperature within the house.
During the week the temperature should be 20°C between 06.00
and 08.30 in the morning and between 17.30 and 22.00 at night.
At weekends it should be 22°C between 08.00 and 23.00. If the
temperature in the house falls below 10°C at any time the boiler is
switched on.
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try the following activities again.
SUMMARY
◼ The constructs sequence, selection and iteration are the basic
building blocks of algorithms.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 14 09/05/20 8:54 AM
UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms 15
We are on all sorts of lists (for example, school and college, clubs and groups,
voting registers) and all these must be searched to find relevant information.
Sorting information is also important to facilitate efficient searches.
LEARNING OBJECTIVES
◼ Understand how standard algorithms work (bubble sort, merge sort, linear
search, binary search)
◼ Understand how the choice of algorithm is influenced by the data
structures and data values that need to be manipulated
◼ Evaluate the fitness for purpose of algorithms in meeting specified
requirements efficiently, using logical reasoning and test data
Two of the most common tasks in computer programs are sorting data into a
particular order and searching for particular items of information.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
There might be millions of items of stored data and searching for information
wouldn’t be efficient if the data was not sorted. Imagine the confusion and
difficulty of having to find something in a dictionary that wasn’t in alphabetical
order. Or planning a trip with train timetables that weren’t sorted into time
order. Even small lists such as football league tables or the Top 20 music
charts are much more useful if they are sorted into order.
SORTING ALGORITHMS As sorting is such a widely used procedure, many algorithms have been created
to carry it out. As with all algorithms, some are more efficient than others.
SUBJECT VOCABULARY
BUBBLE SORT
When data is sorted, different items must be compared with each other and
ascending order this is arranging moved so that they are in either ascending order or descending order.
items from smallest to largest (e.g. 1, 2, 3)
descending order this is arranging The bubble sort algorithm starts at one end of the list and compares pairs of
items from largest to smallest (e.g. 3, 2, 1) data items. If they are in the wrong order, they are swapped. The comparison of
pairs continues to the end of the list, each complete traversal of the list being
traversal travel across or through called a ‘pass’. This process is repeated until there have been no swaps during a
something. pass. This indicates that the items must all be in the correct order.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 15 09/05/20 8:54 AM
16 UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms
WORKED EXAMPLE
Here is an example of a bubble sort in action.
Pass 1
Items 1 and 2 must be
4 2 6 1 3
swapped.
Items 1 and 2 are
2 4 6 1 3
swapped.
Items 2 and 3 are already
2 4 6 1 3
in ascending order.
Items 3 and 4 must be
2 4 6 1 3
swapped.
DID YOU KNOW? Items 3 and 4 have been
Do you know why it is called 2 4 1 6 3
swapped.
‘bubble sort’? If you look carefully, Items 4 and 5 must now
2 4 1 6 3
be swapped.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Pass 3
Items 1 and 2 must be
2 1 3 4 6
swapped.
Items 1 and 2 have been
1 2 3 4 6
swapped.
All items are now in the
1 2 3 4 6
correct order.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 16 09/05/20 8:55 AM
UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms 17
It would take a human three passes to carry out this bubble sort. A computer
would need four passes because it must continue until there have been no swaps;
it cannot just look at all of the numbers at once and see that they are all in order.
The bubble sort algorithm can be represented as a flowchart as shown in
Figure 1.9.
length = length
of list
position = 1
switch = 0
NO
position = position
+1
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
NO Is
position =
length?
YES
NO
Is
switch = 0?
YES
End
Using the variables declared, can you explain the logic behind the
algorithm? How does it function to sort a list?
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 17 09/05/20 8:55 AM
18 UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms
8 4 2 6 1 3 5 7
The list is split into half with recursion to produce a left list and a right list
each time.
8 4 2 6 1 3 5 7
8 4 2 6 1 3 5 7
This continues until there is only one item in each list. Therefore, each list
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
8 4 2 6 1 3 5 7
The left and right lists are now merged through recursion with the items in
the correct order.
4 8 2 6 1 3 5 7
The leftmost items in each list are the lowest items of those lists and the
algorithm compares them – in this case 4 with 2. The 2 is inserted in the
new list and the 4 is then compared with the second number of the right
list – 6. The 4 is inserted and the 6 is compared with the second number
of the left list.
2 4 6 8 1 3 5 7
KEY POINT
The algorithm now merges these two lists in the same way to produce the
In the exam, you will be expected final sorted list. 1 is compared with 2 and then 2 with 3, 3 with 4, etc.
to show the intermediate stages
when the algorithms are applied
1 2 3 4 5 6 7 8
to data.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 18 09/05/20 8:55 AM
UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms 19
SUBJECT VOCABULARY The bubble and merge sort algorithms demonstrate two alternative
approaches to algorithm design.
brute force an algorithm design that
does not include any techniques to improve The bubble sort algorithm is said to be using brute force because it starts at
performance, but instead relies on the beginning and completes the same task over and over again until it has
computing power to try all possibilities found a solution.
until the solution to a problem is found
The merge sort uses the divide and conquer method because it repeatedly
divide and conquer an algorithm
breaks down the problem into smaller sub-problems, solves those and then
design that works by dividing a problem
combines the solutions.
into smaller and smaller sub-problems,
until they are easy to solve. The solutions The graph shows that a bubble sort is far slower at sorting lists of more
to these are then combined to give a than 1000 items, but for smaller lists the time difference is too small to be of
solution to the complete problem importance.
SEARCHING ALGORITHMS To find a specific item in a list involves carrying out a search. Like sorting,
some methods of searching are more efficient than others.
LINEAR SEARCH
A linear search is a simple algorithm and not very sophisticated. It simply starts
GENERAL VOCABULARY at the beginning of the list and goes through it, item by item, until it finds the
sequential following in order, one item it is looking for or reaches the end of the list without finding it.
after the other
A linear search is sequential because it moves through the list item by item.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 19 09/05/20 8:55 AM
20 UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms
LINEAR SEARCH
1 Start at the first item in the list.
2 Compare the item with the search item.
3 If they are the same, then stop.
4 If they are not, then move to the next item.
5 Repeat 2 to 4 until the end of the list is reached.
BINARY SEARCH
Like a merge sort, a binary search uses a ‘divide and conquer’ method.
SUBJECT VOCABULARY In a binary search the middle or median item in a list is repeatedly selected
to reduce the size of the list to be searched – another example of recursion.
median the middle number when the If the selected item is too high or too low, then the items below or above that
numbers are put in ascending or selected item can be searched.
descending order (e.g. if there are
13 numbers, then the 7th number is the To use this method, the list must be sorted into ascending or descending
median). If there are an even number of order. It will not work on an unsorted list.
items in a list, the median is the mean of
the middle two numbers (e.g. if there are
10 numbers, add the 5th and 6th numbers BINARY SEARCH (ITEMS IN ASCENDING ORDER)
together and divide the result by 2). In a
binary search, the higher of the two 1 Select the median item of the list.
numbers would be chosen 2 If the median item is equal to the search item, then stop.
3 If the median is too high, then repeat 1 and 2 with the sub-list to the left.
4 If the median is too low, then repeat 1 and 2 with the sub-list to the right.
5 Repeat steps 3 and 4 until the item has been found or all of the items
DID YOU KNOW? have been checked.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
This is again too high and so the sub-list to the left must be searched.
In this example, it took three attempts to find the search item. A linear
search would have accomplished this with only two attempts.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 20 09/05/20 8:55 AM
UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms 21
Searching algorithms can be compared by looking at the ‘worst case’ and the
‘best case’ for each one.
WORKED EXAMPLE
If you wanted to find a particular item in a list of 1000 items, these are the
best- and worst-case scenarios for the linear search and binary search
algorithms.
Linear search
A linear search starts at the first item and then works through sequentially.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Binary search
The best case would be if the item is in the median position in the list. The
search would require only one comparison.
For the worst case it would have to choose the following medians until it
finally hit the target.
(This assumes that the target is always smaller than the median.)
Attempt Median
1 500
2 250
3 125
4 63
5 32
6 16
7 8
8 4
9 2
10 1
Therefore, the worst case for the binary search is ten comparisons.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 21 09/05/20 8:55 AM
22 UNIT 1 PROBLEM SOLVING 3 Sorting and searching algorithms
The binary search is therefore far more efficient than the linear search.
So, should a binary search be used every time? That depends on the
circumstances. The binary search has one great disadvantage. The list must
be already sorted into ascending or descending order. Therefore, a sorting
algorithm must be applied before the search.
If the list is to be searched just once then a linear search would be better, but
if there is a large list that will be searched many times then sorting the list and
using a binary search would be better. Once the list has been sorted, new
items can be inserted into the correct places.
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 What are the differences between the ‘bubble sort’ and ‘merge sort’
algorithms?
SKILLS DECISION MAKING S2 How does a binary search algorithm find the search item?
Challenge
SKILLS CRITICAL THINKING C1 When might a linear search be preferable to a binary search, even if
the binary search algorithm is more efficient?
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try the following activities again.
SUMMARY
◼ There are many algorithms for sorting and searching data.
◼ The choice of algorithm depends on the data that is to be processed.
◼ If only a small amount of data needs to be processed, then a simpler,
but less efficient search algorithm may be the best choice. The time
difference of the search or sort time will be negligible.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 22 09/05/20 8:55 AM
UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction 23
LEARNING OBJECTIVES
PROBLEM SOLVING The tasks of a computer scientist include defining and analysing problems;
creating structured solutions – algorithms; and coding the solutions into a
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
form that can be implemented by a computer. These tasks are part of what is
SUBJECT VOCABULARY
known as computational thinking.
computational thinking the thought
processes involved in formulating problems One of the skills required for computational thinking is algorithm design (which
and their solutions so that the solutions are we’ve covered in detail in this unit). If there is a fault in the algorithm design,
represented in a form that can be then the program will not work, however good a coder you are. Two other skills
effectively carried out by a computer are decomposition and abstraction.
decomposition breaking a problem
down into smaller, more manageable parts,
which are then easier to solve
abstraction the process of removing or
hiding unnecessary detail so that only the
important points remain
DECOMPOSITION Decomposition is usually the first step in the problem-solving process. Once
a problem has been broken down and the sub-problems have been identified,
algorithms can be developed to solve each of them.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 23 09/05/20 8:55 AM
24 UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction
WORKED EXAMPLE
A student has been set the task of creating a computer version of the
game ‘noughts and crosses’ (also known as ‘tic-tac-toe’) where a user
plays against the computer.
▶ Figure 1.12 Sub-problems to be solved to create a noughts and crosses computer program
ABSTRACTION We use abstraction all the time in our daily lives. We abstract the essential
features of something so that we can understand what people are trying to
communicate.
Somebody might say, ‘I was walking down the street when I saw a cat’. You
GENERAL VOCABULARY
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
What you imagine is very unlikely to match the actual street and cat that the
person experienced. But, because of our ability to abstract, the person did not
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 24 09/05/20 8:56 AM
UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction 25
have to go into unnecessary detail about exactly where they were and what
they saw. They wouldn’t get very far with the story if they did.
When we create algorithms, we abstract the basic details of the problem and
represent them in a way that a computer is able to process.
WORKED EXAMPLE
Yasmin is designing a computer version of a game in which users have to
throw a die to find out their number of moves.
In the computer game, the users can’t have an actual die, so she will have
to design a ‘pretend’ or virtual die that behaves in exactly the same way
as a real-life die.
Yasmin will have to use her powers of abstraction to work out the essential
features of a die and then represent them in computer code.
GENERAL VOCABULARY To represent the die, she will have to create a routine that will select a
random number from 1 to 6 because that’s what a die does.
model to make a simple version of
something to show how it works Yasmin has used abstraction to model a real-life event.
LEVELS OF ABSTRACTION
There are different levels or types of abstraction. The higher the level of
abstraction, the less detail is required. We use abstraction all the time in
accomplishing everyday tasks.
When programmers write the ‘print’ command they do not have to bother
about all of the details of how this will be accomplished. They are removed
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
A driver turning the ignition key to start a car does not have to understand
how the engine works or how the spark to ignite the petrol is generated. It just
happens and they can simply drive the car. That is abstraction.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 25 09/05/20 8:57 AM
26 UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction
The solution is still at a high level of abstraction and more details will need to
be added.
For example, the programmer will need to decide how the game will record
which player has selected each square; how the computer will decide which
square to select; how the game will decide if the computer or the user has
won.
The programmer will have to go into more and more detail or move to lower
levels of abstraction.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Eventually, the programmer will be able to design an algorithm for the game
and code it using a high-level programming language such as Python or Java.
Even before they start to implement the game, they will need to plan how they
will test the finished program to make sure that it works correctly, what test
data they will use and what outcomes it should produce.
CODING AN ALGORITHM High-level programming languages make it easier for a programmer to write
code. Unfortunately, the processor that has to execute the program cannot
understand the language it is written in. It therefore needs a translator to
translate the code into the only language it does understand – a stream of 1s
and 0s.
The processing can be split into parts. For example, in the example of the
noughts and crosses game there could be separate algorithms for:
◼ deciding where the computer should make its next selection – it could be
called ‘computer entry’
◼ checking if the computer or the player has won – it could be called ‘check
if won’
◼ checking if there are any empty squares left – it could be called ‘check draw’.
These separate algorithms could be used when they are needed. It is efficient
because it means that the same code doesn’t have to be rewritten whenever it
is needed.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 26 09/05/20 8:57 AM
UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction 27
REASONING,
SKILLS PROBLEM SOLVING ACTIVITY 12
GENERAL VOCABULARY
CREATING A QUIZ GAME
decompose to divide something into In a game, each player spins a wheel that is divided into four colours:
smaller parts red, blue, green and yellow. Each player has to answer a question
on a particular topic depending on the colour next to a pointer
when the wheel stops. Red is for science, blue for history, green for
general knowledge and yellow for geography. A player scores two
points if they answer correctly on the first attempt and one point for
being correct on the second attempt. The first player to reach 30 points
is the winner.
language you are studying. See One of the requirements that will have to be modelled is the spinning of
if you can end up with a working the wheel. Using a written description and pseudocode shows how this
game. could be done.
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 What is meant by ‘decomposition’? What are the benefits it provides
for programmers?
Challenge
SKILLS CRITICAL THINKING C1 Can you think of some examples when ‘decomposition’ and
‘abstraction’ are used when solving a problem?
SKILLS PROBLEM SOLVING C2 In your own words, can you explain what is meant by ‘computational
thinking’?
SKILLS DECISION MAKING C3 Explain how we use abstraction in our daily lives when we are
communicating with others.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 27 09/05/20 8:57 AM
28 UNIT 1 PROBLEM SOLVING 4 Decomposition and abstraction
How confident do you feel about your answers to these questions? If you’re
DID YOU KNOW? not sure you answered them well, re-read the sections about ‘Decomposition’
Computer models or ‘simulations’ and ‘Abstraction’.
of real life are widely used. It is
far cheaper and safer to train SUMMARY
pilots on flight simulators than on
◼ Computational thinking is an approach to solving problems, such
real aircraft. They are also used as traffic flow in a city, or how many products a business needs to
in weather forecasting, designing make and sell to produce a profit. It includes techniques such as
and testing new cars and bridges decomposition and abstraction.
and even teaching people to drive. ◼ Problems are easier to solve if they are decomposed into smaller
sub-problems.
Computer models are used by all ◼ Abstraction is used to remove unnecessary detail to make a problem
governments around the world to easier to understand and solve. For example, when modelling traffic
experiment with the short and long- flow in a city, unnecessary details could include the colours of the
term effects of changing variables vehicles or the ages of the drivers.
◼ When designing a solution to a problem the inputs, outputs and
such as tax rates on the economy. processing requirements should be identified at the outset.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 28 09/05/20 8:57 AM
UNIT 1 PROBLEM SOLVING UNIT QUESTIONS 29
UNIT QUESTIONS
charge = 0
total = 0
number = 0
Input
customer
charge = £10
number = number
+1
Input
age
Is age YES
charge = £5
A < 13? number = number – 1
NO
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Is age YES
> = 60? charge = £9
NO B
Is
there another YES
customer in the
group?
NO
Is YES
number total = total – £10
> 4?
NO
Output
total
End
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 29 09/05/20 8:57 AM
30 UNIT 1 PROBLEM SOLVING UNIT QUESTIONS
SKILLS PROBLEM SOLVING AO2 1 Explain how the algorithm calculates the total amount that should
be paid. (4)
SKILLS PROBLEM SOLVING AO2 2 Give two variables that are used in the algorithm. (2)
SKILLS PROBLEM SOLVING AO2 3 In the flowchart, two of the constructs are labelled A and B. State
the type of each construct. (2)
SKILLS PROBLEM SOLVING AO2 4 The Lim family is visiting the park. The family consists of two children,
one aged 8 and one aged 10, their two parents and their grandfather,
who is aged 65. Use the algorithm to calculate how much the family
should have to pay for entry. (4)
HINT
Spend some time studying the algorithm to ensure that you fully understand it.
In 1 you are asked to ‘explain’ how the algorithm works. A longer answer is
required, which includes all of the stages of the algorithm. Use the correct
terms to explain the constructs.
In 4 calculate the charge for each person using the rules of the algorithm.
Then calculate the overall charge and check to see if the family qualifies for a
group discount.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
SKILLS PROBLEM SOLVING AO2 5 A teacher has stored learner surnames as shown below.
SKILLS PROBLEM SOLVING AO2 6 The teacher has a sorted list of names from another class as shown below.
Azikiwe Bloom Byrne Davidson Gateri Hinton Jackson Linton Smith Wall
HINT
These questions are testing knowledge of the sort and search algorithms.
In question 5, the answer should be set out to show how the data is
SUBJECT VOCABULARY progressively sorted using the bubble sort and the result of each pass should
be shown.
recursive method a recursive method
calls a function over and over until a Question 6 is to check that you know that this is a recursive method where
required goal is met the median is repeatedly selected.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 30 09/05/20 8:57 AM
UNIT 1 PROBLEM SOLVING UNIT QUESTIONS 31
SKILLS PROBLEM SOLVING AO3 7 Create an algorithm to calculate the cost of sending a parcel.
If the weight of the parcel is 2 kg or under then the standard charge is $3.
There is then a charge of $2 for each extra kilogram up to 10 kg. After
10 kg the charge per extra kilogram is $3.
a Display your algorithm as a flowchart. (5)
b Construct your algorithm as pseudocode. (5)
SKILLS PROBLEM SOLVING AO3 8 A learner hands in three homework assignments, which were each
given a mark out of 10. All of the marks were different. The following
is part of an algorithm to find the highest mark but some of the
decision symbols are empty.
Complete the decision symbols and add ‘YES’ and ‘NO’ labels
where required. (6)
Start
Input mark1,
mark2, mark1
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M01 IGCSE Computer Science SB2 Global 10220 UNIT1.indd 31 09/05/20 8:57 AM
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
UNIT 2
PROGRAMMING
Assessment Objective 1 In this unit you will learn about translating algorithms into
programs written in a high-level language using constructs, such
Demonstrate knowledge and as variables and arrays. You will also look at how programs can
understanding of the key be structured using subprograms and how data input can be
principles of computer validated to ensure that it is reasonable. Humans are not perfect.
science Most programs have one or two errors and you will look at how
programs can be tested, and errors corrected.
Assessment Objective 2
Apply knowledge and
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
understanding of key
concepts and principles of
computer science
Assessment Objective 3
Analyse problems in
computational terms:
• to make reasoned
judgements
• to design, program, test,
evaluate and refine
solutions
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 33 18/05/20 11:42 AM
34 UNIT 2 PROGRAMMING 5 Develop code
5 DEVELOP CODE
Once an algorithm has been developed to solve a particular problem, it has
PROGRAMMING LANGUAGES to be coded into the programming language that the developer is using. This
usually means that the written descriptions, flowcharts and pseudocode have
Throughout the book, we have
to be converted into actual programming code.
coloured the different
programming languages in As you will be expected to understand, use and edit Pearson Edexcel
order for you to easily find the pseudocode in the examination, examples will be given in the pseudocode
one you are looking for. as well as in Python, Java and C#.
The colours are:
LEARNING OBJECTIVES
Pearson Edexcel pseudocode
Python ◼ Explain the difference between algorithms and programs
Java ◼ Code an algorithm in pseudocode and a high-level programming language
ALGORITHMS AND PROGRAMS As you learnt in Unit 1, an algorithm is a precise method of solving a problem.
It consists of a sequence of unambiguous, step-by-step instructions. A
program is an algorithm that has been converted into program code so that it
SUBJECT VOCABULARY can be executed by a computer. A well-written algorithm should be free of
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 34 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 35
DATA TYPES As you learnt in Unit 1, algorithms use variables (named memory locations)
to store values. Variables have a variety of uses. For example, controlling
GENERAL VOCABULARY the number of times a loop is executed, determining which branch of an IF
determine to discover facts about statement is taken, keeping running totals and holding user input.
something
When algorithms are converted into programs, the computer needs to be told
what type of data is stored in each variable. Every programming language has
a number of built-in data types.
real or float Used to store numbers with a fractional part (decimal place). 25.5 weight = 25.5
Real numbers are sometimes referred to as floats (short for price = 12.55
floating point)
Boolean Only has two possible values: True or False False correct = False
lightOn = True
character* A character can be a single letter, a symbol, a number or ‘m’ gender = ‘m’
even a space. It is one of the four basic data types char = ‘:’
string A set of characters which can include spaces and numbers ‘the computer’ name = ‘Catherine’
and are treated as text rather than numbers type = ‘liquid’
*Python does not have a character data type.
▲ Table 2.1 Common data types
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
GENERAL VOCABULARY When writing pseudocode, you don’t have to specify the data types of
variables. However, data types become much more important once you start
assign to give somebody a particular task programming in a high-level language. This is because the data type of a
variable determines the operations that can be performed on it.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 35 18/05/20 11:42 AM
36 UNIT 2 PROGRAMMING 5 Develop code
SUBJECT VOCABULARY You can put an initial value into a variable by:
initialise to set variables to their starting ◼◼ initialising it when the program is run (e.g. SET total TO 0, in
values at the beginning of a program or pseudocode)
subprogram ◼◼ reading a value from a keyboard or other device (e.g. RECEIVE
initialisation the process of assigning admissionCharge FROM (INTEGER) KEYBOARD).
an initial value to a variable
assignment statement the SET…TO Once a variable has been initialised an assignment statement is used to
command is used to initialise variables in change its value (e.g. SET total TO total + admissionCharge).
pseudocode, for example:
In Python this would be:
SET anotherGo TO 0
SET correct TO False total = 0
total = total + admissionCharge
In C#, variables must be declared before use. When you declare a variable,
you need to state the data type that the variable will store, for example:
to the total
total = total + admissionsCharge;
GENERAL VOCABULARY If a variable, such as a loop counter, is intended to hold a running total, then it
should always be initialised to a starting value. Some programming languages
intended designed for a certain purpose won’t execute if the programmer fails to do this; others will do so but may well
produce some unexpected results.
CRITICAL THINKING,
SKILLS DECISION MAKING ACTIVITY 1
DATA TYPES
1 Investigate what data types are available in the high-level language
you are studying. Produce a table similar to Table 2.1 to give a
summary of your findings.
2 What do you think is an appropriate data type for each of these items?
a the test score of an individual learner
b the average score for a group of learners
c whether or not the pass mark for the test has been achieved.
3 Look back over the algorithms you wrote in Unit 1 and find instances
of variable initialisation.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 36 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 37
In Python, type coercion is done automatically, for example, the output from the
following program is 3.25.
x = 1
y = 2.25
z = x + y
print(z)
int x = 1;
double y = 2.25;
double z = x + y;
System.out.print(z);
CRITICAL THINKING,
SKILLS PROBLEM SOLVING, ACTIVITY 2
DECISION MAKING
MONITORING VISITOR NUMBERS
A theme park uses a program to monitor the number of people entering
and exiting the park. The maximum number of visitors at any one time must
not exceed 10 000. When the number of people in the park reaches the
maximum, a ‘Park Full’ message is displayed at the entrance gate. Children
can visit the park free of charge. Adults must pay AED 125 admission. The
program records the amount of money collected at the gate.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 37 18/05/20 11:42 AM
38 UNIT 2 PROGRAMMING 5 Develop code
COMMAND SEQUENCE, In Unit 1 you learnt that the three key building blocks of algorithms are
SELECTION AND ITERATION command sequence, selection and iteration. In this unit, you will have the
opportunity to implement these constructs in the high-level programming
language you are studying.
CRITICAL THINKING,
SKILLS PROBLEM SOLVING, ACTIVITY 3
CREATIVITY
UNDERSTANDING ALGORITHMS
Read the following algorithm written in pseudocode and then answer the
questions below.
SELECTION
The selection construct is used to create a branch in a program. The computer
selects which branch to follow based on the outcome of a condition, using an
IF…THEN…ELSE statement. For example, in pseudocode:
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 38 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 39
WORKED EXAMPLE
A learner handed in three homework assignments, which were each given a mark out of 10. All the marks were
different. Write an algorithm that would print out the highest mark.
Figure 2.1 shows the algorithm expressed as a flowchart.
Start
Input mark1,
mark2,
mark3
Is NO Is NO
mark1 > mark2 >
mark2? mark3?
YES YES
Output Output
NO Is mark2 mark3
Output
mark3 mark1 >
mark3?
End
▲ Figure 2.1 Flowchart of an algorithm to print out the highest homework mark
HINT
When you are creating nested IF statements, you have to ensure that each one is completed with an END IF
statement at the correct indentation level. Some programming languages do not need an END IF statement and
just use the indentation levels to indicate when statements are grouped.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 39 18/05/20 11:42 AM
40 UNIT 2 PROGRAMMING 5 Develop code
In Python, Java and C# this does not have to be done as they have an ‘else if’ statement.
In Python the ‘else if’ statement is elif and the algorithm above could be:
mark1 = input(‘Please enter the first mark’)
mark2 = input(‘Please enter the second mark’)
mark3 = input(‘Please enter the third mark’)
scanner.close();
And in C#:
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 40 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 41
ACTIVITY 4
Look at the following algorithm and answer the questions.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 41 18/05/20 11:42 AM
42 UNIT 2 PROGRAMMING 5 Develop code
LOGICAL OPERATORS
AND
If two conditions are joined by the AND operator, then they must both be true
for the whole statement to be true.
OR
If two conditions are joined by the OR operator, then either one must be true for
the whole statement to be true.
NOT
The NOT operator reverses the logic of the AND and OR statements. The
statement IF A = 3 AND B = 6 will be true only if the conditions are met,
i.e. A and B are both equal to the values stated.
ACTIVITY 5
A driving school uses this rule to estimate how many lessons a learner will
require.
LOOPS
A loop is another name for an iteration. Loops are used to make a computer
repeat a set of instructions more than once. There are two types of loop:
definite and indefinite.
A definite loop is used when you know in advance how often the instructions in
the body of the loop are to be repeated. For example, if you want the computer to
display a character on the screen for a fixed amount of time and then remove it.
An indefinite loop is used when the number of times a loop will need to be
repeated is not known in advance. For example, if you want to give a user the
option of playing a game as often as they want. Indefinite loops are repeated
until a specified condition is reached.
Every programming language has a number of built-in loop constructs. You will
need to explore the ones provided in the language you are studying.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 42 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 43
DEFINITE ITERATION
This is used when the number of iterations, or turns of the loop, is known in
advance.
In the Pearson Edexcel pseudocode there are two ways of doing this using
REPEAT…END REPEAT and FOR…END FOR.
REPEAT 50 TIMES
SEND ‘*’ TO DISPLAY
END REPEAT
FOR loops can also include a step so that the counting is not consecutive. A
step is included in the following pseudocode example.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 43 18/05/20 11:42 AM
44 UNIT 2 PROGRAMMING 5 Develop code
(continued)
amount to 50
}
increase by 75
Printing items String[] aList = {“red”, “blue”, “green”, “yellow”, “purple”, red
from a list “orange”}; blue
for(String colour: aList) { green
yellow
System.out.println(colour);
purple
} orange
Leaving out String[] aList = {“red”, “blue”, “green”, “yellow”, “purple”, red
items from the “orange”}; blue
list for(String colour: aList) { green
purple
if(colour == “yellow”) {
orange
continue;
}
System.out.println(colour);
}
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 44 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 45
The number of iterations does not have to be given as the length of the array is used.
Leaving out items string[] colours = {“red”, “blue”, “green”, “yellow”, “purple”, red
from the array* “orange”}; blue
green
purple
foreach (string i in colours)
orange
{
if (i == “yellow”)
{
continue;
}
else
{
Console.WriteLine(i);
}
*See pages 62–68 for more information on arrays.
▲ Table 2.4 C#
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 45 18/05/20 11:42 AM
46 UNIT 2 PROGRAMMING 5 Develop code
NESTED LOOPS
A nested loop is made of a loop within a loop. When one loop is nested within
another, each iteration of the outer loop causes the inner loop to be executed
until completion.
ACTIVITY 7
1 Python
Look at the following program and then answer the questions below.
a
What is the purpose of this program?
hy is int used in the line nextMark = int(input(‘Please
b
W
enter a mark’))?
2 Java
Look at the following program and then answer the questions below.
import java.util.*;
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for(int student = 1; student < 21; student++) {
int sum = 0;
for(int mark = 1; mark < 6; mark++) {
System.out.print(“Please enter a mark: ”);
int nextMark = scanner.nextInt();
sum = sum + nextMark;
}
double averageMark = sum / 5;
System.out.println(averageMark);
}
scanner.close();
}
}
a
What is the purpose of this program?
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 46 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 47
3 C#
int nextMark, sum, averageMark;
string markString;
sum = 0;
for (int mark = 1; mark <= 5; mark++)
{
Console.WriteLine(“Please enter a mark”);
markString = Console.ReadLine();
nextMark = int.Parse(markString);
sum = sum + nextMark;
}
averageMark = sum / 5;
Console.WriteLine(averageMark);
a
What is the purpose of the program?
hy is int.Parse used in the line nextMark = int.
b
W
Parse(markString);?
INDEFINITE ITERATION
An indefinite loop is used when the number of times a loop will need to be
repeated is not known in advance. For example, if you want to give a user the
option of playing a game as often as they want. Indefinite loops are repeated
until a specified condition is reached.
Python
For indefinite iteration, Python uses the ‘while’ loop – something is done while
a condition is met.
The following program asks a user to enter a number while the number is less
than 20.
number = 1
while number <= 20:
number = int(input(‘Please enter a number’))
print(‘You entered a number greater than 20’)
As soon as the number is greater than 20, the program breaks out of the loop
and prints a message for the user.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 47 18/05/20 11:42 AM
48 UNIT 2 PROGRAMMING 5 Develop code
Java
For indefinite iteration, Java uses a ‘while’ loop – instructions are repeated
while a condition is met.
The following program asks a user to enter a number while the number is less
than 20.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = 1;
while(number <= 20) {
System.out.print(“Please enter a number: ”)
number = scanner.nextInt();
}
System.out.println(“You entered a number greater than 20”)
scanner.close();
}
}
C#
string numberString;
int number = 1;
while (number <=20)
{
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
As soon as the number is greater than 20, the program breaks out of the loop
and prints a message for the user.
ACTIVITY 9
What do these two algorithms do? Implement them in the high-level
programming language you are studying.
a Algorithm A
b
Algorithm B
SET counter TO 10
WHILE counter > 0 DO
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 48 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 5 Develop code 49
RANDOM NUMBERS
Random numbers are commonly used in games of chance such as flipping a
coin or rolling a dice. The aim is to make an event random.
Python
Python has a random module. The following code will generate a random
number between 1 and 10.
import random
x = random.randint(1, 11)
print(x)
The ‘import’ command is necessary so that the ‘random’ module can be used.
Java
Java can generate a random integer using System.util.Random. The
following code will generate a random number between 1 and 10.
import java.util.*;
class Main {
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
class Main {
public static void main(String[] args) {
int x = (int)(Math.random() * 10) + 1;
System.out.println(x);
}
}
C#
C# can generate random numbers using the Random Class. The following
code will generate a random number between 1 and 10 and display on
screen.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 49 18/05/20 11:42 AM
50 UNIT 2 PROGRAMMING 5 Develop code
ACTIVITY 10
Create a guessing-game program with the following specification.
◼◼ The computer generates a random number between 1 and 20.
◼◼ The user is asked to enter a number until they enter this random
number.
◼◼ If their guess is too low or too high they are told.
◼◼ They are told when their guess is correct.
◼◼ They are asked if they want to play another game until their answer
is ‘NO’.
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 Why are variables needed?
SKILLS CRITICAL THINKING S3 How are selection and iteration implemented in the high-level language
you are studying?
Challenge
SKILLS PROBLEM SOLVING C1 Outline the following structural components of a program: variable
and type declarations, command sequences, selection and iteration
constructs.
How confident do you feel about your answers to these questions? If you’re
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
not sure you answered them well, try redoing the activities in this section.
SUMMARY
◼◼ A program is an algorithm that has been converted into program code.
◼◼ Pseudocode is far more forgiving than program code.
◼◼ The four basic data types are integer, float/real, Boolean and character.
◼◼ The data type of a variable determines the operations that can be
performed on it.
◼◼ Data types don’t have to be declared in pseudocode but it’s a good
idea to do so.
◼◼ Variable and type declarations, command sequences, selection and
iteration are four of the structural components of a program.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 50 18/05/20 11:42 AM
UNIT 2 PROGRAMMING 6 Making programs easy to read 51
LEARNING OBJECTIVES
CODE READABILITY You should always try to ensure that any code you write is easy to read and
understand. We refer to this as ‘readability’. This benefits you and anyone else
who needs to understand how your programs work.
It is surprising how quickly you forget. Try revisiting the programs you have
already written in this unit and make sure it is still clear to you what they do
and how they work. Imagine how much more difficult it would be to make
sense of a complex program with lots of variables, subprograms, nested loops
and multiple selection statements.
GENERAL VOCABULARY
practice the way that you do something The programmer who produced the program in Figure 2.2 did not follow good
practice. There are a number of ways that the readability of this code could
be improved.
SUBJECT VOCABULARY
◼◼ Use descriptive names for variables (e.g. userChoice instead of Num1).
block of code a grouping of two or ◼◼ Add blank lines between different blocks of code to make them stand out.
more code statements ◼◼ Add comments that explain what each part of the code does.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 51 18/05/20 11:42 AM
52 UNIT 2 PROGRAMMING 6 Making programs easy to read
HINT
Here’s how to write comments in
Python, Java and C#:
▲ Programmers often work in teams; it is vital that any coding they share is clear and error free
Table 2.5 lists the techniques you should use to make your programs easy to
read and understand.
TECHNIQUE DESCRIPTION
DID YOU KNOW? Comments Comments should be used to explain what each part
Microsoft Windows® uses roughly of the program does.
50 million lines of code – code Descriptive Using descriptive identifiers for variables, constants
readability obviously becomes names and subprograms helps to make their purpose clear.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
more and more important as Indentation Indentation makes it easier to see where each block of
programs get larger. code starts and finishes. Getting the indentation wrong
in Python will result in the program not running or not
producing the expected outcomes.
White space Adding blank lines between different blocks of code
makes them stand out.
CRITICAL THINKING,
SKILLS PROBLEM SOLVING, ACTIVITY 11
CREATIVITY
REWRITING AND IMPLEMENTING ALGORITHMS
1 Program the following algorithm in a high-level language and make it
readable by adding comments and indentation.
SET x TO 10
WHILE x >= 0 DO
IF x > 0
SEND x TO DISPLAY
ELSE
SEND ‘Blast Off’ TO DISPLAY
END IF
SET x TO x -1
END WHILE
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 52 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 6 Making programs easy to read 53
SKILLS CRITICAL THINKING S2 Outline the four techniques that a programmer should use to make
code easy to read.
Challenge
SKILLS PROBLEM SOLVING C1 Revisit the programs you have already written. Do you still understand
what they do and how they work? If not, try to improve their readability.
How confident do you feel about your answers to these questions? If you’re
KEY POINT not sure you answered them well, look again at Table 2.5.
Readability of code is important.
You should always make your
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 53 18/05/20 11:43 AM
54 UNIT 2 PROGRAMMING 7 Strings
7 STRINGS
A string is a data type that is used to represent a sequence of characters,
such as numbers, text, spaces and punctuation. Strings must be enclosed in
quotation marks to distinguish them from variable names. A string could be a
user name, a whole sentence or paragraph of data.
LEARNING OBJECTIVES
◼ Describe what a string is and explain what strings are used for
◼ Use iteration to traverse a string
◼ Concatenate and split strings
SUBJECT VOCABULARY A character is one of the four basic data types. It can be a single letter, a
symbol, a number or even a space. A sequence of characters is called a
string a sequence of characters. They can string. Although strings can contain different sorts of characters, including
be letters, numbers, symbols, punctuation numbers, they are all treated as if they were text.
marks or spaces
When a computer executes a program, it needs a way of telling the difference
between a string and an instruction. In most programming languages, this
is achieved by enclosing strings in quotation marks (e.g. ‘johnsmith@mail.
com’, ‘10/04/15’ or ‘123’). Both single ‘ ’ and double “ ” quotation marks are
acceptable, as long as they are used in the same way each time. In the example,
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
“It’s her book”, the apostrophe is treated as part of the string because double
quotes have been used to enclose the string.
Strings are very useful when communicating with users. For example, asking
them to enter some information into a program or displaying the output of a
program in a format that humans can read and understand.
STRING INDEXING Each character in a string has an index number, with the first character at
position 0. You can use the index to reference individual characters in a
GENERAL VOCABULARY string.
reference to refer to something Therefore the index position of the letter ‘m’ is 2, even though it is the third
character, as shown in Table 2.6.
INDEX 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
String C o m p u t e r S c i e n c e
KEY POINT
Computers start counting at 0. Therefore, although the length of the
string ‘Computer Science’ is 16, the indexes of the characters range
from 0 to 15.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 54 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 7 Strings 55
LENGTH The Pearson Edexcel pseudocode has a built-in LENGTH function, which you
can use to find the number of characters in a string. Therefore:
SUBJECT VOCABULARY
SET numChars TO LENGTH(myText)
function a subprogram that performs
a specific task and returns a value to the SEND numbChars TO DISPLAY
main program. High-level programming
would print ‘16’. Table 2.7 gives the method for Python, Java and C#.
languages have a number of useful built-in
functions. You can also create your own or
use functions available in online libraries
PROBLEM SOLVING,
SKILLS CREATIVITY, ACTIVITY 12
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
DECISION MAKING
CHECKING PASSWORD LENGTH
Create and write a program to check the length of a password. If the
password entered is less than six characters, the program should output
‘The password you have entered is not long enough’; otherwise it should
output ‘Length of password OK’.
STRING TRAVERSAL You can use a FOR loop to cycle through each of the characters in a string.
This is known as string traversal.
SUBJECT VOCABULARY The following algorithm prints out the word ‘monkey’ letter by letter, displaying
each letter on a separate line.
string traversal using a loop to cycle
through each character in a string SET animalName TO ‘monkey’
FOR index = 0 TO LENGTH(animalName) - 1
SEND animalName[index] TO DISPLAY
END FOR
PYTHON
animalName = ‘monkey’
for index in range 0, len(animalName):
print(animalName[index])
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 55 18/05/20 11:43 AM
56 UNIT 2 PROGRAMMING 7 Strings
JAVA
class Main {
public static void main(String[] args) {
String animalName = “monkey”;
for(int index = 0; index < animalName.length(); index++) {
System.out.println(animalName.charAt(index));
}
}
}
C#
string animalName = “monkey”;
PROBLEM SOLVING,
SKILLS CREATIVITY, ACTIVITY 13
DECISION MAKING
WHICH CAR?
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Write a program that will check if a make of car entered by the user is in
the string ‘The cars present included Ford, Mercedes, Toyota, BMW, Audi
and Renault.’
If the car entered by the user is present, then ‘It is present’ should be
returned or ‘It is not present’, if not.
It should not matter which case the car name is entered by the user.
PYTHON
Python uses square brackets to access elements in a string:
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 56 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 7 Strings 57
JAVA
Java allows you to get a character at a particular index using the charAt
method.
class Main {
public static void main(String[] args) {
String string = “Computer Science”;
System.out.println(string.charAt(11));
}
}
This code would display the character ‘i’ (the 12th character at index 11).
C#
string text;
text = “Computer Science”;
Console.WriteLine(text[3]);
JAVA
class Main {
public static void main(String[] args) {
String string = “Computer Science”;
string = string.toLowerCase();
System.out.println(string);
}
}
C#
string text;
text = “Computer Science”;
text = text.ToLower();
Console.WriteLine(text);
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 57 18/05/20 11:43 AM
58 UNIT 2 PROGRAMMING 7 Strings
JAVA
class Main {
public static void main(String[] args) {
String string = “Computer Science”;
string = string.toUpperCase();
System.out.println(string);
}
}
C#
string text;
text = “Computer Science”;
text = text.ToUpper();
Console.WriteLine(text);
JAVA
class Main {
public static void main(String[] args) {
String string = “Computer Science”;
String substring = string.substring(3,6);
System.out.println(substring);
}
}
C#
string text;
text = “Computer Science”;
text = text.Substring(3,4);
Console.WriteLine(text);
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 58 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 7 Strings 59
PYTHON
string = ‘Computer Science’
present = ‘put’ in string
print(present)
present = ‘PUT’ in string
print(present)
JAVA
class Main {
public static void main(String[] args) {
String string = “Computer Science”;
boolean present = string.contains(“put”);
System.out.println(present);
present = string.contains(“PUT”);
System.out.println(present);
}
}
C#
You can check if a substring is present in a string using the contains method. If
the substring is present in the string then ‘True’ is returned, otherwise ‘False’ is
returned.
string text;
bool found = false;
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Note that literal text is enclosed in speech marks but the variable name is not.
In Python, this would be:
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 59 18/05/20 11:43 AM
60 UNIT 2 PROGRAMMING 7 Strings
In Python, you cannot concatenate strings with numbers. For example, the
following would produce an error message.
length = 13
print(‘The length is’ + length)
In Java, you can concatenate strings with most other data types:
COMPARING STRINGS
Comparing strings in Python and C# can be done using the == operator but in
Java you need to use a string object’s equals method:
PROBLEM SOLVING,
SKILLS CREATIVITY, ACTIVITY 14
DECISION MAKING
CONCATENATING AND SLICING STRINGS
A company wants a program to generate usernames for new employees.
Each username consists of the first four letters of the employee’s
last name and the first letter of their first name joined together. If the
employee’s last name is less than four characters in length a letter ‘X’
is used to fill in for each of the missing characters. Develop a program
that asks the user to input their first and last names and outputs their
username.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 60 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 7 Strings 61
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 How are individual characters in a string referenced?
Challenge
SKILLS
PROBLEM SOLVING, C1 Develop a program that asks the user to input a sentence and then
CREATIVITY splits it up wherever a space occurs. Each word should then be
displayed on a separate line.
SUMMARY
◼◼ A string is a sequence of characters.
◼◼ Each character in a string has a unique index value representing its
position in the string. The first character in a string has the index value 0.
◼◼ High-level programming languages have a built-in length function that
finds the length of a string.
◼◼ A loop is used to traverse a string, character by character.
◼◼ Concatenation is the process of joining two or more strings together.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 61 18/05/20 11:43 AM
62 UNIT 2 PROGRAMMING 8 Data structures
8 DATA STRUCTURES
Data should be classified and organised into similar types so it can be easily
searched and analysed. They are stored together in data structures, such as
records and arrays.
LEARNING OBJECTIVES
items of data of the same type. The data is In the Pearson Edexcel pseudocode, an array is initialised using the SET
indexed so that a particular item of data command. For example, this statement initialises an array called firstNames
can be easily found with four elements, all of string type. The square brackets denote the start and
index a number that identifies each end of the array.
element of an array in Python and Java
SET firstNames TO [‘Ashura’, ‘Bryn’, ‘Eloise’, ‘Mei’]
In most programming languages, arrays are static. A static array has a fixed
size and when it is declared the number of items it can hold must be stated.
For example, array friends [5].
As with strings, arrays have a length indicating the number of items. Here are
the functions to find the length of an array declared as myArray.
PYTHON JAVA C#
len(myArray) myArray.length myArray.Length
ACTIVITY 15
Declare an array with the elements Ford, Mercedes, Toyota, BMW, Audi
and Renault.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 62 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 8 Data structures 63
PYTHON
In Python, arrays are not commonly used. Instead lists are used but they are
very similar in the way that they operate. Just like an array, a list is created by
adding items, separated by commas, inside square brackets.
Lists are easier to use as they are dynamic – they do not have a fixed size and
can grow as new elements are added. When they are declared they do not
have to be given a size, e.g.:
cars = []
When adding items to an array the append command is used, for example:
cars = []
cars.append(‘Audi’)
print(cars)
[‘Audi’]
Another advantage of lists is that the items do not have to be of the same data
type.
cars = []
cars.append(‘Audi’)
cars.append(3)
print(cars)
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
would return:
[‘Audi’, 3]
max()
min()
slice()
JAVA
Arrays are static data structures, which means that you can’t change the size
of an array to make it bigger or smaller in order to add or remove values.
integers.add(6); or integers.remove(5);
In order to add or remove values you need to use a list which is a dynamic
data structure.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 63 18/05/20 11:43 AM
64 UNIT 2 PROGRAMMING 8 Data structures
This example will display [2,3,4,5,6] because the first value will be removed.
Arrays are supported for any data type in Java. For example, you can have an
array of strings:
However, you can’t have an array that contains both strings and integers (or
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
This example will output [1, Two true] because the vector allSorts contains
an integer, a string and a Boolean value.
C#
C# supports lists and arrays. The code below uses an array to hold the items.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 64 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 8 Data structures 65
CRITICAL
SKILLS THINKING , ACTIVITY 16
PROBLEM
SOLVING,
CREATIVITY DESCRIBING AND IMPLEMENTING A LINEAR SEARCH ALGORITHM
The following code uses a linear search algorithm.
SET
firstNames TO [‘Ashura’, ‘Bryn’, ‘Eloise’, ‘Mei’, ‘James’, ‘Irena’]
RECEIVE searchName FROM (STRING) KEYBOARD
MULTIDIMENSIONAL ARRAYS
In the array cars = [‘Ford’, ‘Mercedes’, ‘Toyota’, ‘BMW’, ‘Audi’,
‘Renault’] there is only one item at each index position: the name of the
manufacturer.
0 1 2 3
0 80 59 34 89
1 31 11 47 64
2 29 56 13 91
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 65 18/05/20 11:43 AM
66 UNIT 2 PROGRAMMING 8 Data structures
Each item of data has two indexes. An array to hold this data would be
declared as array[3, 4].
If the array was printed it would be [[80, 59, 34, 89], [31, 11, 47,
64], [29, 56, 13, 91]]. There are square brackets around each set of
results and around the whole array.
Scores = [[80, 59, 34, 89], [31, 11, 47, 64], [29, 56, 13, 91]]
WORKED EXAMPLE
A teacher has stored the surnames and test scores of a class of
students in a two-dimensional array, e.g. results[[‘Smith, ‘69’],
[‘Jackson’, ‘90’], etc. Create a program that would print out the
names and test scores of all the students who have scored 50 or over in
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
the test.
Python
results = [[‘Smith’, 69], [‘Jackson’, 90], [‘Dubois’, 30]]
for index in range(0, len(results)):
if results[index][1] >= 50:
print(results[index][0] + str(results[index][1]))
Java
class Main {
public static void main(String[] args) {
String[][] results = {
{“Smith”, “69”},
{“Jackson”, “90”},
{“Dubois”, “30”}};
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 66 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 8 Data structures 67
C#
string[,] results = new string[,] { { “Smith”, “69” },
{ “Jackson”, “90” }, { “Dubois”, “30” } };
results[index,1]);
}
}
In C# an array only consists of one data type, hence the student scores
are in double quotes. To be able to check if the student scores are above
50, the score in the array must be cast as an integer using int.Parse.
CRITICAL THINKING,
SKILLS PROBLEM SOLVING, ACTIVITY 17
CREATIVITY
USING TWO-DIMENSIONAL ARRAYS
HINT
1 Develop a program that creates and initialises an array to hold these
All the data values stored in an
five sets of marks.
array must be of the same data
80, 59, 34, 89
type. In this case they are all
31, 11, 47, 64
strings. You will have to convert
29, 56, 13, 91
the scores to integers to find the
55, 61, 48, 0
highest. But as Python uses lists
75, 78, 81, 91
this is not necessary. Strings and
integers can be combined within 2 Extend your program so that it calculates and displays the highest
the same list. mark, the lowest mark and the average mark achieved.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 67 18/05/20 11:43 AM
68 UNIT 2 PROGRAMMING 8 Data structures
ACTIVITY 18
This two-dimensional array holds the highest score achieved by each
player in each of the three levels of an online game.
1 Develop a program that initialises the array and then searches through
it to find the player with the highest score in each of the three levels.
Seema 1 29
Seema 2 44
Lois 1 10
Alexis 2 17
Alexis 3 36
Dion 1 23
Emma 1 27
Emma 2 48
RECORDS We have already said that the elements of an array must all be the same data
type. In contrast, the record data structure stores a set of related values of
different data types.
Each element in a record is known as a field and is referenced using a field name.
SUBJECT VOCABULARY
record a data structure that stores a set Table 2.10 shows how the record data structure works. Each row of the table
of related values of different data types holds a set of information about a particular learner (these are the records).
field an individual element in a record Each column stores one item of information about the learner – their learner
number, their age, their form, etc. (these are the fields). All the values in a
column have the same data type – learnerNum and ‘age’ are integers;
firstName, lastName and ‘form’ are strings.
Programming languages vary in the way they handle the record data structure.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 68 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 8 Data structures 69
CRITICAL THINKING,
SKILLS PROBLEM SOLVING, ACTIVITY 19
CREATIVITY
USING RECORDS TO STORE MUSIC DETAILS
1 A record data structure is to be used to store the details of music
albums. Provide the appropriate data type for these fields:
a the title of the album
b the name of the artist
c the year of release
d the genre.
2 Develop a program that uses a record structure for storing the details
of music albums. It must:
▲ It is essential to have a way to sort through a have fields for title, artist, year of release and genre
the vast amounts of recorded music available
b allow the user to input the details of new albums
c allow the user to search for an album by name and display its details.
CHECKPOINT
Strengthen
SKILLS CRITICAL THINKING S1 What is the index of the first element in a one-dimensional array?
SKILLS REASONING S2 How does a linear search algorithm find an element in a one-
dimensional array?
Challenge
CRITICAL THINKING,
SKILLS C1 Develop a program for a simple address book that uses a two-dimensional
PROBLEM SOLVING
array to store a set of names and email addresses, and allows the user to
search for a person by name and returns their email address.
CRITICAL THINKING,
SKILLS C2 Develop a program that uses a two-dimensional array to represent a
PROBLEM SOLVING
treasure map consisting of a grid of 4 rows and 4 columns. A random
number function should be used to establish the location of the
treasure. The user must hunt for the treasure by repeatedly entering
the coordinates of squares. The program should tell them when they
have found the treasure and help them in their search by indicating
how close they are.
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try redoing activities 15–19.
SUMMARY
◼◼ A data structure is an organised collection of related elements. Arrays
and records are common data structures.
◼◼ A one-dimensional array is a list of elements, each of which has a
unique index value representing its position in the list.
◼◼ A two-dimensional array is a matrix of rows and columns. Each
element in the array has a unique pair of indices, one to identify the
row and one the column in which it is located.
◼◼ All the elements in an array have the same data type (Python uses lists).
◼◼ A record consists of a collection of fields. The values stored in a
record can be of different data types.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 69 18/05/20 11:43 AM
70 UNIT 2 PROGRAMMING 9 Input/output
9 INPUT/OUTPUT
All program data has to be entered (input) and information is output. The
input could be automatic, e.g. from a sensor, but is often provided by human
users. It is essential that this input is checked to ensure that it is what could
reasonably be expected and falls within a certain range. Incorrect input could
cause problems or even catastrophes.
LEARNING OBJECTIVES
USER INPUT Most programs require some form of input either from a user or from a file. You
already know how to receive user input from a keyboard.
A program can be made much more ‘user friendly’ by displaying helpful messages
informing users of what they are expected to enter and confirming successful input.
VALIDATION
It is important to ensure that data entered by the user is valid, as invalid data
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Any program that requires data entry should have appropriate forms of
SUBJECT VOCABULARY validation built in. But validation can’t guarantee that the data entered is
correct. It can only make sure that it is reasonable.
validation to check that the data entered
by a user or from a file meets specified There are a number of different types of validation.
requirements
RANGE CHECK
A range check is used to ensure that the data entered is within a specified range.
Study this algorithm, written in Pearson Edexcel pseudocode which checks that
the number entered is between 1 and 10.
BOOLEAN valid
SET validNum TO False
WHILE validNum = False DO
SEND ‘Please enter a number between 1 and 10:’ TO
DISPLAY
RECEIVE number FROM (INTEGER) KEYBOARD
IF number >= 1 AND number <= 10 THEN
SET validNum TO True
END IF
END WHILE
SEND ‘You have entered:’ & number TO DISPLAY
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 70 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 71
CRITICAL THINKING,
SKILLS PROBLEM SOLVING ACTIVITY 20
IMPLEMENTING RANGE CHECKS
Implement the range check algorithm in the high-level programming
language you are studying.
PRESENCE CHECK
Another type of validation is a presence check. This simply ensures that a
value has been entered, preventing the user from leaving an input blank.
This algorithm asks the user to input their name and uses a presence check to
ensure they have entered a value. Any value will cause the loop to finish. It will
keep asking the user to input their name until they input a value.
SET userName TO ‘ ’
WHILE userName = ‘ ’ DO
RECEIVE userName FROM (STRING) KEYBOARD
END WHILE
SEND ‘Hello’ & userName TO DISPLAY
CRITICAL THINKING,
SKILLS PROBLEM SOLVING ACTIVITY 21
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
This algorithm stores a list of valid form names in an array. It compares the
form name entered by the user with the values in the array.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 71 18/05/20 11:43 AM
72 UNIT 2 PROGRAMMING 9 Input/output
CRITICAL THINKING,
SKILLS PROBLEM SOLVING ACTIVITY 22
IMPLEMENTING A LOOK-UP CHECK
Implement the look-up check algorithm in the high-level programming
language you are studying.
LENGTH CHECK
It is sometimes necessary to check that the length of a value entered falls
within a specified range. For example, all UK postcodes are between six and
eight characters long, so validation could be used to check that the length
of a postcode entered is within this range. Needless to say, that doesn’t
necessarily mean it is correct.
TESTING VALIDATION RULES It is important to test your validation rules to ensure they work as expected.
You should use:
Normal data – This is data that is within the limits of what should be accepted
by the program. For example, a password with seven characters fulfils the
validation rule that states that passwords must be between six and eight
characters in length.
Boundary data – This is data that is at the outer limits of what should be
accepted by the program. For example, if a validation rule specifies that the
range of acceptable values is >= 75 AND <= 100, then a value of 100 is at the
upper limit and a value of 75 at the lower.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 72 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 73
GENERAL VOCABULARY Erroneous data – This is data that should not be accepted by the program.
For example, a value of 0 should not be accepted by either of the validation
erroneous not correct; based on rules given above.
incorrect information
WORKING WITH TEXT FILES The programs you have created so far haven’t required a huge amount of data
entry, but imagine typing a set of test results for everyone in your computer
science class. It would take a considerable amount of time to do and – even
worse – when the program terminates, all of the data will be lost. Should you
SUBJECT VOCABULARY need to use it again you’d have to re-enter it. This is where storing data in an
text file a sequence of lines, each of external file comes in really useful. If the data you enter is stored in an external
which consists of a sequence of characters text file you can access it as often as you like without having to do any further
keying in.
Text files provide permanent storage for data. This means that the data can
be reused without having to be retyped. Data can be read from, written to and
SUBJECT VOCABULARY appended to a file.
After a file has been opened it must be closed. The data is not written to a file
until this command is executed.
The following program would create a text file called ‘names’ and add two
items of data.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 73 18/05/20 11:43 AM
74 UNIT 2 PROGRAMMING 9 Input/output
There is nothing to separate the two items of data. Therefore, it is useful to add
a character such as a ‘,’ or a ‘;’ between them.
It is important to separate the data items so that they can be read back into a
data structure.
The following program would write the contents of an array into a text file
called cars.txt with a comma between them.
myFile.close()
The file can be read back into an array in the following way.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Blist = []
myFile = open(‘cars.txt’, ‘r’)
Blist = myFile.read().split(‘,’)
MyFile.close()
JAVA
Java programs that read and write to files often start with:
import system.io.*
This allows your Java code to access files such as File and FileReader,
FileWriter from the system.io namespace.
import java.io.*;
class Main {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter(“names.txt”);
fw.write(“First item”);
fw.write(“Second item”);
fw.close();
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 74 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 75
} catch (IOException e) {
System.out.println(“Could not write to file”);
}
}
}
This example will write two strings to the file names.txt, which would then
contain: First itemSecond item.
It is useful to separate each data value in a file with a comma (,) or new line
(\n) so that they can then be read back into an array or opened as a comma
separated value (CSV) file to be edited in a spreadsheet program:
import java.io.*;
class Main {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter(“names.txt”);
fw.write(“First item,”);
fw.write(“Second item\n”);
fw.close();
} catch (IOException e) {
System.out.println(“Could not write to file”);
}
}
}
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Note that the two examples above contain try…catch blocks of code.
These are necessary in Java because file input or output can often cause
runtime errors and Java needs to know what to do instead of crashing
the program.
The following program will write the contents of an array of car brands into a
file called cars.txt with each value separated by a comma:
import java.io.*;
class Main {
public static void main(String[] args) {
String[] cars = {“BMW”, “Toyota”, “Audi”, “Renault”,
“Rover”};
try {
FileWriter fw = new FileWriter(“cars.txt”);
for(int index = 0; index < cars.length; index++) {
fw.write(cars[index] + “,”);
}
fw.close();
} catch (IOException e) {
System.out.println(“Could not write to file”);
}
}
}
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 75 18/05/20 11:43 AM
76 UNIT 2 PROGRAMMING 9 Input/output
The file can be read back into an array in the following way:
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
String[] cars;
try {
File file = new File(“cars.txt”);
Scanner scanner = new Scanner(file);
String line = scanner.nextLine();
scanner.close();
} catch (IOException e) {
System.out.println(“Could not read from file”);
}
}
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
C#
In C#, you’re likely to use the File class for reading and writing files. To use the
File class you will need to add the line Using System.IO; at the top of your
C# program, usually under the existing Using System; line. The File class
provides over 50 different methods for working with files, so this section only
provides an introduction to some of the basic methods.
WRITING TO A FILE
C#
The following program creates a file called “names.txt” and adds two items
of data.
StreamWriter sw = new StreamWriter(“names.txt”);
sw.Write(“First Item”);
sw.Write(“Second Item”);
sw.Close();
The file it creates would contain: First itemSecond item. There is nothing
to separate the two items of data. Therefore, it is useful to add a character such
as a comma or semicolon between them. The file created would then contain:
First item,Second item. It is important to separate the data items so that
they can be read back into a data structure.
The following program would write the contents of an array into a text file
called cars.csv with a comma between each item.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 76 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 77
sw.Close();
ACTIVITY 24
A student has coded a computer game which stores the five highest
scores in an array. She now wants to save those scores to a file and load
them back in when the game is run again.
Write a program that will save the array of scores to a suitable text file and
then load them back in again. Run your program to check that it is working
as intended.
PYTHON
A two-dimensional array can be stored in a text file in a similar way.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
A teacher stores the names of students and their test scores in a two-
dimensional array.
for x in range(len(Slist)):
myFile.write(Slist[x][0] + ‘,’)
new = str(Slist[x][1])
myFile.write(new + ‘,’)
myFile.close()
It is easier to copy the items from a text file into a two-dimensional array in
two stages.
Blist = []
myFile = open(“results.txt”, “r”)
Blist = myFile.read().split(‘,’)
myFile.close()
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 77 18/05/20 11:43 AM
78 UNIT 2 PROGRAMMING 9 Input/output
newList = []
for index in range(0, len(Blist) - 1, 2):
newLlist.append([Blist[index], Blist[index + 1]])
JAVA
The following code writes the student test scores to a file:
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
// store student scores in a 2d array
String[][] studentScores = {
{“Faruq”, “60”},
{“Jalila”, “90”}
};
The following code reads the test scores back into a two-dimensional array:
import java.io.*;
import java.util.*;
class Main {
public static void main(String[] args) {
// list of arrays of strings to store results
ArrayList<String[]> results = new ArrayList<String[]>();
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 78 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 79
// s
plit line into name and score and add it to
the list
String[] singleStudent = line.split(“,”);
results.add(singleStudent);
}
scanner.close();
} catch (IOException e) {
System.out.println(“Could not read from file”);
}
}
}
C#
string[,] grades = new string[,] { { “Faruq”, “60” }, {
“Jalila”, “90” } };
sw.Close();
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 79 18/05/20 11:43 AM
80 UNIT 2 PROGRAMMING 9 Input/output
string[,] grades;
grades = new string[length, 2];
ACTIVITY 25
In Activity 24, only the high scores were saved. Change your program
so that high scores and the names of the players who attained them are
stored.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
CHECKPOINT
Strengthen
SKILLS REASONING
S1 What might happen if a program doesn’t include validation on user input?
SKILLS CRITICAL THINKING S2 Can you think of a data structure that is suitable for storing a list of
values used in a look-up check?
SKILLS PROBLEM SOLVING S3 Show how your name, date of birth and favourite colour would be
stored in a text file.
SKILLS REASONING
S4 Why is it beneficial to write data to a text file?
Challenge
SKILLS PROBLEM SOLVING C1 Develop a program that:
◼◼ writes a set of employee records consisting of employee number,
name and department to a text file
◼◼ reads in the stored records from the text file
◼◼ allows the user to search for an employee’s details.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 80 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 9 Input/output 81
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try redoing the activities in this section.
SUMMARY
◼◼ Validation techniques should be used to ensure that data entered
by a user or from a file is valid. They can’t guarantee that the data is
correct, only that it is reasonable.
◼◼ A range check is used to ensure that data is within a specified range.
◼◼ A length check is used to ensure that data has a length within a
specified range.
◼◼ A presence check is used to ensure the user has entered some data.
◼◼ When users are required to choose from a list of options, their input
should be validated to ensure that their choice is valid.
◼◼ Large sets of data are normally stored in text files. The advantage of
writing data to a file is that the data is not lost when the program is
terminated. It can be read in from the file whenever it is needed.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 81 18/05/20 11:43 AM
82 UNIT 2 PROGRAMMING 10 Subprograms
10 SUBPROGRAMS
When programs are being coded, they should be as structured as possible
so that people reading them can quickly understand their logic. One way
of doing this is to use self-contained modules, which can be reused where
possible. This ensures that programs are shorter, as commands do not have
to be repeated several times. These modules can then be called when they
are needed.
LEARNING OBJECTIVES
FUNCTIONS
EXAMPLE FUNCTIONS
A function returns a value to the main program that called it.
dieThrow = dice()
▲ Figure 2.3 The symbol for a subprogram
in a flowchart The value returned by the function is stored in the variable dieThrow.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 82 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 10 Subprograms 83
PYTHON
def dice()
simDie = random.randint(1, 7)
return simDie
JAVA
import java.util.*;
class Main {
// define the function
public static int dice() {
Random r = new Random();
return 1 + r.nextInt(6);
}
C#
SUBJECT VOCABULARY As C# is an OOP language it has methods rather than functions. There are a
OOP language an object-oriented number of ways of implementing methods, but it could be written like this:
programming language. Instead of data
structures and separate program public static int dice()
structures, both data and program {
elements are combined into one structure Random random = new Random();
called an object return random.Next(1, 7);
}
It would be called from the main program by: int value = dice();.
LOCAL AND GLOBAL VARIABLES Notice that there are two variables that store the random number
generated by the function. In the function itself, the variable simDie is
used. This variable only exists within the function and is referred to as a
SUBJECT VOCABULARY
local variable.
local variable a variable that is
accessed only from within the subprogram In the main program the value returned by the function is stored in the variable
in which it is created dieThrow. It can be used anywhere within the main program and is therefore
global variable a variable that can be referred to as a global variable.
accessed from anywhere in the program,
including inside subprograms PROCEDURES
Unlike a function, a procedure does not return a value to the main program.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 83 18/05/20 11:43 AM
84 UNIT 2 PROGRAMMING 10 Subprograms
EXAMPLE PROCEDURE
In the dice example, a procedure would be written in pseudocode as:
Python
In Python, it would be exactly the same without the return command.
PROCEDURE dice()
simDie = RANDOM(6)
SEND simDIE TO DISPLAY
END PROCEDURE
Java
Because a procedure doesn’t return a value, Java uses the void keyword
to indicate that a subprogram doesn’t return a value.
import java.util.*;
class Main {
// define the procedure
public static void dice() {
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
C#
In C#, the equivalent to a procedure is a method that doesn’t return a
value. For example:
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 84 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 10 Subprograms 85
ARGUMENTS AND PARAMETERS Data for the functions and procedures to work on can be passed from the
main program as arguments. The function accepts them as parameters.
SUBJECT VOCABULARY
parameter the names of the variables
that are used in the subroutine to store the
PYTHON
data passed from the main program as # Function rectangle
arguments def rectangle(length, width):
area = length * width
return area
#Main program
rectangleLength = int(input(‘Please enter the length of
the rectangle’))
rectangleWidth = int(input(‘Please enter the width of the
rectangle’))
rectangleArea = rectangle(rectangleLength, rectangleWidth)
print(rectangleArea)
JAVA
import java.util.*;
class Main {
// define the rectangle function
public static int rectangle(int length, int width) {
int area = length * width;
return area;
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
C#
public static void Main()
{
string lengthString, widthString;
int length, width, rectangleArea;
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 85 18/05/20 11:43 AM
86 UNIT 2 PROGRAMMING 10 Subprograms
In this example, two data items are passed to the function – rectangleLength
and rectangleWidth. These are called arguments.
The function receives them as parameters called length and width when the
function is declared.
SUBJECT VOCABULARY In the function, a variable is declared – area. This is called a local variable and
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
its scope is within the function. If you tried to use it in the main program you
scope the region of code within which a would get an error message.
variable is visible
Lots of arguments can be passed to the function and many values can be
returned.
PYTHON
# Function rectangle
def rectangle(length, width):
area = length * width
circumference = (2 * length) + (2 * width)
return area, circumference
#Main program
rectangleLength = int(input(‘Please enter the length of
the rectangle’))
rectangleWidth = int(input(‘Please enter the width of the
rectangle’))
rectangleArea, rectangleCircumference = rectangle
(rectangleLength, rectangleWidth)
print(rectangleArea)
print(rectangleCircumference)
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 86 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 10 Subprograms 87
JAVA
In Java, functions can only return one value so if you need to return more than
one value, you need to put them in a list or array.
import java.util.*;
class Main {
/
/ returns an array of the area and perimeter of a rectangle
public static int[] rectangle(int length, int width) {
int area = length * width;
int perimeter = 2 * (length + width);
return new int[]{area, perimeter};
}
C#
Methods in C# can’t return multiple values unless you use By Reference,
which is beyond the scope of this book.
ACTIVITY 26
From the above example, list:
a the global variables
b the local variables
c the arguments
d the parameters.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 87 18/05/20 11:43 AM
88 UNIT 2 PROGRAMMING 10 Subprograms
SUBPROGRAMS AND MENUS Functions and procedures are useful when using menus in a program. When a
user selects a menu option, they can be sent to a particular function or procedure.
WORKED EXAMPLE
For a system login and password control, the main program could have a
menu system like this:
The user enters a number between 1 and 4 and is directed to the correct
section:
Python
print (“1. Register as a new user”)
print (“2. Login.”)
print (“3. Change your password.”)
print (“4. Exit.”)
if choice == 1:
newUser()
elif choice == 2:
login()
elif choice == 3:
changePassword()
elif choice == 4:
exit()
else:
print(‘Incorrect option. Try again.’)
Java
import java.util.*;
class Main {
// procedures can be implemented later
// just shown here to illustrate the structure
public static void newUser() {}
public static void login() {}
public static void changePassword() {}
public static void exit() {}
public static void main(String[] args) {
// display main menu
System.out.println(“1. Register as a new user”);
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 88 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 10 Subprograms 89
System.out.println(“2. Login”);
System.out.println(“3. Change your password”);
System.out.println(“4. Exit”);
// get user input
Scanner scanner = new Scanner(System.in);
int choice = scanner.nextInt();
switch(choice) {
// Register as a new user
case 1:
newUser();
break;
// Login
case 2:
login();
break;
// change password
case 3:
changePassword();
break;
// exit
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
case 4:
exit();
break;
// anything else
default:
System.out.println(“Incorrect option, try
again”);
break;
}
scanner.close();
}
}
C#
string choiceString;
int choice;
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 89 18/05/20 11:43 AM
90 UNIT 2 PROGRAMMING 10 Subprograms
ACTIVITY 27
a Describe the purpose of the program in the worked example above
and explain how it functions.
b If the user inputs an incorrect option, they receive an error message
and then the program terminates. Edit the program so that the
program will run until a suitable option is input.
THE BENEFITS OF USING Repeated sections of code need only be written once and called when
SUBPROGRAMS
necessary. This shortens the development time of a program and means that
the finished program will occupy less memory space when it is run.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 90 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 10 Subprograms 91
SKILLS REASONING S2 What is meant by the scope of a variable? Use your own examples.
SKILLS REASONING S3 What happens when a global variable and a local variable share the
same name?
Challenge
SKILLS PROBLEM SOLVING C1 Create and implement a calculator program that:
◼◼ allows the user to enter a set of numbers
◼◼ uses separate functions to calculate the mean, mode and median
◼◼ allows the user to select which function they want
◼◼ uses appropriate validation.
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try redoing the activities in this section.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
SUMMARY
◼◼ A subprogram is a section of code within a larger piece of code that
performs a specific task. It can be used at any point in the program.
◼◼ A function is a subprogram that returns a value to the main program.
◼◼ A procedure is a subprogram that does not return a value to the main
program.
◼◼ Parameters are values that are passed to a subprogram when it is called.
◼◼ Local variables can only be accessed from within the subprogram in
which they are created.
◼◼ Global variables can be accessed anywhere in the program, including
inside subprograms.
◼◼ Built-in functions are functions provided in a high-level programming
language to perform common tasks.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 91 18/05/20 11:43 AM
92 UNIT 2 PROGRAMMING 11 Testing and evaluation
LOGIC ERRORS Logic errors occur when the thinking behind an algorithm is incorrect so that
the output isn’t what is expected or intended. Ideally, logic errors should be
EXTEND YOUR KNOWLEDGE identified and fixed at the design stage.
Research other problems and The following algorithm is intended to work out whether a learner has passed a
disasters that have been caused test. Learners need a score of 80 or above to pass. However, a logic error in the
by software failures. algorithm means that it produces an incorrect and unexpected result.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 92 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 93
With a partner, discuss this algorithm and find the logic error in the algorithm?
Start
Input
yearGroup
Is
yearGroup >=
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
7 OR <= 13?
YES
WORKED EXAMPLE
Study this algorithm.
But there is a logic error. The variable ‘index’ is initialised in the wrong
place. It should be done before the start of the WHILE loop.
This algorithm would loop forever because at each turn in the loop
the variable index is set to 1. It will never reach 10. This is an
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 93 18/05/20 11:43 AM
94 UNIT 2 PROGRAMMING 11 Testing and evaluation
SUBJECT VOCABULARY
example of an ‘infinite loop’. The algorithm should have been written
infinite loop a loop that is never-ending as shown below.
since the condition required to terminate
SET index TO 1
the loop is never reached
WHILE index < 10
SEND index TO DISPLAY
GENERAL VOCABULARY
SET index TO index + 1
terminate to cause something to end or END WHILE
stop
REASONING,
SKILLS PROBLEM SOLVING ACTIVITY 29
FINDING AND CORRECTING ERRORS
Find and correct the errors in these algorithms.
Example 1
SET index TO 1
WHILE index < 10
SEND index TO DISPLAY
END WHILE
Example 2
SET index TO 1
WHILE index < 10
SEND index TO DISPLAY
SET index TO index - 1
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
END WHILE
Example 3
SET index TO 1
WHILE index < 1
SEND index TO DISPLAY
SET index TO index + 1
END WHILE
TRACE TABLES
The formal way of checking the logic of an algorithm is to use a trace table.
SUBJECT VOCABULARY
logic error an error in an algorithm that WORKED EXAMPLE
results in incorrect or unexpected
behaviour Create a trace table for the following algorithm written in Pearson Edexcel
trace table a technique used to identify pseudocode.
any logic errors in algorithms. Each column SET number TO 3
represents a variable or output and each FOR index FROM 1 TO 5 DO
row a value of that variable
SET number1 TO number * index
SET number2 TO number1 * 2
IF number2 > 20 THEN
SEND number2 TO DISPLAY
END IF
END FOR
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 94 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 95
3 1 3 6
3 2 6 12
3 3 9 18
3 4 12 24 24
3 5 15 30 30
When the value of number2 is greater than 20, its value is output.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
WORKED EXAMPLE
Here is a program.
Python
y = 2
for x in range(1, 7):
y = y + x
print(y)
Java
class Main {
public static void main(String[] args) {
int y = 2;
for(int x = 1; x < 7; x++) {
y += x;
}
System.out.println(y);
}
}
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 95 18/05/20 11:43 AM
96 UNIT 2 PROGRAMMING 11 Testing and evaluation
C#
int number = 3;
int number1, number2;
X Y OUTPUT EXPLANATION
4 8
5 12 Explanations as above.
6 17
ACTIVITY 30
Complete a trace table for this program written in a high-level
language.
Python
number1 = 2
number2 = 3
for index in range(1, 6)
number1 = number1 * index
number2 = number2 + number1
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 96 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 97
Java
class Main {
public static void main(String[] args) {
int number1 = 2;
int number2 = 3;
for(int index = 1; index < 6; index++) {
number1 = number1 * index;
number2 = number2 + number1;
}
}
}
C#
int number1 = 2;
int number2 = 3;
for (int index = 1; index < 6; index++)
{
number1 = number1 * index;
number2 = number2 + number1;
}
learners in a class.
Python
gender = [‘M’, ‘M’, ‘F’, ‘M’, ‘F’, ‘F’, ‘M’, ‘F’, ‘M’, ‘F’]
length = len(gender)
count = 0
for index in range(length):
if gender[index] ‘F’:
count = count + 1
Java
class Main {
public static void main(String[] args) {
String[] gender = {“M”, “M”, “F”, “M”, “F”, “F”,
“M”, “F”, “M”, “F”};
int length = gender.length;
int count = 0;
for(int index = 0; index < length; index++) {
if(gender[index].equals(“F”)) {
count++;
}
}
}
}
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 97 18/05/20 11:43 AM
98 UNIT 2 PROGRAMMING 11 Testing and evaluation
C#
int length, count;
char[] gender;
gender = new char[]{ ‘M’, ‘M’, ‘F’, ‘M’, ‘F’, ‘F’, ‘M’,
‘F’, ‘M’, ‘F’ };
count = 0;
length = gender.Length;
for (int index = 0; index < length; index++)
{
if (gender[index] == ‘F’)
{
count += 1;
}
}
Python
total = 0
number = int(input(‘Please enter the number’)
while number > 0:
total = total + number
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
Java
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int total = 0;
System.out.print(“Please enter the number: “);
int number = scanner.nextInt();
while(number > 0) {
total += number;
number = scanner.nextInt();
}
System.out.println(total);
}
}
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 98 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 99
C#
int total = 0;
int number;
string numberString;
SYNTAX ERRORS Syntax errors occur when the grammar rules of a programming language are
not followed.
RUNTIME ERRORS Runtime errors occur during program execution and are the most difficult to
predict and spot.
SUBJECT VOCABULARY
runtime error an error that occurs while This program is designed to take two numbers, divide the first number by
the program is running – the operation the the second number and output the result. It will work as intended at least
computer is asked to do is impossible to some of the time. However, if the user entered 5 and 0, a runtime error
execute would occur because it is impossible for the computer to divide 5 by 0.
Python
firstNumber = int(input(‘Please enter the first number’)
secondNumber = int(input(‘Please enter the second
number’)
result = firstNumber / secondNumber
print(result)
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 99 18/05/20 11:43 AM
100 UNIT 2 PROGRAMMING 11 Testing and evaluation
Java
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Please enter the first number: ”);
int firstNumber = scanner.nextInt();
System.out.print(“Please enter the second number: ”);
int secondNumber = scanner.nextInt();
scanner.close();
C#
int firstNumber, secondNumber, result;
string firstNumberString, secondNumberString;
firstNumber = int.Parse(firstNumberString);
ERROR SUMMARY This table gives a summary of the three types of error you are likely to encounter.
Logic The program seems to run normally; however, there is an error in the logic of the program, which
means it does not produce the result you expect.
Syntax Syntax refers to the rules of the programming language. A syntax error means that part of the code
breaks the rules of the language, which stops it running.
Runtime An error that occurs when the computer tries to run code that it cannot execute.
▲ Table 2.14 Summary of the three types of error you are likely to encounter
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 100 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 TESTING AND EVALUATION 101
USING AN INTEGRATED You probably already have first-hand experience of using an Integrated
DEVELOPMENT ENVIRONMENT (IDE) Development Environment (IDE) when writing code. It’s definitely worth
taking some time to get to know the IDE that comes with the language you are
SUBJECT VOCABULARY using. Useful features such as syntax highlighting, code auto complete and
auto indent will help to make your programming experience far less stressful,
Integrated Development especially at the beginning.
Environment (IDE) a package that helps
programmers to develop program code. It has One of the most useful features of an IDE is the debugger. One of its tasks
a number of useful tools, including a source is to flag up syntax errors in the code and issue helpful error messages. It is
code editor and a debugger really important that you get lots of practice interpreting error messages and
debugger a computer program that fixing errors in your code.
assists in the detection and correction of
errors in other computer programs HINT
Here are some error messages that you are likely to see in popular IDEs.
◼ SyntaxError: invalid syntax – part of the code breaks one of the rules
of the programming language.
◼ IndentationError: expected an indented block – statements after a
colon must be indented.
◼ TypeError: Can’t convert ‘int’ object to str implicitly – trying to join a
string and an integer together.
◼ ZeroDivisionError: integer division or modulo by zero – trying to
divide a value by 0.
◼ NameError: name is not defined – referring to a variable or subprogram
that does not exist.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
THE TEST PLAN At the start of a programming project, it is crucial to make a list of the
requirements that the program is expected to meet. Throughout the
development phase of the project, you should regularly refer back to this list of
requirements to check that you are on track to achieve them.
Deciding how to test the finished program to make sure that it fully meets
the requirements can’t be left to the last moment either. As part of the design
stage, you should create a test plan listing the tests you will carry out, the data
that will be used for each test and the expected result.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 101 18/05/20 11:43 AM
102 UNIT 2 PROGRAMMING 11 Testing and evaluation
MARKS TO GRADES
RECEIVE examMark FROM (INTEGER) KEYBOARD
IF examMark >= 80 THEN
SEND ‘A’ TO DISPLAY
ELSE
IF examMark >= 70 THEN
SEND ‘B’ TO DISPLAY
ELSE
IF examMark >= 60 THEN
SEND ‘C’ TO DISPLAY
ELSE
IF examMark > 0 THEN
SEND ‘D’ TO DISPLAY
ELSE
SEND ‘FAIL’ TO DISPLAY
END IF
END IF
END IF
END IF
This algorithm converts an exam mark into a grade. It should only accept
marks between 0 and 100.
The test plan extract in Table 2.15 shows some of the tests that have been
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
planned for the finished program to ensure that it meets all the requirements.
ACTION NEEDED/
TEST NO. PURPOSE OF THE TEST TEST DATA EXPECTED RESULT ACTUAL RESULT COMMENTS
1 To check correct conversion of 0 ‘FAIL’
valid mark 55 ‘D’
65 ‘C’
75 ‘B’
85 ‘A’
2 To check correct conversion of 0 ‘FAIL’
boundary mark 1, 59 ‘D’
60, 69 ‘C’
70, 79 ‘B’
80, 100 ‘A’
3 To check response to erroneous –5 Error message
mark 105 Error message
▲ Table 2.15 Test plan extract
Only the first four columns of the test plan table can be completed at the design
stage. The remaining columns are filled in when the program is complete.
At the start, it’s unlikely that you’ll know every test that will be needed to
ensure the program works as intended. The test plan is not a fixed document.
If additional tests are required, they should be added to the test plan.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 102 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 103
If a test produces the expected result, you can simply write ‘None’ in the
‘Action needed/comments’ column. If, however, that is not the case then you
should instead note what went wrong and what you did to put it right.
It is important to select suitable test data for the tests. Test data falls into
three different categories: normal, boundary and erroneous.
Normal data Data that is well within the limits of Test 1 uses normal data to check if marks are
what should be accepted by the converted into grades correctly (e.g. a mark of 65
program. should be converted to a grade C).
Boundary data Data that is at the outer limits of what Test 2 uses boundary data to check that the program
should be accepted by the program. works correctly with marks at the upper and lower
boundaries (e.g. a mark of 60 and a mark of 69 should
both convert to a grade C).
Erroneous data Data that should not be accepted by Test 3 uses erroneous data to check that the program
the program. does not accept it.
Testing is just as important as writing code because it ensures that the finished
program works correctly and fully meets the requirements. You should use a
‘bottom up’ approach to testing (i.e. test each subprogram as you develop it
and then test the whole program once it is finished).
Here is the completed test plan for the grade calculator program. As you can
see, the expected result was not produced when the program was tested with
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
erroneous data. A range check had to be added to the program to ensure that
only marks between 0 and 100 can be entered.
ACTION NEEDED/
TEST NO. PURPOSE OF THE TEST TEST DATA EXPECTED RESULT ACTUAL RESULT COMMENTS
▲ Table 2.17 The completed test plan for the grade calculator program
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 103 18/05/20 11:43 AM
104 UNIT 2 PROGRAMMING 11 Testing and evaluation
After you have carried out all of the tests and made all the necessary changes,
the program should be retested. This is to ensure that the improvements you
have made haven’t introduced any new errors into the program.
EVALUATING PROGRAMS You need to be able to identify the strengths and weaknesses of your own
programs as well as those created by other programmers. This will enable you
to identify techniques that work well and aspects that could be improved.
Validation – has
Usability – is the
appropriate validation
program easy to use?
been applied to user input?
Evaluating programs
repetition?
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 104 18/05/20 11:43 AM
UNIT 2 PROGRAMMING 11 Testing and evaluation 105
CHECKPOINT
Strengthen
CRITICAL THINKING, S1 What are the three types of error associated with program development?
SKILLS REASONING
Can you identify the stage(s) of development at which they are most likely
to occur?
SKILLS REASONING S3 What are the features of an IDE that help programmers write error-free
code?
SKILLS CRITICAL THINKING S4 What is the function of a test plan in program development?
SKILLS CRITICAL THINKING S5 What is meant by normal, boundary and erroneous data?
SKILLS REASONING S6 Why might it be necessary to retest a program once all the planned
tests are completed?
Challenge
SKILLS PROBLEM SOLVING C1 Think of a problem which could be solved using a computer program.
What are the requirements for the program? Create a solution and
draw up a test plan for it.
SKILLS PROBLEM SOLVING C2 Develop and implement the program. Conduct your planned tests and
make any necessary changes to your program, ensuring your test plan
is kept up to date.
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
How confident do you feel about your answers to these questions? If you’re
not sure you answered them well, try completing Activities 28–32.
SUMMARY
◼◼ Logic errors occur when there is an error in the logic of the code,
causing the program to produce an unexpected result.
◼◼ A syntax error occurs when part of the code breaks the rules of the
programming language.
◼◼ A runtime error occurs while the program is running and it is asked to
do something that is impossible to do.
◼◼ Trace tables can be used to manually trace the execution of an
algorithm, allowing you to track the changes in variable values.
◼◼ Before creating a program, it is important to produce a test plan that
outlines how the final program will be tested to ensure it meets the
requirements.
◼◼ Evaluating a program involves considering its strengths and weaknesses
and identifying areas for improvement.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 105 18/05/20 11:43 AM
106 UNIT 2 PROGRAMMING UNIT QUESTIONS
UNIT QUESTIONS
CRITICAL THINKING, 1 a Identify the line number(s) that show one example of each of these
SKILLS REASONING
AO2
structural components in the program below: (6)
◼◼ variable initialisation
◼◼ type declaration
◼◼ selection
◼◼ iteration
◼◼ data structure
◼◼ subprogram.
15
16 SET max TO maxCalc(valuesArray)
SEND max TO DISPLAY
HINT
Question 1 is testing your ability to identify the seven key structural
components of a program. Make sure you have identified the line numbers
in which the components can be found.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 106 20/05/20 3:18 PM
UNIT 2 PROGRAMMING UNIT QUESTIONS 107
CRITICAL THINKING, 3 Draw and complete a trace table for this algorithm with these column
SKILLS PROBLEM SOLVING,
AO2
headings: (5)
REASONING
◼◼ length
◼◼ count
◼◼ index
◼◼ scores[index].
HINT
Question 3 tests your ability to trace an algorithm using a trace table.
Remember each variable change should be recorded and each time a line of
code alters the value of a variable or variables a new row of the trace table
should be completed.
CRITICAL THINKING, 4 Open file Q01a. Answer these questions about the code.
SKILLS REASONING
AO2
a State the name of a user-defined subprogram. (1)
b State the name of one in-built subprogram. (1)
c State the names of one input parameter. (1)
d State the name of a global variable. (1)
e State the name of a local variable. (1)
f State the line number of the command that ‘calls’ the variable. (1)
HINT
These questions are asking you to ‘state’ various elements in the program.
You do not have to describe them or explain how they function.
CRITICAL THINKING, AO2 5 Open file Q02a. Answer these questions about the code.
SKILLS PROBLEM SOLVING,
REASONING AO3 A data structure has been used to store the results of a survey to find
Sample material. Not for resale, circulation or distribution in whole or in part. © Pearson 2020.
HINT
This question is asking you to traverse a list to find a particular item. When
you print out the result text and variables have to be concatenated.
HINT
The question requires you to use a loop and selection.
M02 IGCSE Computer Science SB2 Global 10220 UNIT2.indd 107 18/05/20 11:43 AM