AQA GCSE Computer Science [2 ed.] 1510484302, 9781510484306

Updated specification; first teaching September 2020. Specification code: 8525 Written by leading Computer Science teac

347 93 20MB

English Pages 264 [267] Year 2020

Report DMCA / Copyright

DOWNLOAD PDF FILE

Table of contents :
Cover
Book title
Copyright
Contents
How to use this book
1 FUNDAMENTALS OF ALGORITHMS
1.1 Representing algorithms
1.2 Efficiency of simple algorithms
1.3 Sorting and searching algorithms
2 PROGRAMMING
2.1 Data types
2.2 Programming concepts
2.3 Arithmetic operations
2.4 Relational operations
2.5 Boolean operations
2.6 Data structures
2.7 Input and output
2.8 String-handling operations
2.9 Random number generation
2.10 Structured programming and subroutines
2.11 Robust and secure programming
3 FUNDAMENTALS OF DATA REPRESENTATION
3.1 Number bases
3.2 Converting between number bases
3.3 Units of information
3.4 Binary arithmetic
3.5 Character encoding
3.6 Representing images
3.7 Representing sound
3.8 Data compression
4 COMPUTER SYSTEMS
4.1 Hardware and software
4.2 Boolean logic
4.3 Software classification
4.4 Classification of programming languages and translators
4.5 Systems architecture
5 FUNDAMENTALS OF COMPUTER NETWORKS
5.1 Computer networks
6 CYBER SECURITY
6.1 Fundamentals of cyber security
6.2 Cyber security threats
6.3 Methods to detect and prevent cyber security threats
7 RELATIONAL DATABASES AND STRUCTURED QUERY LANGUAGE (SQL)
7.1 Relational databases
7.2 Structured Query Language (SQL)
8 ETHICAL, LEGAL AND ENVIRONMENTAL IMPACTS OF DIGITAL TECHNOLOGY ON WIDER SOCIETY
8.1 Ethical, legal and environmental impacts and risks of digital technology
GLOSSARY
A
B
C
D
E
F
H
I
L
M
N
O
P
R
S
T
U
V
W
X
KNOWLEDGE CHECK ANSWERS
QUESTION PRACTICE ANSWERS
INDEX
A
B
C
D
E
F
G
H
I
K
L
M
N
O
P
Q
R
S
T
U
V
W
X
ACKNOWLEDGEMENTS
Recommend Papers

AQA GCSE Computer Science [2 ed.]
 1510484302, 9781510484306

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
File loading please wait...
Citation preview

AQA GCSE (9–1) Computer Science is available as a Whiteboard eTextbook and Student eTextbook. Whiteboard eTextbooks are online interactive versions of the printed textbook that enable teachers to: ●● Display interactive pages to their class ●● Add notes and highlight areas ●● Add double page spreads into lesson plans Student eTextbooks are downloadable versions of the printed textbooks that teachers can assign to students. Students can: ●● Download and view them on any device or browser ●● Add, edit and synchronise notes across two devices ●● Access their personal copy on the move Find out more and sign up for a free trial – visit: www.hoddereducation.co.uk/dynamiclearning

FOR THE

8525 SPECIFICATION

AQA GCSE (9–1)

Computer Science Second Edition George Rouse Lorne Pearcey Gavin Craddock

9781510484306_AQA_GCSE_Computer_Science_FM.indd 1

19/08/20 10:56 PM

Although every effort has been made to ensure that website addresses are correct at time of going to press, Hodder Education cannot be held responsible for the content of any website mentioned in this book. It is sometimes possible to find a relocated web page by typing in the address of the home page for a website in the URL window of your browser. Hachette UK’s policy is to use papers that are natural, renewable and recyclable products and made from wood grown in well-managed forests and other controlled sources. The logging and manufacturing processes are expected to conform to the environmental regulations of the country of origin. Orders: please contact Bookpoint Ltd, 130 Park Drive, Milton Park, Abingdon, Oxon OX14 4SE. Telephone: +44 (0)1235 827827. Fax: +44 (0)1235 400401. Email [email protected] Lines are open from 9 a.m. to 5 p.m., Monday to Saturday, with a 24-hour message answering service. You can also order through our website: www.hoddereducation.co.uk ISBN: 978 1 5104 8430 6 © George Rouse, Lorne Pearcey and Gavin Craddock 2020 First published in 2020 by Hodder Education, An Hachette UK Company Carmelite House 50 Victoria Embankment London EC4Y 0DZ www.hoddereducation.co.uk Impression number 10 9 8 7 6 5 4 3 2 1 Year 2024 2023 2022 2021 2020 All rights reserved. Apart from any use permitted under UK copyright law, no part of this publication may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying and recording, or held within any information storage and retrieval system, without permission in writing from the publisher or under licence from the Copyright Licensing Agency Limited. Further details of such licences (for reprographic reproduction) may be obtained from the Copyright Licensing Agency Limited, www.cla.co.uk Cover illustration © By ToheyVector – stock.adobe.com Illustrations by Integra Software Services Pvt. Ltd., Pondicherry, India. Typeset in Integra Software Services Pvt. Ltd., Pondicherry, India. Printed in Italy A catalogue record for this title is available from the British Library.

9781510484306.indb 2

19/08/20 8:31 PM

CONTENTS How to use this book

1 FUNDAMENTALS OF ALGORITHMS 1.1 Representing algorithms 1.2 Efficiency of simple algorithms 1.3 Sorting and searching algorithms

2 PROGRAMMING

1 1 8 9 25

2.1 Data types 2.2 Programming concepts 2.3 Arithmetic operations 2.4 Relational operations 2.5 Boolean operations 2.6 Data structures 2.7 Input and output 2.8 String-handling operations 2.9 Random number generation 2.10 Structured programming and subroutines 2.11 Robust and secure programming

3 FUNDAMENTALS OF DATA REPRESENTATION 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8

Number bases Converting between number bases Units of information Binary arithmetic Character encoding Representing images Representing sound Data compression

4 COMPUTER SYSTEMS 4.1 4.2 4.3 4.4 4.5

9781510484306.indb 3

v

Hardware and software Boolean logic Software classification Classification of programming languages and translators Systems architecture

26 28 37 38 40 42 46 46 49 50 55 80 81 83 90 91 95 97 100 103 123 124 124 134 138 143

iii

19/08/20 8:31 PM

5 FUNDAMENTALS OF COMPUTER NETWORKS 5.1 Computer networks

6 CYBER SECURITY 6.1 Fundamentals of cyber security 6.2 Cyber security threats 6.3 Methods to detect and prevent cyber security threats

7 RELATIONAL DATABASES AND STRUCTURED QUERY LANGUAGE (SQL) 7.1 Relational databases 7.2 Structured Query Language (SQL)

8 ETHICAL, LEGAL AND ENVIRONMENTAL IMPACTS OF DIGITAL TECHNOLOGY ON WIDER SOCIETY 8.1 Ethical, legal and environmental impacts and risks of digital technology

169 169 188 188 188 194 200 200 203 211 211

GLOSSARY

221

KNOWLEDGE CHECK ANSWERS

226

QUESTION PRACTICE ANSWERS

234

INDEX

252

ACKNOWLEDGEMENTS

257

iv

9781510484306.indb 4

19/08/20 8:31 PM

HOW TO USE THIS BOOK To help you get the most out of it, this textbook uses the following learning features:

Important words Highlighted in green, these are terms that you will be expected to know and understand in your exams.

Important words You will need to know and understand the following terms: algorithm decomposition abstraction

Tech terms Jargon or technical definitions in blue that you may find useful.

Tech terms Inverter An alternative name for a NOT gate, because the output inverts the input.

Key point An important idea or concept.

Key point A computer program is an implementation of an algorithm – an algorithm is not a computer program!

Worked examples Used to illustrate an idea or a concept, these will guide you through the reasoning behind each step of a calculation or process.

Worked example FOR a ← 1 to 4 FOR b ← 1 to 3 OUTPUT a * b ENDFOR ENDFOR

v

9781510484306.indb 5

19/08/20 8:31 PM

Beyond the spec Information that you will not be expected to know or state in an exam but will aid understanding or add some useful context..

Beyond the spec Computer Scientists use ‘Big O notation’ to measure mathematically how efficient algorithms are. Big O attempts to measure the change in efficiency as the size of the data input increases. This is covered fully in the A-level Computer Science specification.

Knowledge check Quick check-ins that help you to recap and consolidate your understanding of the previous section.

Knowledge check 1 Define the following terms:

(a) Decomposition (b) Abstraction 2 A programmer is creating software to send and receive encrypted messages via email. Describe how decomposition can be used to allow this problem to be solved.

Recap and review A targeted summary of everything you have learned in the chapter. Use this to help you recap as you work through your course.

Question practice More formal questions to help you to prepare for both examination papers.

Answers Answers to all of the Knowledge check and Question practice questions are at the back of the book and also at www.hoddereducation.co.uk/ AQAGCSEComputerScience.

vi

9781510484306.indb 6

19/08/20 8:31 PM

1 FUNDAMENTALS OF ALGORITHMS

CHAPTER INTRODUCTION In this chapter you will learn about: 1.1 Representing algorithms ➤ Understand and explain the term algorithm ➤ Understand and explain the terms decomposition and abstraction ➤ Explain algorithms in terms of their inputs, outputs and processing ➤ Use a systematic approach to problem solving including pseudo-code, program code and flowcharts ➤ Determine the purpose of simple algorithms using trace tables and visual inspection 1.2 Efficiency of simple algorithms ➤ Understand that more than one algorithm can be used to solve the same problem ➤ Compare the efficiency of algorithms 1.3 Sorting and searching algorithms ➤ Understand and explain how linear search and binary search algorithms work ➤ Understand and explain how merge sort and bubble sort algorithms work

9781510484306.indb 1

1.1 Representing algorithms Computers are simply electronic machines that carry out instructions given by human programmers; although a computer can solve many complex problems, it can only do so if it is given instructions to tell it how to do so. Writing these instructions in a form that is suitable for a computer to carry out can be a challenging task! An algorithm is a step-by-step sequence of instructions that are used to solve a problem or complete a task. Each instruction in an algorithm must be precise enough to be understood independently. An algorithm must also clearly show the order in which instructions are carried out and where decisions are made or sections repeated.

Key point A computer program is an implementation of an algorithm – an algorithm is not a computer program!

1

19/08/20 8:31 PM

1  Fundamentals of algorithms

Decomposition and abstraction In order to define algorithms effectively, decomposition and abstraction are often used. ● Decomposition is breaking a problem down into smaller sub-problems that each accomplish an identifiable task, which might itself be further subdivided. ● Abstraction is removing or hiding unnecessary details from a problem so that the important details can be focused on or more easily understood. For example, imagine a programmer wishes to create a system to sell T-shirts. This could be a relatively large problem. Where would they start? By using decomposition and abstraction, the programmer can begin to work out how to tackle the problem. Decomposition

Abstraction

How can the T-shirt sales system be split up?

What can we focus on and what can we ignore?

It perhaps involves: ● A login system for users ● A search function to find particular T-shirt ● A system to allow users to buy a T-shirt. ● A reordering system

Let’s consider the login and search functions: ● The login system could focus on a customer’s email address and password but ignore everything else. ● The search function could focus only on certain T-shirt details (for example colour, size, material, price, how many in stock).

A particularly powerful example of abstraction is Harry Beck’s well-known London underground map. The map focuses on the connections between stations and how lines intersect. It is a useful tool for anyone who wants to plan a journey in London. However, it ignores details such as tunnels, distances between stations and which streets pass overhead. These details are not important for underground travellers and would make the map more confusing if included. To see Harry Beck's original design, go to the Transport for London website, at https://tfl.gov.uk/corporate/about-tfl/culture-and-heritage/art-and-design/harrybecks-tube-map.

Figure 1.1 A modern interpretation of a transport system map 2

9781510484306.indb 2

19/08/20 8:31 PM

AQA GCSE Computer Science

Knowledge check 1 Define the following terms:

(a) Decomposition (b) Abstraction 2 A programmer is creating software to send and receive encrypted messages via email. Describe how decomposition can be used to allow this problem to be solved. 3 A chess club develops a system to store details about games played. For each game, the winner's and loser’s names are stored alongside the date that the game was played. Explain how abstraction has been used in the development of this system.

Explain simple algorithms in terms of their inputs, processing and outputs An algorithm can be represented by the diagram below: Input

Process

Output

Figure 1.2 Input–Process–Output

Input refers to data that is given to the algorithm by the user. This may be typed in via the keyboard, entered with another input device such as a microphone or read in from an external data file. Output is the data that is given back to the user by the algorithm. This may be done with a message on the screen, using another output device such as a printer or by writing to an external data file. Processing describes the steps that the algorithm takes in order to solve the problem. This stage involves processing the given input in order to produce the desired output. Going back to the example of the system to sell T-shirts, what are the inputs, outputs and processes for the section of the system that allows the user to search for suitable T-shirts? The inputs include everything that the system requires the user to enter: for example, the size, colour and style of T-shirt that they require. Another input would be an external file containing details of all the T-shirts available. With these inputs, the system will then carry out processes to find T-shirts to match the user’s search criteria, such as only selecting those in the correct size and colour and excluding any that are out of stock. Once this has been completed, a list of matching T-shirts will be produced as an output to the user. Input

Process

Output

Size of T-shirt required Colour of T-shirt required File of all T-shirts available

Search through list Find matching T-shirts Exclude T-shirts out of stock

List of T-shirts that meet customer requirements

Figure 1.3 Example of Input–Process–Output

3

9781510484306.indb 3

19/08/20 8:31 PM

1  Fundamentals of algorithms

Problem solving and algorithm creation Algorithms can be created using flowcharts, pseudo-code or program code.

Flowcharts The inputs, processes and outputs can be put together into an algorithm by using a flowchart. This is a graphical representation of an algorithm and uses symbols to denote each step, with arrows showing how to move between each step. A flowchart may use any of the following symbols: Line

An arrow represents control passing between the connected shapes.

Process

This shape represents something being performed or done.

Subroutine

This shape represents a subroutine call that will relate to a separate, non-linked flowchart.

Input/ output

This shape represents the input or output of something into or out of the flowchart.

Decision

This shape represents a decision (Yes/No or True/False) that results in two lines representing the different possible outcomes.

Terminal

This shape represents the ‘Start’ and ‘End’ of the process.

Figure 1.4 Flow diagram symbols

All flowcharts begin and end with the terminal shape, indicating the start and end of the flowchart. Inputs and outputs are represented by a parallelogram, with decisions using a diamond shape. Decision boxes must have two possible outputs: True/False or Yes/No. All other processes are shown as a rectangle. Where algorithms are decomposed into separate subroutines, a rectangle with two additional vertical lines is used to show a call to a different subroutine. The following flowchart shows part of an algorithm for the T-shirt system that deals with re-ordering T-shirts when stock runs low.

4

9781510484306.indb 4

19/08/20 8:31 PM

AQA GCSE Computer Science Start

Enter ItemCode

Read StockLevel, ReorderLevel from User

Is StockLevel ≤ ReorderLevel?

True

Call Reorder Subroutine

False Output ‘Stock not ordered’

Output ‘Stock ordered’

End

Figure 1.5 Flow diagram for T-shirt reordering system

Pseudo-code Key point In general, pseudo-code is not strictly defined so many variations would be acceptable. For example, the keyword OUTPUT could instead be replaced with PRINT, or even DISPLAY – as long as the steps to be taken are clear, that is sufficient.

Key point Questions in the exam use AQA Pseudo-code to define the algorithm. This has a particular syntax – an AQA Pseudo-code guide is available on the AQA website. All examples in this book will also be written using AQA Pseudo-code.

Alternatively, an algorithm may be represented using pseudo-code. Pseudo-code is a textual, English-like method of describing an algorithm. It is much less strict than high-level programming languages, although it may look a little like a program that could be entered directly into a computer. The same T-shirt reordering system that was described in a flowchart could also be represented in pseudo-code as follows: ItemCode ← USERINPUT StockLevel ← USERINPUT ReorderLevel ← USERINPUT IF StockLevel ≤ ReorderLevel THEN ReOrder() OUTPUT 'Stock ordered' ELSE OUTPUT 'Stock not ordered' ENDIF

5

9781510484306.indb 5

19/08/20 8:31 PM

1  Fundamentals of algorithms

Program code Program code refers to instructions given in a high-level language. For the AQA GCSE Computer Science specification, you must choose to use either Python, VB.Net or C#; each of these languages has a separate examination paper. Where answers are requested as program code, it is important that you are as precise with the syntax as when you are actually coding. Your code answers should work if they were typed into your computer. The following shows the T-shirt ordering algorithm written in each of these high-level languages: Python

ItemCode = input("enter item code") StockLevel = int(input("enter stock level")) ReorderLevel = int(input("enter reorder level")) if StockLevel list[x + 1] THEN  swap list[x], list[x + 1]  ENDIF UNTIL all pairs of values checked UNTIL no swaps made

Key point At GCSE level, you will not be expected to remember the sorting and searching algorithms in pseudo-code, but you are expected to understand how they work.

Merge sort Key point You will be expected to know how to perform a merge sort on a list with an even or odd number of elements. With an odd number of elements there are two choices of where to divide lists – you can choose either but you must apply your choice consistently. Each of the merge stages must resemble the divide stages, just with elements in a different order.

The merge sort algorithm uses a ‘divide and conquer’ approach to split data up into individual lists and then merge them back together in order. The way that the lists are merged back together is key to understanding how this algorithm works. For example, we have a list like this one below and we want to sort it in ascending order (from lowest to highest): 7

2

9

4

3

8

5

1

First, in the ‘divide’ stage the list of values is split into two separate sublists. Each sublist is repeatedly split in half until we have individual lists of size 1 each. 7

2

9

4

3

8

5

1

Then each pair of lists are merged together into new lists in the ‘conquer’ stage. Where there is an uneven number of lists, the odd list will simply remain unmerged until the next step in the process. When two lists are merged together, the first two numbers in each of the lists are compared and whichever should be first is taken to be first in the new list. This process is repeated until all numbers have been inserted into the new list. 3

8

5

1

  

4

  

9

  

2

  

7 2

4

3

1

7

9

8

5

Here, 7 and 2 are compared, with 2 being inserted into a new list before 7. Similarly, 4 is inserted before 9 in the next merged list. This continues for the other pairs of lists, merging them together into four new lists. The merging process is repeated again to merge pairs of lists together. This time the first list is made of 2 and 7, and the second list is made of 4 and 9. The algorithm compares the first numbers in each list, 2 and 4, to decide which value will be first in the new list. 2 is inserted into the new list. Next, 7 and 4 are then compared, with 4 being inserted. Then, 7 and 9 are compared, with 7 being inserted before 9 into the first new list. The same process is then repeated for the lists made of 3 and 8, and 1 and 5, leaving two new lists in order, each made of four numbers.

9781510484306.indb 11

11

19/08/20 8:31 PM

1  Fundamentals of algorithms 7

4

9

3

2

4

7

8

1

5

  

  

2

9

1

3

5

8

The merging process is again repeated with the final two lists. The first numbers in each list (2 and 1) are compared to decide which value will be first in the merged list, with 1 being inserted. 2 is then compared against 3, with 2 being inserted into the new list next. This continues until all numbers have been merged from the two lists into the final list. This final list is now in order. 2

4

7

9

1

3

5

8

  1

2

3

4

5

7

8

9

Key point At any point in the merging stage of this algorithm, each merged list is always in order. This means that it is only the first numbers from each list that need to be considered when deciding on how to merge them.

We can write out the merge sort algorithm in very informal pseudo-code as follows: REPEAT

Divide each list in half UNTIL each list is of size 1

When all numbers are split up into separate lists, the merge stage can begin. This uses the following steps in very informal pseudo-code: REPEAT

REPEAT REPEAT Compare the first value in both lists Insert larger of two values into new merged list Remove value from old list UNTIL all numbers in pairs of lists are merged UNTIL each pair of lists have been considered UNTIL all lists are merged

If at any stage an odd number of lists are present, the odd list can simply be ignored until the next iteration.

Comparison of sorting algorithms

12

9781510484306.indb 12

Both of the above algorithms will result in a sorted list, but they do it in very different ways. As previously discussed, an algorithm's efficiency depends on the number of steps it takes to execute – the more steps, the lower the efficiency. A bubble sort is generally thought of as a simple but slow algorithm – as the size of the list of values increases, it slows down significantly because it requires multiple passes over the same data. A merge sort is much more efficient, especially with large lists of values.

19/08/20 8:31 PM

AQA GCSE Computer Science

Knowledge check 5 Explain how a bubble sort would sort the values [6, 9, 2, 5, 8] into order. 6 A merge sort is an example of a divide and conquer algorithm. State what happens during the divide stage.

Searching algorithms A searching algorithm is used to find an item of data in a list, or to confirm that it is not in the list. The simplest searching algorithm is a linear search.

Linear search A linear search is carried out by inspecting each item of the list in turn to check if it is the desired value. If it is, we have found the item; if it is not, the next item in the list must be checked. If the algorithm gets to the end of the list without finding the item, then it is not in the list. 7

2

9

4

3

To find the value 9 in this list, the algorithm would first check 7 and then check 2 before finally finding 9. To find the value 8, the algorithm would check every item in the list (7, 2, 9, 4 and 3). Only after checking the last value can we can be sure that 8 is not in the list. A linear search is simple but inefficient. If we have a list of a million values, the algorithm would have to check all one million of them before being sure that that a particular value was not in the list. We can write out the linear search algorithm in very informal pseudo-code as follows: REPEAT

Check one value (from the start) IF value matches what is being searched for THEN Output value ELSE Move to next value ENDIF UNTIL number is found OR end of list is reached

Binary search A much more efficient algorithm to find values in a list is a binary search. However, this algorithm has the pre-requisite that the list it searches must be in order. A binary search on an unsorted list will not work. The binary search algorithm picks the middle value in the sorted list. ‘Middle’ means there are equal numbers of values either side of it. If there are an even number of values in the list then there isn’t an exact middle value – however, generally the value to the left of the middle is chosen. (Either side can be picked as long as we are consistent.) 13

9781510484306.indb 13

19/08/20 8:31 PM

1  Fundamentals of algorithms If the middle value is the one that we are searching for then the algorithm finishes. However, if not, then the algorithm can discard half of the list because the value we are looking for cannot be in it. It can discard the lower half of the list if the middle value is smaller than the one we are searching for (as all of the values in the lower half will be smaller than the middle value); or it can discard the upper half of the list if the middle number is larger than the one we are searching for (as all of the values in the upper half will be larger than the middle value). Either way, we always also discard the middle value. If we get to a situation where the list only has one item and it is not the one that we are searching for, then the value is not in the list.

Worked example The list below is in alphabetical order and so can be used in a binary search. We will look for the value Q in this list. A

C

D

F

H

K

P

Q

S

T

V

W

Z

We first take the middle value P. This is not the value that we are looking for and is smaller than Q alphabetically, so we can discard the lower half of the list, up to and including P. Q

S

T

V

W

Z

We now have a list of six values. As there is no middle value, we pick the value to the left of the middle, which is T. This is the not the value that we are looking and T is larger than Q alphabetically, so the upper half of the list (including T) can be discarded. Q

S

We now have a list of two values. Again, there is no middle value so we pick the value to the left of the middle which is Q. This is the value that we are searching for and so the algorithm stops. We can write out the binary search algorithm in very informal pseudo-code as follows: REPEAT

ick the middle value in a list (if even number of P values, pick left-of-middle value) ­ IF value matches what is being searched for THEN Output value ELSE IF value searched for > middle value THEN Discard middle value AND lower half of list ELSE IF value searched for < middle value THEN Discard middle value AND upper half of list ENDIF UNTIL (value found) or (list is of size 1 and value is not found)

14

9781510484306.indb 14

19/08/20 8:31 PM

AQA GCSE Computer Science

Comparison of searching algorithms A linear search and a binary search will both find a value in a list, but will do so in very different ways. As previously discussed, an algorithm's efficiency depends on the number of steps it takes to execute – the more steps, the lower the efficiency. A linear search will work with any list of values, but may be very slow as it checks every value in the list. A binary search will be much more efficient, but requires the list to be sorted into order. A binary search halves the size of the list to be searched on every comparison. Imagine searching for a value in a list of one million numbers sorted in order. In the worst-case scenario, a linear search will need to compare against each and every one of these million numbers. A binary search, however, needs only to make a maximum of 21 comparisons before it has completed its search. This is because the number of values in the list halves on every comparison. So, by the second comparison the number has halved from one million to 500 000. After three comparisons it has halved again to 250 000. After 21 comparisons the original list has been reduced to a single number. This means we can be sure that if a binary search of a million items cannot find the value being searched for in 21 comparisons, then the number is not in the list.

Knowledge check 7 Explain how a linear search would find the value 18 in the list [1, 8, 6, 2, 18, 14, 7]. 8 Which value would be the first to be compared in a binary search through the list [A, B, C, D, E]?

9 How does a linear search determine that a value does not appear in a list?

15

9781510484306.indb 15

19/08/20 8:31 PM

RECAP AND REVIEW 1 FUNDAMENTALS OF ALGORITHMS Important words You will need to know and understand the following terms: algorithm decomposition abstraction input process output flowchart pseudo-code program code trace table efficiency sorting algorithm bubble sort merge sort searching algorithm linear search binary search

1.1 Representing algorithms Decomposition and abstraction

An algorithm is a step-by-step sequence of instructions that are used to solve a problem. Each instruction in an algorithm must be precise enough to be understood independently. ■ An algorithm must also clearly show the order that each instruction is carried out in. ■

Decomposition breaks a problem into smaller sub-problems that can each be tackled individually. Each stage can be further decomposed if needed. Abstraction means focusing on what is important in a problem and ignoring or hiding the irrelevant details.

Explain simple algorithms in terms of their inputs, processing and outputs An algorithm: ■ accepts inputs from a user (or from sensors or data files) ■ processes this data, and then ■ outputs the result back to the user in some format. Identifying the inputs and the required outputs for a system enable us to decide how to map between the two. Programmers write code that processes the inputs in order to provide the required outputs. Input

Process

Output

Problem solving and algorithm creation

Algorithms can be created using flowcharts, pseudo-code or program code.

Flowcharts A flowchart is a graphical representation of an algorithm. It can be followed from top to bottom, making decisions as appropriate. Decisions are represented by diamond shapes and must have two output lines corresponding to Yes/No or True/False. ■ Inputs and outputs are represented by parallelograms. ■

16

9781510484306.indb 16

19/08/20 8:31 PM

AQA GCSE Computer Science

Processes are represented by rectangles. ■ Start/Stop instructions are represented by rounded rectangles. ■ Each flowchart must begin and end with a Start and Stop instruction. ■

Line

An arrow represents control passing between the connected shapes.

Process

This shape represents something being performed or done.

Subroutine

This shape represents a subroutine call that will relate to a separate, non-linked flowchart.

Input/ output

This shape represents the input or output of something into or out of the flowchart.

Decision

This shape represents a decision (Yes/No or True/False) that results in two lines representing the different possible outcomes.

Terminal

This shape represents the ‘Start’ and ‘End’ of the process.

As an example, the algorithm in the figure below will decide whether a positive number entered is odd or even using repeated subtraction. Start

Enter Number

Is Number = 0?

TRUE

Output ‘Even’

FALSE

Is Number = 1?

TRUE

Output ‘Odd’

FALSE Number = Number − 2

End

17

9781510484306.indb 17

19/08/20 8:31 PM

1  Fundamentals of algorithms

Pseudo-code Pseudo-code is a textual representation of an algorithm. ■ Pseudo-code enables programmers to communicate algorithms to other programmers, showing the steps used without worrying about which language they are using. The pseudo-code algorithm below carries out the same algorithm as the flowchart shown previously – finding whether a positive number is odd or even through repeated subtraction. ■

Number ← USERINPUT WHILE Number ≥ 0

IF Number = 1 THEN OUTPUT 'odd'

ELSE IF Number = 0 OUTPUT 'even'

END IF

Number ← Number – 2

ENDWHILE

Program code Program code is code that is written in a high-level language. As you are studying AQA’s GCSE Computer Science specification, this will be either Python, VB.net or C#. Program code in answers must be precise.

Determine the purpose of simple algorithms Trace tables

Very simple algorithms can be visually inspected to check their purpose. ■ Trace tables are used to follow each line of a more complex algorithm from start to finish. At each point, the value of each variable and any outputs are recorded. A table such as the one shown below is used. More columns are added if more variables are used. ■

Line

Variable1

Variable2

Variable3

Output

Comments

If the program repeats certain lines, this is reflected in the trace table. Each row shows one line that is executed and lines of code can be repeated as many times as required. The completed trace table below shows the previous algorithm running to check whether 5 is an odd or even number.

18

9781510484306.indb 18

19/08/20 8:31 PM

AQA GCSE Computer Science

Line 01: number ← USERINPUT 02: WHILE number ≥ 0 03: IF number = 1 05: ELSE IF number = 0 07: ENDIF 08: number ← number - 2 09 ENDWHILE 02: WHILE number ≥ 0 03: IF number = 1 05: ELSE IF number = 0 07: ENDIF 08: number ← number - 2 09 ENDWHILE 02: WHILE number ≥ 0 03: IF number = 1 04: OUTPUT 'odd' 07: ENDIF 08: number ← number - 2 09 ENDWHILE 02: WHILE number ≥ 0

Number 5 5 5 5 5 3 3 3 3 3 3 1 1 1 1 1 1 -1 -1 -1

Output

'odd'

Comments Number inputted by user Number is ≥ 0, continue Number is not equal to 1 Number is not equal to 0 End of IF statement 2 subtracted from number End of loop, repeat again Number is ≥ 0, continue Number is not equal to 1 Number is not equal to 0 End of IF statement 2 subtracted from number End of loop, repeat again Number is ≥ 0, continue Number does equal 1 'odd' printed End of IF statement 2 subtracted from number End of loop, repeat again Number is NOT ≥ 0, WHILE loop and program ends.

1.2 Efficiency of simple algorithms An algorithm’s efficiency depends on the time it takes to execute. ■ As computers vary in speed, the number of steps taken is counted as an estimate of this. ■ The more steps a computer takes to complete a process, the lower the efficiency of the algorithm. ■

1.3 Sorting and searching algorithms Sorting algorithms Bubble sort

The bubble sort algorithm uses the following steps in very informal pseudo-code:

19

9781510484306.indb 19

19/08/20 8:31 PM

1  Fundamentals of algorithms

REPEAT

REPEAT for each pair of numbers in the list # where list[x] is 1st item in a pair

# and where list[x + 1] is 2nd item in a pair

IF list[x] > list[x + 1] THEN

swap list[x], list[x + 1]

ENDIF

UNTIL all pairs of values checked

UNTIL no swaps made

Bubble sort is a relatively simple algorithm. However, it is quite inefficient and may take much longer to complete than other sorting algorithms on very large lists.

Merge sort The merge sort is a divide and conquer algorithm. The divide stage uses the following steps in very informal pseudo-code: REPEAT

Divide each list in half

UNTIL each list is of size 1

When all numbers are split up into separate lists, the merge stage can begin. This uses the following steps in very informal pseudo-code: REPEAT

REPEAT

REPEAT

Compare the first value in both lists

Insert larger of two values into new merged list Remove value from old list

UNTIL all numbers in pairs of lists are merged

UNTIL each pair of lists have been considered

UNTIL all lists are merged

If at any stage an odd number of lists are present, then one list can simply be ignored until the next iteration. ● The merge sort is much more efficient than the bubble sort. ● It will sort a large list of random values into order in a quicker time than a bubble sort.

20

9781510484306.indb 20

19/08/20 8:31 PM

AQA GCSE Computer Science

Searching algorithms Linear search A linear search uses the following steps: REPEAT

Check one value (from the start)

IF value matches what is being searched for THEN Output value

ELSE

Move to next value

ENDIF

UNTIL number is found OR end of list is reached

The linear search is relatively inefficient, but it works on any list, regardless of whether it is in any particular order. Every single value in the list needs to be checked before you can be certain that a value is not present in a list.

Binary search A binary search requires the list of values to be in order. It uses the following steps: REPEAT

Pick the middle value in a list (if even number of values, pick left of-middle value)

IF value matches what is being searched for THEN  Output value 

ELSE IF value searched for > middle value THEN

Discard middle value AND lower half of list

ELSE IF value searched for < middle value THEN

Discard middle value AND upper half of list

ENDIF

UNTIL (value found) or (list is of size 1 and value is not found)

A binary search is highly efficient. If an ordered list of one million numbers is used, the binary search could find a number in the list with no more than 21 comparisons. The linear search by contrast could take up to one million comparisons. ■ However, the binary search will only work if the list of values is ordered. Therefore, it cannot always be used. ■

21

9781510484306.indb 21

19/08/20 8:31 PM

QUESTION PRACTICE 1 Fundamentals of algorithms 01 State two computational thinking principles and describe how they could be used when developing a computerised solution to a problem. [6 marks] 02 Draw a flowchart to describe a solution to the following problem. A menu offers four options: • A Add a name • B Delete a name • C Change a name • D End

The program should ask for an input repeatedly until option D is selected, at which point it ends.



If option A, B or C is selected, the program should pass control to a procedure depending on which option is selected: • A: Add • B: Delete • C: Change

[10 marks]

03 An amateur football team wants a computer program to calculate the points scored. The user inputs: • the number of games won • the number of games drawn.

There are 3 points for a win, 1 for a draw and 0 for a loss.



The program should prompt the user for the inputs and output a suitable message with the points total.



Using AQA pseudo-code or a high-level language that you have learned, write a program to input the data above and output the total points scored. [6 marks]

22

9781510484306.indb 22

19/08/20 8:31 PM

AQA GCSE Computer Science 04 Here is an algorithm that is intended to collect and store the names of people going into an event. Only 15 people are allowed to enter the event. number WHILE number < 15 name[1] ← USERINPUT number ← number + 1 ENDWHILE OUTPUT 'The total number of names entered is' OUTPUT number

04.1 Identify the mistakes in this algorithm.

[2 marks]

04.2 Rewrite the algorithm so that it does what is intended.

[2 marks]

04.3 Add to the algorithm so that it outputs all the names entered.

[4 marks]

05 Complete the trace table for the following program:

[6 marks]

x ← 0 y ← 0 WHILE y < 6 y ← y + 1 x ← x + y ENDWHILE OUTPUT x

x

y

output

06 Show the stages of a bubble sort when applied to the following data: Elephant, Dog, Cat, Dolphin, Sheep, Frog

[4 marks]

23

9781510484306.indb 23

19/08/20 8:31 PM

1  Fundamentals of algorithms 07 Show the stages of a bubble sort on the following data: Pear, Apple, Grape, Banana, Strawberry, Raspberry

[5 marks]

08 For the following data: Pizza, Apple, Banana, Chips, Sandwich, Crisps, Egg, Pasty 08.1 Show the stages of a merge sort on the data.

[4 marks]

08.2 Outline the advantage of a merge sort over a bubble sort.

[2 marks]

09 For the following list: Jeremy, Adrian, Ben, Harry, Frank, James 09.1 Show the stages of a linear search for Harry in the list. 09.2 Explain why a binary search could not be used with this list to find Harry.

[4 marks] [1 mark]

10 The following shows airline departures from an airport. 10.1 Show the stages of a binary search for HA102 in the list:

AD245, BE767, FR226, HA102, HC224, JA233, KE124, MA267, PE334

[3 marks]

10.2 State the number of comparisons needed to find MA267 using a binary search.

[1 mark]

10.3 State the number of comparisons needed to find MA267 using a linear search.

[1 mark]

24

9781510484306.indb 24

19/08/20 8:31 PM

2 PROGRAMMING

CHAPTER INTRODUCTION In this chapter you will learn about: 2.1 Data types ➤ Understand the concept of a data type ➤ Understand the use of integer, real, Boolean, character and string data types 2.2 Programming concepts ➤ Use and understand variables, constants and assignments ➤ Use meaningful identifier names and understand why it is important to use them ➤ Understand the three combining principles of sequence, selection/choice and iteration/repetition ➤ Use definite (count-controlled) and indefinite (condition-controlled) iteration ➤ Use nested selection and iteration structures 2.3 Arithmetic operations in a programming language ➤ Be familiar with and use addition, subtraction, multiplication and division (real and integer division, including remainders)

2.4 Relational operations in a programming language ➤ Be familiar with and use equal to, not equal to, less than, greater than, less than or equal to, and greater than or equal to 2.5 Boolean operations in a programming language ➤ Be familiar with and be able to use NOT, AND, OR 2.6 Data structures ➤ Understand the concept of data structures ➤ Use one and two-dimensional arrays (or equivalent) in the design of solutions to simple problems ➤ Use records (or equivalent) in the design of solutions to simple problems 2.7 Input/output ➤ Be able to obtain user input from the keyboard ➤ Be able to output data and information from a program to the computer display 2.8 String-handling operations in a programming language ➤ Understand and be able to use standard stringhandling operations such as length, position, substring, concatenation and type conversion 25

9781510484306.indb 25

19/08/20 8:31 PM

2  Programming 2.9 Random number generation in a programming language ➤ Be able to use random number generation within a computer program 2.10 Structured programming and subroutines (procedures and functions) ➤ Understand the concept and advantages of subroutines ➤ Describe how parameters are used to pass data within programs ➤ Use subroutines that return values to the calling routine

➤ Understand and use local variables ➤ Describe and explain the advantage of a structured

approach to programming 2.11 Robust and secure programming ➤ Understand simple data validation and authentication routines ➤ Test algorithms and programs, correcting errors ➤ Understand and justify the choice of test data, including normal, boundary and erroneous data

Key point Paper 1 requires significant knowledge and understanding of programming. It is a requirement of the AQA GCSE Computer Science course that you are able to program in one of the specified high-level languages (Python, VB.Net or C#). Assessment of programming skills will only be made through this written examination. ➤ Understand syntax and logic errors Some questions in the examination will be presented in AQA Pseudo-code. Full details of this are ➤ Identify categorise errorsquestions within algorithms and programs given on theand AQA website. Other will be presented in Python, VB.Net or C#, depending upon the option chosen by your teacher; AQA provide a separate examination paper for each of these languages. Examples in the main text are given in AQA Pseudo-code. Where possible, all worked examples given in this chapter are written in AQA Pseudo-code, Python, VB.Net and C#. Please ensure that you are aware which of these you are studying. Please refer to www.aqa.org.uk for full details of the assessment.

2.1 Data types Computer programs store data in memory. However, the type of data to be stored determines how much memory needs to be allocated for that value. There are five main data types that GCSE Computer Scientists need to be aware of.

Integer Integers are whole numbers, positive or negative, that have no decimal or fractional part. Integers are used for counting or storing quantities. For example: score ← 25 highScore ← 100 numOfAttempts ← 0

All variables used in this example are integers.

26

9781510484306.indb 26

19/08/20 8:31 PM

AQA GCSE Computer Science

Tech term Floating point numbers Another name for real numbers – the floating point refers to the position of the decimal point, which can be different (or ‘float’) for different numbers.

Real The real data type is used for numbers, positive or negative, that have (or may have) a decimal or fractional part. Real numbers are sometimes called float or floating point numbers. For example: price ← 19.99 fastestTime ← 9.983 score ← 17.0

All variables used in this example are real numbers.

Boolean Boolean variables only ever store True or False values. They are used to indicate the result of a condition. For example: sorted ← False LoggedIn ← True

All variables used in this example are Boolean values.

Character A character is a single item from the character set used on the computer, such as H, r, 7 or &. Uppercase and lowercase are different characters and space is also a character. When assigning a character to a variable, quotation marks are required to indicate that the value to be assigned is a character. For example: a b c d

← ← ← ←

't' '4' '%' ''

All variables used in this example are characters.

String A string data type stores a collection of characters and is typically used for names, addresses or other textual information. Note that numbers and symbols can also be characters and so can be included in a string. Just like characters, when assigning a string to a variable, quotation marks are required: a b c d

← ← ← ←

'the colour blue' '47 times' '95% increase' 'p@55w0rd'

All variables used in this example are strings.

27

9781510484306.indb 27

19/08/20 8:31 PM

2  Programming

Key point Strings and characters require quotation marks around the values to be assigned. This is to differentiate them from variables. Compare the following lines of code: colour ← 'blue' colour ← blue

The first line assigns the string value of 'blue' to the variable colour. However, the second line treats both colour and blue as variables and assigns the contents of variable blue to the variable colour. If the variable blue does not exist, this would cause an error in the program.

Knowledge check 1 State whether the following data are real numbers, integers, characters, Boolean or strings: (a) 35 (b) & (c) 3 ≠ 2 (d) twenty (e) 35.0 (f) 6.63

2.2 Programming concepts Tech terms Identifier The name of a variable or constant. Reserved keyword A word in a ­programming language that has some special purpose and cannot be used for a variable or constant identifier.

Variables, constants and assignments Variables are used in a computer program to store a single piece of data. For example, you may wish to store someone’s score in a game. As the name suggests, the contents of a variable may be changed (or varied) during the running of a program. When a variable is first defined, the programming language allocates a small area of memory to store this data. A variable has an identifier, or name. This is the label given to the area of memory. Variable identifiers can be almost anything, but they must not contain a space, start with a number or be a reserved keyword (that is, a word that means something else in that programming language). Examples of allowed variable names score max_points item2

Examples of disallowed variable names new score  (contains a space) 2ndName  (starts with number) print  (reserved keyword)

Identifier names should also be meaningful. This means that the purpose of the variable should be obvious to another programmer. For example, although variables are allowed to be called x, temp or abc, the purpose of these are unclear. It would be much better to give a variable an identifier that describes what data is being held, such as userName, totalScore or goalScored. Most programming languages (including Python and C#) are case sensitive; this means that score and Score are treated as different variables Constants are used in computer programs to store a single piece of data that has a fixed value and cannot change during the running of the program. A constant also has an identifier that acts as a label for a memory location that stores the data. 28

9781510484306.indb 28

19/08/20 8:31 PM

AQA GCSE Computer Science

Key point A common mistake is to describe a constant as a variable that doesn’t change – variables and constants are similar, but they are not the same. Would you describe a car as a bike with four wheels?

Assignment means to give a value to a variable or constant. This is done using the ‘←’ sign in AQA Pseudo-code and the ‘=’ symbol in Python, VB.Net and C#. The variable or constant identifier always goes on the left and the value to be assigned goes on the right. A variable can be assigned a value multiple times, but when a new value is assigned the old value is overwritten and lost. A constant can only be assigned a value once, usually at the start of a program. In most high-level languages, variables and constants are declared (defined) at the beginning of the program. (Note, however, that Python does not use declarations.)

Worked example The following program shows a variable and a constant being assigned values, using the AQA Pseudo-code. Note how the contents of the variable score is changed, but the constant maxScore is fixed and cannot change. constant score ← score ← score ←

maxScore ← 100 20 30 score + 10

After this algorithm is run, maxScore has the value 100 and score has the value 40.

Examples in high-level languages – variables Python does not require variables to be declared before they are used. The data type will automatically be chosen by Python based on the data given. score = 20 playerName = "Kirstie"

VB.Net allows the programmer to declare the variable before it is used with the Dim keyword. The data type is declared at this point. However, this declaration is optional. Dim score As Integer = 20 Dim playerName As String = "Kirstie"

C# makes it compulsory to declare a variable before it is used with the int , float , bool, char or string keywords. int score = 20; string playerName = "Kirstie";

Once a variable has been declared, its value can be changed by simply reassigning a new value. It does not need to be declared again. score = 30 score = 30 score = 30;

#Python 'VB.Net //C# 29

9781510484306.indb 29

19/08/20 8:31 PM

2  Programming

Examples in high-level languages – constants Python does not allow the programmer to define constants. By convention, variable names in capitals (such as SCORE) will be treated as constants by other programmers, but there is no restriction on their value being changed. MAXSCORE = 100

#Python

Const maxScore As Integer = 100 const int maxScore = 100;

'VB.Net

//C#

Sequence, selection and iteration The building blocks for any computer program can be reduced down to only three constructs: sequence, selection and iteration.

Sequence Sequence is the execution of statements one after the other, in order. The program runs from top to bottom and each instruction completes fully before the next one is executed. Program A x ← 10 x ← x * 3 x ← x + 1 OUTPUT x

Program B x ← 10 x ← x + 1 OUTPUT x x ← x * 3

Both programs have the same instructions but in a different order. Program A will print out 31 but program B will print out 11. However, in program B the final value of x equals 33 because there is another line of code after the OUTPUT x statement. The sequence of instructions is important and changing this can change how the program works.

Selection Selection is the construct used to make decisions in a program. These decisions are based on Boolean conditions and the program then takes one of two paths based on this condition.

Key point A Boolean condition is a statement that can be evaluated to be either True or False. ‘What do I want for lunch today?’ is not a Boolean condition as the answer could be one of many things, but ‘Do I want pizza for lunch?’ would be a Boolean condition as the answer could only be True (Yes, I want pizza) or False (No, I do not want pizza).

Condition

False

True Code to execute if condition is True

Code to execute if condition is False

Figure 2.1 Selection based on a Boolean condition 30

9781510484306.indb 30

19/08/20 8:31 PM

AQA GCSE Computer Science The most common way of implementing selection is by using IF statements. The IF keyword is used to define the condition to be evaluated, with the code to be executed if true indented between the IF and ENDIF keywords.

Worked example name ← USERINPUT IF name = 'George' THEN OUTPUT 'Hello George' ENDIF

In this example, the condition that is evaluated is whether the inputted name matches the value given (George). If it does, the third line is executed. If not, the program skips over this line entirely. To extend this program to do something else if the condition is false, the ELSE keyword can be used.

Worked example name ← USERINPUT IF name = 'George' THEN OUTPUT 'Hello George' ELSE OUTPUT 'Hello stranger' ENDIF

But what if we want to check for multiple conditions, each with their own associated code to run if true? The ELSE IF keyword allows us to do this.

Worked example name ← USERINPUT IF name = 'George' THEN OUTPUT 'Hello George' ELSE IF name = 'Lorne' THEN OUTPUT 'Great work Lorne' ELSE IF name = 'Kirstie' THEN OUTPUT 'Nice to see you again' ELSE OUTPUT 'Hello stranger' ENDIF

In this example, each possible condition is evaluated in turn. First, the inputted name is checked against ‘George’. If this is true, the message on line 3 is printed. If not, the second possible condition (‘Lorne’) is checked. If not true, the third and final condition (‘Kirstie’) is checked. If none of these is true, the ‘Hello stranger’ message is printed.

31

9781510484306.indb 31

19/08/20 8:31 PM

2  Programming

Examples in high-level languages – IF statements Python uses the if, elif and else keywords. Indentation is used to show which code is inside each block. A double equals sign (==) is used to compare if values are equivalent. #Python name = input("enter a name") if name == "George": print("Hello George") elif name == "Lorne": print("Great work Lorne") elif name == "Kirstie": print("Nice to see you again") else: print("Hello stranger")

VB.Net uses If, ElseIf, Else and End If keywords. Indentation is optional and a single equals (=) is used to compare if values are equivalent. 'VB.Net name = Console.Readline() If name = "George" Then Console.WriteLine("Hello George") ElseIf name = "Lorne" Then Console.WriteLine("Great work Lorne") ElseIf name = "Kirstie" Then Console.WriteLine("Nice to see you again") Else Console.WriteLine("Hello stranger") End If

C# uses if, else if and else keywords. Indentation is optional and a double equals (==) is used to compare if values are equivalent. //C# name = Console.Readline(); if (name == "George") { Console.WriteLine("Hello George"); } else if (name == "Lorne") { Console.WriteLine("Great work Lorne"); } else if (name == "Kirstie") { Console.WriteLine("Nice to see you again"); } else { Console.WriteLine("Hello stranger); }

With the above example, the program will always have one path to follow. It is important to note that the conditions are checked in the sequence given.

32

9781510484306.indb 32

19/08/20 8:31 PM

AQA GCSE Computer Science

Worked example OUTPUT 'Enter a score out of 20' mark ← USERINPUT IF mark > 5 THEN OUTPUT 'Could do better' ELSE IF mark > 10 THEN OUTPUT 'Average mark' ELSE IF mark > 15 THEN OUTPUT 'Excellent' ENDIF

What would happen if someone here got a mark of 19 out of 20? Unfortunately, the message ‘Could do better’ would be displayed as 17 is larger than 5 and so the first condition is true. The other conditions will not be checked. The solution to this problem would be to change the sequence of the conditions so that the highest mark is checked first.

Iteration (definite and indefinite loops) Iteration is the construct used to repeat sections of code. Iteration is commonly called looping.

Tech term Increment  Add a value to; ‘increment by one’ adds 1 to the counter each time the loop repeats.

Key point Iteration can be definite (count-controlled) or indefinite (conditioncontrolled). Definite iteration repeats a set number of times (e.g. ‘repeat this code 5 times’) whereas indefinite iteration repeats based on a Boolean condition.

Definite loops Definite iteration uses the FOR and ENDFOR keywords in AQA Pseudo-code. This uses a variable to act as a counter for the loop. By default, the program will assign this variable a starting value and then automatically increment the variable by one every time the code repeats. When this counter equals the final value, the loop stops. This code and flowchart are logically identical. Both print out the 8 times table from 1 to 10.

Worked example FOR p ← 1 TO 10 OUTPUT p * 8 ENDFOR Start p=1 print (p * 8) p=p+1 Is p = 10?

No

Yes End

Figure 2.2 Flowchart representing this code

Both the program code and flowchart will print out the values 8, 16, 24 and so on, up to and including the final value 80.

9781510484306.indb 33

33

19/08/20 8:31 PM

2  Programming

Key point A FOR loop will automatically increment the value of the counter variable by 1 each time; there is no need to do this manually.

Using the FOR loop shown so far, the programmer defines exactly how many times the given code will repeat.

Examples in high-level languages – FOR loops Python repeats using the RANGE keyword. Uniquely, the number given controls how many times the loop iterates, but the values will start at 0. The code below will therefore print out 0 to 9. for x in range(10): print(x)

VB.Net uses syntax very similar to the AQA Pseudo-code. The following code will print out 0 to 9. For x = 0 To 9 Console.WriteLine(x) Next x

C# uses a for loop that has three parts: the initialisation of the counter variable, the condition to check whether to repeat again, and the step to increase the counter variable by 1 each time (in this case ++ meaning to add one to the variable). The following code will print out 0 to 9. for (int x=0; x = 20

VB also has a LOOP WHILE statement (where the condition is checked at the end of the loop) and also a DO WHILE loop, which is functionally equivalent to a WHILE loop. C# has a WHILE loop in the same way that Python and VB.Net do. C# does not have a DO UNTIL loop, but it has a DO WHILE loop, which can be used in an equivalent way. //WHILE loop example int total = 0; while (total < 20) { string num = Console.ReadLine(); total = total + Convert.ToInt32(num); } //DO WHILE loop example int total = 0; do { string num = Console.ReadLine(); total = total + Convert.ToInt32(num); } while (total < 20);

The two C# examples given above are functionally equivalent, apart from where the condition is checked. The first example will check before beginning the first iteration whereas the second example is not checked until the loop has run at least once.

9781510484306.indb 35

35

19/08/20 8:31 PM

2  Programming

Nested selection and iteration Selection and iteration can both be nested. This is where more than one statement is used in such a way that they occur inside each other.

Worked example OUTPUT 'Enter an even number up to 100' num ← USERINPUT IF num > 100 THEN OUTPUT 'That is too large' IF num MOD 2 ≠ 0 THEN OUTPUT 'It isn’t an even number either!' ENDIF ENDIF

The code will first check if the number is above 100 and output a warning message if this is the case. However, another IF statement is then nested inside this to give another warning message if the number is not even. Notice that if an odd number over 100 is entered, both warning messages are displayed, but if an odd number below 100 is entered, nothing is displayed; this differentiates it from simply using separate IF or ELSE IF statements. The nested IF statement is only checked if the first one is True.

Worked example FOR a ← 1 TO 4 FOR b ← 1 TO 3 OUTPUT a * b ENDFOR ENDFOR

In this example, the outer loop will repeat four times, but each of these repetitions involves three executions of the inner loop. This code will therefore produce 12 lines of output (4 × 3 = 12). WHILE loops can be nested in exactly the same way.

Worked example age ← 0 WHILE age < 18 OUTPUT 'Enter your age' age ← USERINPUT IF age = 17 THEN OUTPUT 'You cannot vote but you can drive a car' ELSE IF age = 16 THEN OUTPUT 'You cannot vote but you can drive a ­ moped' ELSE IF age < 16 THEN OUTPUT 'Sorry, you are too young to vote or drive' ELSE OUTPUT 'Congratulations, you can vote and drive' ENDIF ENDWHILE

36

9781510484306.indb 36

In this example, the code checks whether the user can vote (if they are aged 18 or over) or drive (if they are aged 17 or 16). This is all nested inside a WHILE loop that repeats while the user’s age is under 18.

19/08/20 8:31 PM

AQA GCSE Computer Science

Knowledge check 2 State the three basic program constructs and describe each one. 3 What is the difference between a WHILE loop and a REPEAT UNTIL loop?

2.3 Arithmetic operations The arithmetic operators are used to carry out basic mathematical operations on values in computer programs. The common operators are: Operator +

Name Addition

Example a←b+c

Comment Adds the two values given.



Subtraction

x←y–1

Subtracts the second value from the first.

*

Multiplication

score ← score * 10

Multiplies the two values together.

/

Division

value ← num1 / num2 Divides the first value by the second.

MOD

Modulus

r ← score MOD 2

Returns the remainder after dividing the first value by the second value. So, 5 MOD 2 would return 1.

DIV

Integer division

q ← score DIV 2

Returns the whole number part after dividing the first value by the second value, ignoring any remainder. So, 5 DIV 2 would return 2.

Examples in high-level languages – arithmetic operators Python uses the following operators: a = b + c  #addition x = y – 1  #subtraction score = score * 10  #multiplication value = num1 / num2  #division r = score % 2  #modulus q = score // 2  #integer division

(See C# for a note specific to Python version 2.) VB.Net uses the following operators: a = b + c  'addition x = y – 1  'subtraction score = score * 10  'multiplication value = num1 / num2  'division r = score Mod 2  'modulus q = score \ 2  'integer division 37

9781510484306.indb 37

19/08/20 8:31 PM

2  Programming C# uses the following arithmetic operators: a = b + c;  //addition x = y – 1;  //subtraction score = score * 10;  //multiplication r = score % 2;  //modulus

Tech terms Operator precedence The order in which operations are carried out. BIDMAS This stands for Brackets, Indices, Division, Multiplication, Addition and Subtraction and is the order in which mathematical operations should take place if no other information is provided.

For division, the ‘/’ operator is used, but the output depends on whether the values given are defined as integers or real numbers. If integers are divided then the answer will always be an integer and the operation is integer division. If real numbers are divided then the answer will always be a real number and the operation is normal division. This is also the case for Python prior to version 3. Operator precedence is the same as in GCSE Mathematics, with BIDMAS being important. Any operators in brackets are applied first, with indices next, then division and multiplication, then addition and subtraction last.

Worked example For example, (3 + 6) + 7 * 2 means that the (3 + 6) is completed first, with the multiplication (7 * 2) completed next and then the results of these added together: (3 + 6) + 7 * 2 =9+7*2 = 9 + 14 = 23 This gives the answer of 23. If the calculation was (incorrectly) carried out sequentially then this would give the wrong answer of 32.

Key point The MOD operator can be used to decide if a number is odd or even. If we hold a value in the variable num, then num MOD  2 will give 0 if the value is an even number and 1 if the value is an odd number. It can also be used in the same way to decide if a number is an exact multiple of another smaller number.

2.4 Relational operations The relational operators (also known as comparison operators) all evaluate to a Boolean True or False outcome. Operator in AQA Pseudo-code

Name

Examples

Comment

=

Equal to

7 = 7 (true)

Some languages such as Python and C# may use a double == sign.

8 = 2 (false) ≠

Not equal to

7 ≠ 9 (true)

Some languages may use or !=

3 ≠ (1+2) (false) < 38

9781510484306.indb 38

Less than

4 < 7 (true) 4 < 4 (false)

Note – gives a False output if the values are equal.

19/08/20 8:31 PM

AQA GCSE Computer Science Operator in AQA Pseudo-code

Name

Examples

Comment



Less than or equal to

7 ≤ 7 (true)

Note – gives a True output if the values are equal.

6 ≤ 4 (false)

Greater than

2 > 1 (true) 3 > 3 (false)



Greater than or equal to

9 ≥ 9 (true) 6 ≥ 9 (false)

Note – gives a False output if the values are equal. Note – gives a True output if the values are equal. >= used in high-level languages.

Examples in high-level languages – relational operators Python uses the following relational operators: a == b a != b

#equal to #not equal to

a < b

#less than

a b

#greater than

a >= b

#greater than or equal to

VB.Net uses the following relational operators: a = b a b

'equal to 'not equal to

a < b

'less than

a = b

'greater than or equal to

C# uses the following relational operators: a == b a != b

//equal to //not equal to

a < b

//less than

a b

//greater than

a >= b

//greater than or equal to

39

9781510484306.indb 39

19/08/20 8:31 PM

2  Programming

2.5 Boolean operations If multiple conditions need to be evaluated, the Boolean operators AND and OR can be used. A condition can also be reversed using the NOT operator. These function in the same way as the Boolean logic gates with the same names in section 4.2. The AND operator requires both conditions to be True for the overall condition to be True. If either or both of the conditions are False, the overall condition will be False.

Worked example OUTPUT 'enter your username' username ← USERINPUT OUTPUT 'enter your password' password ← USERINPUT IF username = 'admin' AND password = 'changeme123' THEN OUTPUT 'Correct details. Logged in' ELSE OUTPUT 'Incorrect details' ENDIF

In this example, the AND operator means that both conditions (the username and password both matching the correct ones) need to be True for the user to be logged in. The OR operator requires one or the other (or both) of the conditions to be True for the overall condition to be True. If both of the conditions are False, the overall condition will be False.

Worked example num1 ← USERINPUT num2 ← USERINPUT IF num1 > 10 OR num2 > 10 THEN OUTPUT 'Accepted' ELSE OUTPUT 'Rejected' ENDIF

In this example, the OR keyword means that either of the entries needs to be over 10 for the ‘Accepted’ message to be displayed. If both are over 10 then the accepted message is still displayed. The ‘Rejected’ message is only displayed if neither of the two entries is over 10.

Key point Each condition given to an AND or OR operator must be a full condition. A very common mistake is to write code such as: IF num1 OR num2 > 10 THEN This is incorrect; the first condition (num1) has nothing to be compared against and so this code will not work as intended. The correct way, to write this is: IF num1 > 10 OR num2 > 10 THEN

40

9781510484306.indb 40

19/08/20 8:31 PM

AQA GCSE Computer Science The NOT operator reverses the True or False outcome from a comparison.

Worked example num1 ← USERINPUT num2 ← USERINPUT IF NOT(num1 = num2) THEN OUTPUT 'the numbers are not the same' ENDIF

In this example, the equivalence operator (=) would give a True outcome if the input values were the same. However, the NOT operator reverses this, so that a False is returned if the numbers are the same and True if they are not the same. Of course, this is logically the same as using the ≠ operator.

Examples in high-level languages – Boolean operators Python uses the following Boolean operators: a and b a or b not a

#AND #OR #NOT

VB.Net uses the following Boolean operators: a And b a Or b Not a

'AND 'OR 'NOT

C# uses the following Boolean operators, which are considerably different from the AQA Pseudo-code: a & b a | b !a

//AND //OR //NOT

Knowledge check 4 What is the value assigned to the variable x in each of the following? (a) x ← 23 – 4 * 3 (b) x ← (12 – 5) * 3 (c) x ← 6 * 2 / 3 (d) x ← 8 / (5 – 1) (e) x ← 19 MOD 5 (f) x ← 22 MOD 4 * 2 (g) x ← 28 DIV 6 (h) x ← 23 DIV 2 * 4 5 What will be returned by the following comparisons? (a) a ≠ b if a = 8 and b = 5 (b) a ≥ b if a = 9 and b = 5 (c) a > b OR c