Cambridge IGCSE™ and O Level Computer Science Coursebook with Digital Access (2 Years) (Cambridge International IGCSE) 1108915140, 9781108915144

This series supports learners through the Cambridge IGCSE™ and O Level Computer Science syllabuses (0478/0984/2210). Bui

233 147 45MB

English Pages 408 [412] Year 2021

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Cambridge IGCSE™ and O Level Computer Science Coursebook with Digital Access (2 Years) (Cambridge International IGCSE)
 1108915140, 9781108915144

Citation preview

Second edition

Digital Access

Your Access Code This code gives you access to your digital resource. Please scratch the panel lightly to reveal the code beneath (a coin is ideal for this):

How do I activate my digital resource? •

Please log in at cambridge.org/go and then click on 'Add new resources' to use the access code above.



Need to register? Create your account at cambridge.org/go and then click on 'Add new resources' to use the access code above.

Terms and conditions: •

This access code will give you 2 years' (24 months') access to the digital resource starting from the day you first use the code.



This code can only be used once, is personal to you, and cannot be reused by anyone else.



Full terms and conditions are available at: cambridge.org/go/terms_of_use

CAMBRIDGE UNIVERSITY PRESS

Computer Science ™

for Cambridge IGCSE & 0 Level COURSEBOOK Sarah Lawrey & Victoria Ellis

CAMBRIDGE UNIVERSITY PRESS

University Printing House, Cambridge CB2 8BS, United Kingdom One Liberty Plaza, 20th Floor, New York, NY 10006, USA 477 Williamstown Road, Port Melbourne, VIC 3207, Australia 314--321, 3rd Floor, Plot 3, Splendor Forum, Jasola District Centre, New Delhi- 110025, India 79 Anson Road, #06-04/06, Singapore 079906 Cambridge University Press is part of the University of Cambridge. It furthers the University's mission by disseminating knowledge in the pursuit of education, learning and research at the highest international levels of excellence. www.cambridge.org Information on this title: www.cambridge.org/9781108915144 © Cambridge University Press 2021 This publication is in copyright. Subject to statutory exception and to the provisions of relevant collective licensing agreements, no reproduction of any part may take place without the written permission of Cambridge University Press. First published 2015 Second edition 2021 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 Printed in Malaysia by Vivar Printing A catalogue recordfor this publication is available_fi'om rhe British Library

ISBN 978-1-108-91514-4 Coursebook Paperback with Digital Access (2 Years) ISBN 978-1-108-82414-9 Digital Coursebook (2 Years)

ISBN 978-1-108-82416-3 Coursebook eBook

Additional resources for this publication at www.cambridge.org/go Cambridge University Press has no responsibility for the persistence or accuracy of URLs for external or third-party internet websites referred to in this publication, and does not guarantee that any content on such websites is, or will remain, accurate or appropriate. Information regarding prices, travel timetables, and other factual information given in this work is correct at the time of first printing but Cambridge University Press does not guarantee the accuracy of such information thereafter. Exam-style questions and sample answers have been written by the authors. In examinations, the way marks are awarded may be different. References to assessment and/or assessment preparation are the publisher's interpretation of the syllabus requirements and may not fully reflect the approach of Cambridge Assessment International Education. Cambridge International copyright material in this publication is reproduced under licence and remains the intellectual property of Cambridge Assessment International Education. NOTICE TO TEACHERS IN THE UK It is illegal to reproduce any part of this work in material form (including photocopying and electronic storage) except under the following circumstances: (i) where you are abiding by a licence granted to your school or institution by the Copyright Licensing Agency; (ii) where no such licence exists, or where you wish to exceed the terms of a licence, and you have gained the written permission of Cambridge University Press; (iii) where you are allowed to reproduce without permission under the provisions of Chapter 3 of the Copyright, Designs and Patents Act 1988, which covers, for example, the reproduction of short passages within certain types of educational anthology and reproduction for the purposes of setting examination questions.

... �.., DEDICATED < >TEACHER ��,Ji AWARDS

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

> Contents

The items in orange are accessible to teachers for free on the supporting resources area of Cambridge GO.

How to use this book How to use this series

1

8

1.3 1.4 1.5

2

Data transmission The structure of a data packet 2.1 Packet switching 2.2 Methods of data transmission 2.3 2.4 The universal serial bus (USB) 2.5 2.6

3

Hardware The role of the CPU 3.1 The fetch stage 3.2 The decode stage 3.3 The execute stage 3.4 Factors that can affect the 3.5 3.6 3.7 3.8 3.9 3.10

IV

interface Detecting errors in data transmission Encryption

>

performance of a CPU Input and output devices Data storage Virtual memory Cloud storage Network hardware

78

5

The internet and its uses 5.1 The internet and the world wide web 5.2 Requesting and retrieving web pages 5.3 The purpose of a web browser 5.4 Digital currency 5.5 Cyber security

94

6

Automated and emerging technologies 6.1 Automated systems 6.2 Robotics 6.3 Robots in context 6.4 Artificial intelligence

VIII

1

numbers How do computers represent text, images and sound? Measuring data storage Data compression

Software 4.1 Types of software 4.2 Operating system Interrupts 4.3 4.4 Types of programming language 4.5 Translators 4.6 Integrated Development Environment

VI

Introduction Data representation 1.1 Binary and hexadecimal Binary manipulation and negative 1.2

4

10 16

(IDE)

21 25 27

33 35 36 38

43 44 49

54 56 57 58 58

60 62 66 69 70 72

7

80 81 84 85 87 90

96 97 100 105 106

125

126 132 132 136

Algorithm design and problem solving 143 7.1 Program development life cycle 145 7.2 Analysis 146 7.3 Design 146 7.4 154 Pseudocode 7.5 157 Coding 7.6 157 Testing 7.7 159 Common algorithms 7.8 179 Trace tables 7.9 Finding the purpose of an algorithm 184 7.10 Finding errors in a program and 187 correcting the errors

Contents

8

Programming 8.1 8.2 8.3 8.4 8.5 8.6 8.7 8.8 8.9 8.10 8.11 8.12 8.13 8.14 8.15 8.16

9

Programming concepts Data types Input and output Arithmetic operators Sequence Selection Iteration Totalling Counting String manipulation Nested statements Subroutines Library routines Maintainable programs Arrays File handling

Databases 9.1 9.2 9.3 9.4 9.5 9.6 9.7

Database structure SQL SELECT ... FROM SELECT ... FROM ... WHERE Order by SUM COUNT

196 198 202 205 209 214 216 231 241 243 245 251 255 265 267 270 286

295 297 302 302 305 311 312 313

10 Boolean logic 10.1 10.2 10.3 10.4 10.5 10.6 10.7 10.8 10.9 10.10 10.11

324

The role of logic gates The NOT logic gate The AND logic gate The OR logic gate The NAND logic gate The NOR logic gate The XOR logic gate Logic expressions Representing truth tables Representing logic expressions Representing problem statements

326 326 327 329 330 331 333 337 339 344 347

11 Programming scenarios practice 11.1 11.2 11.3 11.4

353

Programming scenario Method 1: Identifying the inputs, processes and outputs Writing the code Method 2: Practically carrying out the program and identifying the stages

355 355 357 365

Microsoft case studies

381

Glossary

386

Index

394

Acknowledgements

400

Coursebook answers

V

>

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

> How to use this book Throughout this book, you will notice lots of different features that will help your learning. These are explained below. Answers to all questions and activities are accessible to teachers in the 'supporting resources' area of cambridge.org/go.

LE ARNING INTENTIONS

These set the scene for each chapter, help with navigation through the coursebook and indicate the important concepts in each topic.

This contains questions and activities on subject knowledge you will need before starting this chapter. COMPUTER SCIENCE IN CONTEXT

PROGRAMMING TASKS

This feature presents real-world examples and applications of the content in a chapter, encouraging you to look further into topics. The 'Computer science in context' feature that opens each chapter also ends with discussion questions.

Programming tasks give you the opportunity to develop your programming and problem-solving skills.

KEY WORDS

Key vocabulary is highlighted in the text when it is first introduced. Definitions are then given in the margin and can also be found in the glossary at the back of this book. SKILLS FOCUS This feature supports your computational thinking, mathematical and programming skills. The features include useful explanations, step-by-step examples and questions for you to try out yourselves.

Each task is divided into three parts:

Getting started



These questions will help build your basic problem-solving skills.

Practice



These questions will ask you to design a possible solution to a problem or complete a coding task.

Challenge



These questions will stretch and challenge your problem-solving, logic and programming skills even further.

These are short suggestions to remind you about important learning points.

VI

>

How to use this book

COMMAND WORDS

ACTIVITY

Command words that appear in the Cambridge Assessment International Education syllabus are highlighted in the exam-style questions when they are first introduced, and are accompanied with their syllabus definitions in the margins. Not all command words from the syllabus are included in the exam-style questions, but you will find all command word definitions in the glossary at the back of the book.

Activities give you an opportunity to check your understanding throughout the text in a more active way, for example, by creating presentations, posters or role plays.

Questions Appearing throughout the text, questions give you a chance to check that you have understood the topic you have just read about.

At the end of some activities, you will find opportunities to help you assess your own work, or that of your classmates, and consider how you can improve the way you learn.

REFLECTION These activities ask you to think about the approach that you take to your work, and how you might improve this in the future.

Further Information: This feature highlights the advanced aspects in this book that go beyond the immediate scope of the syllabus.

lsuMMARY There is a summary of key points at the end of each chapter.

1· EXAM-STYLE QUESTIONS Questions at the end of each chapter provide more demanding exam-style questions, some of which may require use of knowledge from previous chapters. S�LF-EVALUATION CHECKLIST The summary checklists are followed by 'I can' statements which match the Learning intentions at the beginning of the chapter. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'.

VII

>

iTihc ...:our�eboo�

resource contains detailed

appropriate interventions

and stretch learners.

The digital teacher's resource also contains scaffolded worksheets for each chapter, as well as practice exam-style papers. Answers are free!� accessible to teadiers on tne 'supporting resources' area of the Cambridge GO platform.

Computer Science for Cambridge IGCSE,. & 0 Level

There are three programming books: one for each of the recommended languages in the syllabuses - Python, Microsoft Visual Basic and Java. Each of the books are made up of programming tasks that follow a scaffolded approach to skills development. This allows learners to gradually progress through 'demo', 'practice' and 'challenge' tasks to ensure that every learner is supported. There is also a chapter dedicated to programming scenario tasks to provide support for this new area of the syllabuses. The digital part of each book contains a comprehensive solutions chapter, giving step-by-step answers to the tasks in the book.



)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

What is computer science?

Computer science is the study of computers and computational thinking. It includes the purpose and operation of hardware, software and networks.

Computer science involves studying theoretical ideas about how data is processed and stored, and what would be necessary to perform such theoretical operations. It is also the practical application of these ideas to create new hardware and software. Studying hardware involves learning about the basic design of computers and how they operate, including how they perform calculations, logical operations and how they store data. It involves understanding how and why binary is used in a computer for these processes. Studying software involves learning about the different programming concepts and how to apply these in different programming languages. It involves looking at how translators are used to convert programming languages into the necessary binary state needed for a computer to process. It also involves learning about different types of software, such as operating systems and applications. Studying networks involves learning about how data is transmitted across a network, including some of the components involved in this process. It also involves looking at the risks involved in using a network and how you can use different methods to help prevent exposure to these risks.

Introduction

Why should you study computer science?

Over the years since their invention, computers have dramatically changed the way many of us live. The introduction of the personal computer (PC) into many homes around the world has led to the development of the internet, which began to transform the way that many people communicate and share information. The use of computer systems is now a widespread practice. They range from small embedded systems in our everyday devices, such as refrigerators, traffic lights, digital cameras and washing machines, to being responsible for handling the world's money in huge banking systems.

Hardware and software used in an industrial setting

There are many aspects of our life today that would not be possible on the same scale without the use of computers, so studying what they are, how they work and the many purposes they have can be both fun and exciting. It can also be very interesting and challenging as you try to understand the complex nature of their operation. There are many lifelong skills that you can develop through learning about computer science, these including logical thinking, creativity and problem solving. These are all skills that add to your employability status in the future. Computer scientists are needed in many different industries, so the choice of career that you could take is very open. Industries such as science, engineering, finance, manufacturing, sports and healthcare all use a wide variety of computers and require lifelong skills that the study of computer science builds. Computers advance on a constant basis, so being part of the study of how that happens keeps your studies relevant and engaging. What are you waiting for? Let the enjoyment begin!

Doctors performing robotic surgery

Aeronautical engineer using a tablet computer

3

>

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Under the hood of a computer

In order to study their wider purpose, it is useful to understand what exactly is 'under the hood' of a computer. Let's look at a personal computer (PC), what are the components that they contain? Power supply unit

Random access memory (RAM)

Computer case Optical drive

Computer case fan

Central processing unit (CPU) cooling fan

Hard drive

Central processing unit (CPU) (under the fan)

Graphics card

Motherboard

Inside a desktop computer case

Computer case

The computer case is the unit in which all the other components are stored. The case stops too much dust getting to the computer components, which can harm them and affect the way that they are able to perform. The size of a case is often dictated by the size of the motherboard that it will store, as this is one of the larger components within the computer. Computer cases have been made from all kinds of material such as steel, aluminium, plastic, wood, glass and even Lego!

A computer case

4

>

Introduction

Computer case fan The components inside a computer consume power to operate. This means that they can often get quite hot. A computer case has a fan that is attached to the side of it that spins to keep the components within the case nice and cool. If a computer is needed for high performing tasks that will require more power, it may need more than one case fan.

Motherboard The motherboard (shown in the image below) is a very important component in a computer. All the other components in the computer plug into the motherboard. The motherboard allows the components to be connected and to communicate in order to carry out all the operations. It also allows all the components to receive the power that comes from the power supply unit. It is a large and very important circuit board. It is often thought of as the backbone of a computer as it holds all the other components together. The motherboard has a special unit in which the CPU is seated. It also has lots of special slots that components such as the RAM and the graphics card are clipped into. It has lots of pins around the edges where cables can be plugged into to power the different components.

Computer case fans

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CPU The central processing unit (CPU) is a very important component within a computer. It is known as the brains of the computer. It is responsible for the operation of each fetch-decode-execute cycle that the computer carries out. You will learn a lot more about the CPU and what it does in Chapter 3. You can find it inserted into a special unit on the motherboard. It's a very small component but has a very big job!

The CPU

CPU Cooling fan One component that can get very hot in a computer is the CPU. It is constantly working and it is completing millions of cycles each second. It is vital that the CPU doesn't get too hot or it will no longer work . Therefore, the CPU normally has its own fan that sits directly on top of it. This keeps it running at the best temperature for it to operate. CPU cooling fans can just be a simple fan, or they can be as elaborate as water cooling systems to keep the CPU at the best temperature.

PSU All the components in a computer need power to operate. They are all connected to the motherboard to get access to power. There is one component that powers the motherboard to allow it to pass power to the other components and this is called the power supply unit (PSU). PSUs can have different levels of wattage output. The higher the wattage, the more powerful the PSU. A standard computer will need a PSU that outputs approximately 300 to 500 watts. A computer that has lots of high performance components will need a more powerful PSU to supply a higher level of power. A PSU like this could output over 1000 watts.

A water cooled CPU

A power supply unit

RAM The random access memory (RAM) is the component that temporarily stores data in a computer that is waiting to be processed. RAM is plugged into the motherboard and is available in different storage sizes. A common size of RAM for a computer to have is 8 GB of RAM. However, if a computer is a high performance computer, it will have a lot more data that needs to be processed each second, so it will need a larger amount of RAM. A computer like this could have 32GB of RAM. The amount of RAM a computer has can be upgraded. RAM is commonly available in sizes of 8 GB. So, another 8 GB card can be inserted into a RAM slot on the motherboard to upgrade the amount of RAM by 8 GBs. You will learn more about the purpose of RAM in Chapter 3.

6

>

RAM memory modules

Introduction

Graphics card A graphics card is the component in the computer that is responsible for producing the images that you see on your computer screen. Some computers have a graphics unit built into the motherboard, this is called a graphics processing unit (GPU). However, most GPUs are low performing and not capable of producing the high quality of graphics seen by most computers today. Therefore, graphics cards are now more commonly used in computers to produce the high quality of graphics desired by many users. The graphics card plugs into a special slot on the motherboard. Like the CPU, a graphics card is responsible for processing a lot of data, so it normally has built in fans to keep it cool and stop it from overheating. A graphics card

Hard drive The hard drive is where all the files and software that you use on your computer are permanently stored. Most computers will either have a hard disk drive (HDD) or a solid state drive (SSD). It is common in computers now to have approximately 1 TB of storage, but earlier computers only had 250-S00GB of data storage. The demand for an increasing amount of storage space continues as we store more and more data on our computers. Some companies have predicted this demand and have started to encourage users to use cloud storage as a result. You will learn more about the operation of a HDD and an SSD, and cloud storage in Chapter 3.

A hard drive

Optical drive The final component is an optical drive. This is the device in which you insert optical media such as CDs into, to be read by the computer. Optical drives used to be very common in computers, but more modern computers are often now manufactured without them. This is because a lot of content and data is now digitally shared and the need for using CDs to share data has decreased as a result. You now know what is inside a computer case, eagerly working hard to complete all the actions that you ask of your computer. You now get to learn some exciting information about computer science, including how some of those components work on a more detailed level, and you get to learn how to create the computer programs that are processed by your computer. Let's get started!

An optical drive

7

>

learn why computers use binary to process data •

develop an understanding about how binary is used to represent different forms of data, such as text, sound and images



learn to convert between the number systems denary, binary and hexadecimal



learn to add two binary numbers and understand what is meant by overflow



learn to perform a binary shift and how this affects the number



learn to use two's complement to represent negative binary numbers



learn how the file size of data is measured



learn how and why data is compressed.

1

Data representation

GETTING STARTED

Working with a partner, write the words 'text', 'sound' and 'image' on a piece of paper. Around each word, write words that you can think of that are linked to each of the three words. For example, you could write the words 'sound wave' next to the word 'sound'. DEBUGGING USING HEXADECIMAL

Computer programs are the foundation of computer games. If there is an error with the program, this can cause unexpected behaviour in the game. For example, a character may move the wrong way when a button is pressed. The programmer needs to find out why the character is moving incorrectly. The amount of code that needs to be assessed to find this error in a computer game is enormous and the binary values involved will be vast. Therefore, the programmer will often use hexadecimal to debug the error. One way this can be done is to look at the address for a variable. The address is the location in memory where the data is stored and it is shown in hexadecimal. This address is then looked up in a table to find the value held in the address. The value is also given as hexadecimal. If the value in the address is, for example, 0000 or FFFF (this can mean that the variable has not been initiated) the programmer will know that there is a problem with this value and has located the variable with which the error is occurring. The programmer can then find out why the variable is not holding a valid value.

KEYWORDS hexadecimal: a base-16 number system that uses the values 0-9 and characters A-F. binary: a base-2 number system that uses the values 0 and 1.

If the addresses and values were given as binary, rather than as hexadecimal, then it would be more difficult to identify if an error has occurred. For example, it is easier to see if an address contains a valid value, e.g. F2A5, rather than 1111001010100101.

Figure 1.1: Data represented by hexadecimal letters and numbers

9

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED Discussion questions

1

Do you think that you have ever seen or used hexadecimal before? If you have, can you provide an example of where you have seen or used it?

2

Why is it important for a programmer to be able to effectively debug a computer program?

1.1 Binary and hexadecimal Humans process a large amount of data on a daily basis. Did you know that when we have a conversation with someone, we process approximately 60 bits of information per second? Our brain is designed to process a maximum of about 120 bits per second. That's why it is so difficult to listen to two people talk to us at once! As humans, we process data that is called analogue data. Everything we see, hear, feel and smell is a continuous stream of analogue data to our senses.

Questions 1 2

Can you think of three examples of analogue data? Why is analogue data described as continuous data?

The components that process data in a computer are made up of very small logic gates. These gates cannot process analogue data, they can only process digital data. This data is stored in registers. You can find out more about logic gates in Chapter 10. Digital data is discrete data that only has two values, 1 and 0. Any data that we want a computer to process must be converted into digital data. This type of data is also called binary data.

Number systems In our daily lives we mostly use a denary number system. This is called a base-10 number system and uses the digits 0-9. The units in a denary number system are ones, tens, hundreds and thousands. Each time the unit increases by the power of 10. For example, the denary number 123 has: Increases by power of 10



One hundred

'\

Increases by power of 10

Two tens

2



'\

Three ones

3

Computers use a binary number system. This is called a base-2 number system and uses the digits O and 1. The units in a binary number system increase by the power of 2. Any denary values need to be converted to binary values so that they can be processed by a computer.

10

)

KEYWORDS analogue data:

a continuous stream of data that is processed by humans. logic gate: a very small component in a computer system that controls the flow of e Iectricity. digital data: discrete data that only uses the values O and 1. register: a small component in a computer system that is used to temporarily store data. denary: a base-10 number system that uses the values 0-9.

1

Data representation

SKILLS FOCUS 1.1 CONVERTING BETWEEN DENARY AND BINARY NUMBERS The size of a binary number is referred to by the number of bits it has. A 4-bit binary number will have 4 values that are either 1 or 0, for example, 1001. An 8-bit binary number will have 8 values that are also either 1 or 0. Binary values can get very large, some have as many as 64 bits; now that's a very big number! You will need to be able to understand binary numbers that have as many as 16 bits. First, focus on converting denary numbers to 4-bit binary. To convert denary numbers to 4-bit binary the units that you need to use are 1, 2, 4 and 8. You can indicate with a 1 or a 0 whether that unit is required. For example, if you convert the denary number 13 to a 4-bit binary number you can use the following steps: Write down the binary units from 8 to 1. An easy way to do this is using a table.

Do you notice how the units increase by the power of 2 each time (going from right to left)? Compare the denary number (13) to the first binary unit (8) to see whether it is equal to or greater than the denary number. 13 is greater than 8, which means that the unit 8 is required and you can write a 1 beneath it. 8 can then be subtracted from the denary value, 13-8 = 5.

Now compare the denary number (5) to the next binary unit (4) to see whether it is equal to or greater than the denary number. 5 is greater than 4, which means that the unit 4 is required and you can write a 1 beneath it. 4 can then be subtracted from the denary value, 5-4=1.

Then compare the denary number (1) to the next binary unit (2) to see whether it is equal to or greater than the denary number. 1 is not greater than 2, which means that the unit 2 is not required and you can write a 0 beneath it. No subtraction is needed this time as you haven't used the unit.

Finally, compare the denary number (1) to the last binary unit (1) to see whether it is equal to or greater than the denary number. 1 is equal to 1, which means that the unit is required and you can write a 1 beneath it. 1 can then be subtracted from the denary value. 1 - 1 = 0.

11

>

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED

This means that if you convert the denary number 13 to 4-bit binary, you get the binary number 1101. Questions

1 2 3

What is the largest denary number that can be created with a 4-bit binary number? Convert the denary number 6 to a 4-bit binary number. Convert the binary number 9 to a 4-bit binary number.

To convert denary numbers to 8-bit binary the units that you need to use are 1, 2, 4, 8, 16, 32, 64 and 128. You can indicate, again, with a 1 or a 0 whether that unit is required. For example, if you convert the denary number 150 to an 8-bit binary number you can use the same method as before: Write down the binary units from 128 to 1:

64

6 1

1 1 1 Compare the denary number (150) to the first binary unit (128) to see whether it is equal to or greater than the denary number. 150 is greater than 128, which means that the unit 128 is required and you can write a 1 beneath it. 128 can then be subtracted from the denary value, 128-150 = 22.

28 1 1

3

6

4

1

1

2

2 3

1

6

1

Next, compare the denary number (22) to the next binary unit (64) to see whether it is equal to or greater than the denary number. 22 is not greater than 64, which means that the unit 64 is not required and you can write a 0 beneath it. No subtraction is needed this time as you haven't used the unit. 3 1

2

1

6

1

Then compare the denary number (22) to the next binary unit (32) to see whether it is equal to or greater than the denary number. 22 is not greater than 32, which means that the unit 32 is not required and you can write a 0 beneath it. No subtraction is needed this time as you haven't used the unit. 6 1 1

Now, continue this process until you have compared all the binary units. Remember to subtract the unit from the denary number if it is required. You should end with the following result:

12

)

1

Data representation

CONTINUED This means that if you convert the denary number 150 to 8-bit binary, you get the binary number I 00IO 110. A quick check that you can do on your calculation is to look at the last unit on the right of your binary number. If the denary number you are converting is an odd number, this number should be 1. If the denary number you are converting is an even number, this number should be 0. Questions

4 5

Convert the denary number 58 to an 8-bit binary number. Convert the denary number 123 to an 8-bit binary number.

If you need to convert a binary number into a denary number, you can use simple addition. You just need to add together all the units that are represented by the value 1. Try converting the binary number 1010. A simple way to do this is to use a table. You can write the units above and the binary number below:

You just need to add together all the units that have a I below. This means the calculation is 8 + 2 = 10. Therefore, if you are converting the binary number 1010 to denary, you get the denary number 10. If you need to convert an 8-bit binary number, you need to extend the units so that you have 8 of them. Remember to increase by the power of 2 each time. Try converting the binary number 10011001. You can write the values in a table again to make it clearer:

You just need to add together all the units again that have a I below. This means the calculation is 128 + 16 + 8 +I= 153. Therefore, if you are converting the binary number 100011001 to denary, you get the denary number 153. Questions

6 7

8

What is the largest denary number that can be created with an 8-bit binary number? Convert the 8-bit binary number 01100011 to a denary number. You need to be able to convert up to 16-bit binary values. Fill in the missing units in the table and calculate the denary number for the given binary number.

REFLECTION How did you know how to add in the correct missing units for Question 8? How did you work out each unit?

13

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Hexadecimal Hexadecimal is also a number system. Humans can use hexadecimal, but computers cannot process it. Like denary numbers, hexadecimal numbers also need to be converted to binary to be processed by a computer. Hexadecimal is a base-16 system and uses 16 symbols, these are the numbers 0-9 and the letters A-F. This is to allow the denary values 0-15 to be represented in hexadecimal. This is shown in Table 1.1. Denary

0

1

2

3

4

5

6

7

8

9

10 11 12 13 14 15

Hexadecimal

0

1

2

3

4

5

6

7

8

9

A

B

C

D

E

F

Table 1.1: Hexadecimal representations of denary numbers

The reason for using the symbols A-F for the denary numbers 10-15 is so only one symbol is needed for the denary number in hexadecimal.

SKILLS FOCUS 1.2 CONVERTING BETWEEN DENARY NUMBERS AND HEXADECIMAL To convert a denary number to hexadecimal, it is easier to convert it to binary first. For example: First convert the denary number 7 to 4-bit binary.

To convert the binary number to hexadecimal you can use simple addition again. 4 + 2 + 1 = 7. If you look at the symbol table (Table 1.1), you can see that the hexadecimal for 7 is also 7. Therefore, the denary number 7 is 0 111 as binary and 7 as hexadecimal. So, what happens with denary numbers that are greater than 9? First convert the denary number 12 to 4-bit binary.

To convert the binary number to hexadecimal you can use simple addition again. 8 + 4 = 12. If you look at the symbol table (Table 1.1), you can see that the hexadecimal for 12 is C. Therefore, the denary number 12 is 1100 as binary and 12 as hexadecimal. Converting the denary number to binary first isn't necessary for denary numbers that are less than 16, but it makes the process easier when you need to convert larger denary numbers. So, how do you convert a larger denary number to hexadecimal?

14

)

1

Data representation

CONTINUED

· � I I I I 1: I� I� I� 1: I� I� I� 1: I� I� I�

First, convert the denary number 201 to 8-bit binary. You know you can use 8-bit binary because the denary number is less than 256.



2

28



6



Each hexadecimal symbol only uses 4 bits. Therefore, you need to split the 8-bit binary number into two 4-bit binary numbers.

You then convert each 4-bit binary number again using simple addition. 8+4= 12 8+1=9

The hexadecimal for 12 is C and the hexadecimal for 9 is 9. Therefore, the denary number 201 converted to binary is 11001001 and to hexadecimal is C9. To convert a hexadecimal number to a binary number of a denary number you can just reverse the process. To convert the hexadecimal number SE to a binary number you need to convert each symbol to 4-bit binary. Remember E is the number 14.

5

E

Therefore, the hexadecimal SE converted to a binary number is 01011110. To convert the hexadecimal SE to denary, you can use the binary number that you have just calculated.

You can add all the units together to get the denary value. 64+16 + 8+4+2=v94. The hexadecimal SE converted to a denary number is 94. Questions 1

2 3 4

Convert the hexadecimal A2 to a binary number. Convert the binary number 100111010001 to hexadecimal. Convert the denary number 350 to hexadecimal. Convert the hexadecimal 3AC to a denary number.

15

)

CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Why is hexadecimal used in computer science? Programmers often use hexadecimal when writing and analysing computer programs. They do this because it is easy for a human to read hexadecimal, rather than binary. For example, if a programmer looked at a set of data that is stored in registers, as binary it could look like this:

10011100101110111000111011100010111101011010

The programmer may be trying to find out if the data stored matches the correct data which should be:

10011100101110111001011011100010111101011010

At a glance, it is difficult to see whether the two values match or if an error has occurred. If that stored data is represented in hexadecimal it would be: 9CBB8EE2F5A Comparing it to the correct value that should be: 9CBB96E2F5A It is much easier to see that the data does not match, and the programmer can identify that an error has occurred. The benefits of using hexadecimal rather than binary for a programmer are: •

Hexadecimal is a shorter way of representing binary, so it takes up less space on the computer screen or piece of paper.



Hexadecimal is easier for a programmer to read, write and understand.



Hexadecimal is easier to debug and locate errors in data.

ACTIVITY 1.1

KEY WORD

Each computer has a MAC address. This MAC address is written in hexadecimal. This is one of the ways that hexadecimal is used in computer science.

MAC address: a unique address that is given to a computer at the manufacturing stage that can be used to identify the computer.

Use the internet to find three more uses of hexadecimal in computer science.

1.2 Binary manipulation and negative numbers Binary addition You need to be able to add together two 8-bit binary numbers. When binary numbers are added together there are four rules that you will need to use: Rule 1 is 0 + 0 = 0

16

)

1

Data representation

Rule 2 is 1+0 = 1 Rule 3 is 1 + 1 = 10 (this is because 10 in binary is 2) Rule 4 is 1 + I + 1 = 11 (this is because 11 in binary is 3) You can apply these rules to add the binary numbers 10010100 and 00011110.

0

0

0

0

0

0

0

0 0

You need to start at the right and begin applying the rules. The first calculation is 0+0.Rule The next calculation is 0+1. Rule 2 means the result is 1.

0

0 0

0 0

0

0

1

0 0

0

The next calculation is 1 + 1.Rule 3 means the result is 10. You need to write the 0 in the answer section and carry the 1 to the next calculation. +

0

0 0

0 0

0

0

0

0

0

1

0

The next calculation is 1 + 0+1, which results in l + I.Rule 3 means the result is 10. Write the 0 in the answer section again and carry the I. +

1 0

0 0

1 0 1

0 0

0

0

0

0

1

0

0

The next calculation is 1 +1 + 1. Rule 4 means the result is 11. Write 1 in the answer section and carry 1. +

0

0 0

1 0 0

0 1

0

1

0

0 1

0 0

0

The next calculation is I + 0+0, which results in 1 +0.Rule 2 means the result is 1. Write 1 in the answer section. There is no carry this time. +

0

0 0

1 0 0 1

1 0

0

1

1

0

0

1

0 0

0

17

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

The next calculation is O + 0. Rule 1 means the result is 0. Write O in the answer section.

1 0

+

0 0

1 0 0

0

1

1 0 1 1

0

0

0

0 0

1

0

The final calculation is 1 + 0. Rules 2 means the result is 1. Write 1 in the answer section. +

0 1

0 0

0

0 0 1

1 1

0 0

1 0

0 1

0 0

0

Therefore, when the binary numbers 10010100 and 00011110 are added, the answer is 10110010.

Questions 3 4

Add the 8-bit binary values 00011001 and 01000011. Add the 8-bit binary values 00100110 and 01010111.

You should now know that the largest number that can be stored in an 8-bit binary register is 255. What happens when two 8-bit binary values are added, and the result is larger than 255? The following example, which is almost complete, is very much like the previous calculation with a slightly different binary number. Can you spot the difference?

+

0 0

0 0

0

1

0 1

0

0

0

0 0

1

0

If you now try and do the final calculation, that would be 1 + 1 = 10. You write O in the answer section, but there is nowhere to carry the 1. This is because the two 8-binary binary values are added the result is 306, which is greater than 255. Therefore, the number cannot fit in the 8-bit register and an overflow error is created. +

1

0

0

0 0

0

1

1

0 0

0

1

1

1

1

0

0

0 1

0 0

0

Overflow error Each computer has a predefined limit, for example, 16-bit registers. What is the largest number that could be stored in a 16-bit register? If a number larger than this is generated in a process, an overflow error will occur.

18

)

KEY WORD overflow error: a type of error that occurs when a number larger than a register can store is generated.

1

Data representation

Logical binary shifts Another process than can occur with binary numbers that are stored in a register is called a logical binary shift. This kind of shift can move the binary values in the number to the left or to the right. Consider the binary number:

lo

lo

lo

lo

lo

If a logical binary shift to the left is performed on the binary number, each value in the binary number is moved one place to the left. The result would be:

lo

lo

lo

lo

lo

lo

lo

lo

lo

lo

lo

You should notice that the left most 0 has been removed from the register. This is because there was no place to the left to shift this value. You should also notice that there is now an empty section in the register at the right. When a binary number is shifted, the resulting empty sections are filled with a 0.

If you convert the first binary number to denary, you get the denary number 44. If you convert the binary number after the logical left shift has been performed, you get the denary number 88. This means that each logical shift to the left multiples the binary number by 2. Consider the binary number again:

lo

lo

lo

If a logical shift to the right is performed on the binary number, each value in the binary number is moved one place to the right. The result would be:

lo

lo

lo

lo

lo

lo

lo

lo

You should notice that the right most 0 has been removed from the register. This is because there was no place to the right to shift this value. You should also notice that there is now an empty section in the register at the left. When a binary number is shifted, the resulting empty sections are, again, filled with a 0.

lo

You already know that the first binary number converted to a denary number is 44. If you convert the binary number after the logical right shift has been performed, you get the denary number 22. This means that each logical shift to the right divides the binary number by 2. Consider another binary number:

I

1

I

1

I

1

I

1

lo

I

1

I

I

1

I

1

lo

lo

lo

lo

When a logical left shift is performed on the binary value the result is:

[1

lo

1

lo

19

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

When the first binary number is converted to a denary number, the result is 236. When the binary number is converted after the logical shift to the left has been performed, the denary value is 216. You should notice that 236 multiplied by 2 is not 216. Therefore, one of the problems with a logical shift is that data can lose its integrity as vital bits can be removed from the register. More than one logical shift can be performed on a register. For example, two logical shifts to the left can be performed. This time, each value in the register is shifted two places to the left. The binary value:

I

1

I

1

I

1

would become:

lo

I

1

lo

I

I

1

I

lo

1

1

1

lo

lo

lo

lo

lo

I

Questions 5

6

Describe what happens in a logical binary shift. Perform two logical shifts to the right on the binary number 11101100.

Negative binary numbers All the binary numbers that you have used so far have been positive binary numbers. Numbers can sometimes be negatives number though, for example, -150. How are negative numbers represented as binary? Binary only has two values that can be used, a O and a 1, so you can't just put a minus symbol (-) in front of the number, as that symbol doesn't exist in binary. Therefore, a method exists that can be used to represent negative binary numbers and it is called two's complement. Most modern computers use this method. The method of two's complement is a simple one. F irst you invert all the values in the binary number (change the ls to Os and the Os to l s), then you add 1 to the result. You can use this process to find out how the denary value -35 is represented as binary. Convert 35 to a binary number:

lo

lo

lo

I

lo

I1

I

1

I

1

lo

lo

lo

I

I

1

I

1

lo

I

lo

lo

I

I

1

I

1

I

1

I

1

1

Invert each of the values in the binary number:

Then simply add 1:

1

1

I

1

1

11011101 is the binary representation of -35 using the two's complement method.

20

)

1

Data representation

1.3 How do computers represent text, images and sound? You have already learnt that computers only process binary. This means that all data must be converted to binary to be processed by a computer. You have already looked at converting numbers, but text, images and sound all have to be converted to binary too, so they can be processed by a computer. How is this done?

Converting text to binary When a computer converts text to binary to be processed it uses a tool called a character set. There are two main types of character set that a computer can use, ASCII and Unicode. An ASCII character set represents characters using 8-bit binary numbers. This means that it can represent up to 256 characters (0 to 255). This is fine for certain languages, but some languages have an alphabet that requires more than 256 characters; therefore, Unicode was invented. A Unicode character set represents characters using 16-bit binary numbers. This means it can represent a much greater number of characters, approximately 65 000. This means that many more characters can be developed in different alphabets and also symbols such as emojis can also be used.

KEYWORD

it contains all the characters that are in that character set and the binary value that is assigned to each character.

character set:

Each character has a set binary value, for example, the letter A is 01000001.

ACTIVITY 1.2

Use the internet to find an example of an ASCII character set and a Unicode character set. What kind of different characters are represented? Are upper and lowercase letters the same? Using the ASCII table, try to decode this message: 01000011011011110100110101110000011101010111010001100101011100 100101001101 10001101101001010001010110111001100011011001010110100101110011 011001100111 01010110111000100001 Remember, each letter will be represented as an 8-bit binary number. Try writing a message for your friend to decode.

Converting images to binary

KEYWORD

An image is made up of tiny dots called pixels. If an image was simply created using the colours black and white, each pixel would be either black or white. The binary value 1 could be used to represent the colour black and the binary value 0 could be used to represent the colour white.

a very small dot of colour that is displayed with many others to create an image. pixel:

21

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

If each pixel is converted to its binary value, a data set such as the following could be created: 0011111000100000101000000011001010011000000011010001011001110010100000100 01111100 If the computer is informed that the image that should be created using this data is 9 pixels wide and 10 pixels high, it can set each pixel to black or white and create the image (See Figure 1.2). The type of data that is used to provide information, such as the dimensions and resolution of an image, is called metadata.

KEYWORDS resolution: the dimensions of an image. metadata: additional data that is stored with an image that can provide information such as the dimensions of the image and the time and date the image was taken.

Figure 1.2:

An image created just from black and white pixels

Most images use a lot more colours than black and white. Each colour has its own binary values. Colours are created by computer screens using the Red Green Blue (RGB) colour system. This system mixes the colours red, green and blue in different amounts to achieve each colour.

ACTIVITY 1.3 Use the internet to find an RGB colour scale. You should notice that each colour in the scale is first presented as hexadecimal. The first two hexadecimal values are the amount of red, the second two the amount of blue and the last two the amount of green. Practise your hexadecimal to binary conversion by converting your favourite colour to its binary value.

22

)

1

Most images are created using thousands of pixels. Each of those pixels needs quite a lot of data. Multiply that by the thousands of pixels that make up the image and that is a huge amount of data. This is why image files can often be so large in size. Each image has a resolution and a colour depth. The resolution is the number of pixels wide and the number of pixels high that are used to create the image. The colour depth is the number of bits that are used to represent each colour. For example, each colour could be represented using 8-bit, 16-bit or 32-bit binary numbers (see Figure 1.3). The greater the number of bits, the greater the range of colours that can be represented.

Data representation

KEY WORD colour depth: the number of bits that are used to create each colour in an image

If the colour depth of an image is reduced, the quality of the image is often reduced.

Figure 1.3: 8-bit colour

16-bit colour

32-bit colour

Can you see how the quality of the image is reduced in comparison to the number of bits used? If the resolution or the colour depth of an image is changed, this will have an effect on the size of the image file. If the resolution is increased, the image will be created using more pixels, so more data will need to be stored. If the colour depth of the image is increased, each pixel will need more data to display a greater range of colours so more data will need to be stored. Both will result in a larger file size for the image. lcoMPUTER SCIENCE IN CONTEXT People often have to sacrifice the quality of their images when displaying them online. This is because having files that are very large in size can take more time to download. This may frustrate users as it may mean they have to wait for a website to load, due to the number of large files it contains.

Converting sound to binary Sound is made up of sound waves. When sound is recorded, this is done at set time intervals. This process is known as sound sampling.

KEY WORD sound sampling: a little piece of sound that is recorded at regular time intervals.

23

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

15 -

, '''

"

I

,r

""O C

'' ''

6 5 - II 0

, I

l

'\

I I

2

0

3

J

''

I\.

I I

\ \ \

1

l

I

'-

5

\

I

\

'-.J

4

I I

6 7 Time samples

'

\

I I

\ \ \

, ....'" .....

I I

,,,I

I I

8

10

9

11

12

Figure 1.4: A sound wave

Figure 1.4 is an example of a sound wave. If you recorded the sound at each time sample, you would have the following set of values: Time sample Sound value

1

9

2 13

3 9

5

4

3.5

6 9

4

7 1.5

8 9

10 5

9 8

11 8

12 5.5

Each sound value is converted to binary to be processed by the computer. Each sound value is then used to playback the sound, when the recording is played. If the recorded sound wave is played it would now look like Figure 1.5: 15

""O C

,, '-', '

6 5 - II

,I

0

'' , ', __ ,,

\

I I

2

3

'' II '' II ,,

.J'\

4

5

6 7 Time samples

j ---

8

'"'"

9

,,

/

10

-

11

,....._

12

Figure 1.5: A sound wave created by playing back a recorded sound

You will notice that the two sound waves look different. This is because the number of samples taken is too far apart, so vital data in between time samples has been lost. This will result in a lack of accuracy in the sound that is recorded. Therefore, more samples need to be taken each second to improve the accuracy of the recorded sound. The number of samples taken in a second is called the sample rate. Sample rates are measured in hertz. 1 hertz is equal to 1 sample per second. A common sample rate is 44.1 khz (kilohertz), this would require 44 100 samples to be taken each second. That is a lot of data! If the sample rate is increased, the amount of data required for the recording is increased. This increases the size of the file that stores the sound. Further data is required to represent sound, and this is the sample resolution. This is the number of bits that are used to represent each sample. A common sample resolution is

24

)

KEYWORDS sample rate: the number of samples recorded each second. sample resolution:

the number of bits that are used to record each sound sample.

1

Data representation

16-bit. The higher the sample resolution, the greater the variations in amplitude that can be stored for each sample. This means that aspects such as the loudness of the sound can be recorded more accurately. This will also increase the amount of data that needs to be stored for each sample. This increases the size of the file that stores the sound.

1.4 Measuring data storage Earlier in the chapter, you learnt that all data need to be converted to digital data to be processed by a computer, and you now know how that is done for different types of data. But how is data measured when it is stored? COMPUTER SCIENCE IN CONTEXT T here are times when you will need to know the size of a data file, suc h as when you are attaching a file to an email. Most email providers have a file size limit, so you need to know the size of that file, to know if it c an be attached to your email.

Data is measured using different units, which are shown in Table 1.2. Description

Unit Bit

This is the smallest measurement for data

Nibble

There are 4 bits in a nibble

Byte

There are 8 bits in a byte

Kibibyte (KiB)

There are 1024 bytes in a Kibibyte

Mebibyte (MiB)

There are 1024 Kibibytes in a Mebibyte

Gibibyte (GiB)

There are 1024 Mebibytes in a Gibibyte

Tebibyte (TiB)

There are 1024 Gibibyte in a Tebibyte

Pebibyte (PiB)

There are 1024 Tebibytes in a Pebibyte

Exbibyte (EiB)

There are 1024 Pebibytes in an Exbibyte

Table 1.2: Data measuring units

Although most computers will calculate the size of a file for you, you need to be able to show that you can do this manually for the exam. This is just for an image file and a sound file. l[k1LLS FOCUS 1.3 CALCULATING THE SIZE OF A FILE There are several pieces of information that you need to know to calculate the size of an image file, these are:

• • •

the number of images in the file the resolution of the image the colour depth of the image.

25

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED When you know this information, you can perform a simple calculation to get the size of the image file, which is: width of image x height of image x colour depth of image x number of images in file Therefore, if you have the following information about an image file: • • •

10 images in the file image resolution is 100 x 150 colour depth is 8-bit colour,

you can calculate the size of the image file as follows: • • •

100 x 150 = 15,000 (this means there are 15 000 pixels in the image) 15 000 x 8 = 120,000 (this means that there are 120 000 bits in each image) 120 000 x 10 = I 200 000 (this means there are I 200 000 bits in the image file). You will be asked to calculate the size of an image file to a certain unit of measurement. The answer given here (1 200 000) is the number of bits that are in the image file. If you wanted to know how many bytes are in the image file, you need to divide the final answer by 8, as there are 8 bits in each byte, for example: I 200 000 -;- 8 = 150 000 bytes If you wanted to know how many kibibytes the file was, you need to divide the answer in bytes by 1024, for example: 150 000 -;- 1024 = 146. 5 KiB (to I decimal place) Questions

1

How many times would you need to divide the answer in bytes by 1024 to find the answer in Gibibytes? 2 How many pixels would there be in an image that has a resolution of 1000 x 1500? There are several pieces of information that you need to know to calculate the size of a sound file, these are: • • •

the length of the soundtrack the sample rate of the soundtrack the sample resolution of the soundtrack. When you know this information, you can perform a simple calculation to get the size of the sound file, which is: sample rate x sample resolution x length of soundtrack Therefore, if you have the following information about a sound file: • • •

length of 30 seconds sample rate of 44,100 hz sample resolution of 8 bits,

you can calculate the size of the sound file as follows: • •

26

44 100 x 8 = 352 800 (this means there are 352 800 bits per second) 352 800 x 30 = 10 584 000 (this means there are 10 584 000 bits in the sound file).

)

1

Data representation

CONTINUED You will be asked to calculate the size of a sound file to a certain unit of measurement. The answer given (10 584 000) is the number of bits that are in the sound file. If you wanted to know how many bytes are in the sound file, you need to divide the final answer again by 8 , as there are 8 bits in each byte, for example: 10 584 000-:- 8 = 1323 000 bytes If you wanted to know how many mebibytes the file was, you need to divide the answer in bytes by 1024, then by 1024 again, for example: 1323 000-:-1024-:-1024= 1.3MiB (to 1 decimal place)

1.5 Data compression

You may already have experience of having large files and struggling to have enough storage space to store them. One thing that can be done to reduce the size of a file is compression.

KEYWORDS compression: a



Not as much storage space is needed to store the file.

method that uses an algorithm to reduce the size of a file.



It will take less time to transmit the file from one device to another.

lossy: a compression



It will be quicker to upload and download the file.



Not as much bandwidth is needed to transmit the file over the internet.

method that reduces the size of a file by permanently removing data.

Compressing a file will reduce the size of the file that can have several benefits, such as:

There two type of compression that can be used, lossy and lossless. Each compresses the data in a different way. Lossy compression uses a compression algorithm that finds the unnecessary and redundant data in the file. This data is permanently removed from the file. This type of compression is mainly used on an image file or a sound file. Unnecessary data in an image file that could be removed are colours that the human eye cannot distinguish. This means that a lossy compression algorithm for an image file could reduce the size of the file by reducing the colour depth. It could also reduce the size of the file by reducing the image resolution, reducing the number of pixels used to create the image. Unnecessary data in a sound file that could be removed are sounds that cannot be heard by the human ear. It could also be the removal of softer sounds that are played at the same time as louder sounds, as humans will only hear the louder sound. The method that is used to find these kinds of sounds in a sound file is called perceptual music shaping. This is the most common type of method that is used in the file format MP3. The size of a sound file can also be reduced by reducing the sample rate and the sample resolution.

Questions

7

8 9

Why do you think lossy compression is not commonly used on text files? Will lossy compression affect the quality of an image? Why? Will lossy compression affect the quality of a sound recording? Why?

lossless: a compression method that reduces the size of a file by temporarily altering the data.

KEYWORD perceptual music shaping: a process that is used in lossy compression that removes sounds that are not normally heard by the human ear.

27

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

SELF ASSESSMENT What were the points that you thought about regarding lossy compression to answer question 7? Did you relate these points back to why lossy compression is not suitable for a text file, or did you just make points about the drawbacks of lossy compression in general? Lossless compression uses a compression algorithm to reduce the size of the file, without permanently removing any data. A common method that can be used to do this is by finding repeating data in the file and grouping this data together. For example, consider the following message: WHEN IT IS SNOWING HEAVILY LOOK OUTSIDE. LOOK OUTSIDE IT IS SNOWING HEAVILY.

Excluding the spaces between the words and the full stops, the message has a total of 62 characters. 1 character requires 1 byte of storage, so 62 bytes of storage would be needed to store this message. When you look at the message, you should notice that it consists of words that are mostly repeated. Instead of storing all 62 characters individually, the words and the positions at which they occur in the message can be stored in a lookup table, for example: Word

Position(s) in the message

WHEN IT IS SNOWING HEAVILY LOOK OUTSIDE

1 2, 10 3, 11 4, 12 5, 13 6, 8

7,9

The lookup table needs 1 byte for each character in each word and 1 byte for each position the word occurs in the message. Therefore, 33 bytes are needed to store the words and 13 bytes to store the positions, giving a total of 46 bytes. This is much less than the 62 bytes we required with our original method. No data has been lost and we have reduced our storage requirements by 26%, quite a saving! To recreate the message, the computer simply retrieves the words and places them in the positions allocated. A similar process can be applied to an image file with a lossless compression algorithm called run length encoding (RLE). This algorithm will group together repeating pixels and store how many times they occur. For example, consider the simple image in Figure 1.6:

28

)

KEY WORD run length encoding (RLE): An algorithm

that groups together repeating patterns and indexes them.

1

Data representation

Figure 1.6: A simple pixel image

If W is white, Y is yellow, R is red and G is green, RLE could compress the image into the following data: I2W, 3Y, 5W, 2Y, IR, 2Y, 3W, 2Y, 3R, 2Y, 3W, 2Y, IR, 2Y, 5W, 3Y, 7W, lG, 5W, 2G, lW, lG, lW, 2G, 4W, 3G, 7W, lG, 4W. This means that the amount of data can be reduced as pixels are grouped together and the data for each pixel does not need to be stored. The resolution of the image is stored with the data, so that the computer knows the size to recreate it when the data is decompressed. t ACTIVITY 1 .4 Why don't you try creating a simple image and writing out the RLE data for it? You could then give it to your friend, along with the image resolution, and they can have fun trying to recreate your image. Peer Assessment Ask your friend whether you got the RLE correct for your image in Activity 1.4. Ask them if you could have done anything to make your RLE any clearer. Ask them if you missed any important data.

29

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

SUMMARY Computers require any data to be converted to binary before it can be processed by the computer. Different number systems exist such as denary, binary and hexadecimal. Hexadecimal is used in computer science for uses such as aiding programmers and representing MAC addresses. Binary numbers can be added using four rules. If this creates a result greater than 255 for 8-bit binary numbers, an overflow error occurs. Logical binary shifts can be performed on binary numbers. These can shift left or shift right and can be done multiple times. This changes the binary number and can affect the accuracy of the binary number. Text is converted to binary using a character set such as ASCII or Unicode. Images are converted to binary by taking each pixel and providing it with a colour code that is converted to a binary value. The larger the resolution and colour depth of an image, the greater the amount of data that will need to be stored in the image file. This also increases the quality of the image. Sound is converted to binary by sampling the sound at a set time interval. The value of each sound sample is converted to binary. The greater the sample rate and resolution of the sound, the greater the amount of data that will need to be stored in the sound file. This also increases the accuracy of the recording. Data is measured in different units such as bits, bytes and mebibytes. Data can be compressed, using lossy or lossless compression, to reduce the size of a file. This means it will take up less storage space and it can be quicker to transmit the file.

EXAM-STYLE QUESTIONS 1 There are two different types of data, known as analogue data and digital data. a State what is meant by analogue data. [1] b State what is meant by digital data.

[1] [Total: 2]

2 Describe the difference between a denary number system and a

binary number system. 3 A music venue has a small display screen built into the top of each seat. The display screen displays the number of the seat. Each seat number is displayed as hexadecimal. a Convert the two given seat numbers into 12-bit binary values. • 21A • 90D b Write the seat number that would be displayed for the binary number 000010011100.

[4]

[4]

[ 2] [Total: 6]

4 Two registers store the given 8-bit binary values. Register 1

stores 00110111 and register 2 stores 01110011. a Add the two binary values and write the result of the calculation. Show all your working.

30

)

[3]

COMMAND WORDS state: express in clear terms. describe: state the points of a topic/ give characteristics and main features.

1

Data representation

CONTINUED b A logical left shift of three places is performed on Register 1. Write the

contents of register 1 after the logical shift has been performed.

[1]

[Total: 4]

5 Show how the value -28 is represented in binary using two's complement. Show all your working. 6 A student wants to store some images that they have taken with their digital camera. They do not have enough storage space on their external hard disk drive to store the images at their current file size. a State how the student can reduce the amount of data stored for each image. b The student has 20 images to store, that have a resolution of 150 x 250 and a colour depth of 16-bit. Calculate the size of the file that will store the images in MiB.

[2]

[1]

[3] [Total: 4]

7 A blogger displays images of their daily life on their blog. They also

have sound files of hints and tips that they record available on their blog. a The blogger compresses the images that they display on their blog. Give two benefits of compressing an image file. [2] b The blogger uses lossless compression to compress the sound file on their blog. Explain how lossless compression will compress the sound file that the blogger makes available on their blog. [4] [Total: 6] 8 Four file sizes are given. Tick ( ✓) to show which file size is the largest. File size

COMMAND WORDS show (that}: provide structured evidence that leads to a given result. calculate: work out from given facts, figures or information. give: produce an answer from a given source or recall / memory. explain: set out purposes or reasons / make the relationships between things evident / provide why and/or how and support with relevant evidence.

Tick( ✓) the largest file size

1 GiB 2033 bytes 1050MiB 1500 KiB

[1 l

SELF-EVALUATION CHECKLIST -'\fter studying this chapter, think about how confident you are with the different topics. fhis will help you to see any gaps in your knowledge and help you to learn more effectively. l'ou might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'.

31

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED

32

I can...

See topic

explain why data needs to be converted to binary to be processed by a computer.

1.1

convert between denary numbers and binary numbers.

1.1

convert between denary numbers and hexadecimal.

1.1

convert between binary numbers and hexadecimal.

1.1

provide examples of the use of hexadecimal in computer science.

1.1

explain why hexadecimal is used in computer science.

1.1

add two 8-bit binary numbers.

1.2

explain what is meant by an overflow error.

1.2

perform a logical binary shift on a binary number, including left and right shifts and multiple shifts.

1.2

use two's complement to represent negative numbers.

1.2

explain how character sets are used by a computer to represent text.

1.3

explain how pixels are used by a computer to create images.

1.3

explain how the file size of an image is affected by the image resolution and colour depth.

1.3

explain how a sound wave is sampled by a computer.

1.3

explain how the file size of a sound recording is affected by the sample rate and sample resolution.

1.3

understand how the size of a data file is measured.

1.4

calculate the size of an image file.

1.4

calculate the size of a sound file.

1.4

understand the need for data compression and the effect it has on a file.

1.5

explain how different types of data are compressed using lossy compression.

1.5

explain how different types of file are compressed using lossless compression.

1.5

)

Needs more work

Getting

there

Confident to move on

• • • • • •

learn how data is broken down into packets to be transmitted, including the contents of each packet understand how data is transmitted using a range of different transmission methods be able to choose a data transmission method for a given scenario learn about the universal serial bus (USS) interface and how it is used to transmit data learn how errors can occur when transmitting data be able to describe how a range of different error detection methods work understand why it is useful to encrypt data when it is transmitted be able to describe how data is encrypted using both symmetric and asymmetric encryption.

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

GETTING STARTED Your data is transmitted to other devices, sometimes all over the world, on a regular basis. Have you thought about how it gets there? Draw a diagram to represent how you think data travels from your device to your friend's device when you send them a message. It doesn't matter if you don't think you know how this is done, just draw what you think happens and you can see at the end of the chapter how close you were with your diagram.

DATA TRANSMISSION IN THE FINANCIAL WORLD A bank has to transmit data all around the world for thousands, possibly millions, of people on a daily basis. The accuracy of this data is imperative. Imagine what would happen if one person's hard earned money went into another person's bank account! When data is transmitted, there are certain things that can cause it to suffer errors. Interference is a big issue in data transmission that can cause errors in the data, therefore banks have to make sure that they have many error detection methods in place to make sure that data is accurate, even after transmission. As the accuracy of the data is so crucial for banking transactions, banks have to combine Figure 2.1: Financial transactions can be done on line several types of error detection, to make sure that the data has been thoroughly and completely analysed for errors. The importance of checking for errors in data transmission can costs banks a lot of money. It takes very large and powerful systems to check the millions of transactions that are made every day. However, it would cost them even more in compensation money, if they messed up the data of their customers, and possibly their money, so they put a lot of time, money and effort into the process. Discussion questions

1

How would you feel about having a bank account with a bank that did not have any error detection systems in place? What problems do you think this could cause?

2

Do you think it is right that the bank is responsible for checking errors in the transmission of data? Much of the hardware, that will be used to transmit the data from one device to another, will not be owned by them. So, why do you think the bank should be made responsible for checking for errors if the errors may occur using hardware that isn't theirs?

34

)

2

Data transmission

2.1 The structure of a data packet The amount of data that is stored in a file can be very large. If you tried to transmit this data from one device to another, all at once, this just wouldn't be possible or practical. The wires or radio waves used would simply not be able to accommodate sending such large amounts of data at a single time. Therefore, for the data in a file to be transmitted, it is broken down into very small units called packets. Each packet of data contains three different sections: Packet header Payload Trailer The packet header contains a lot of important information about the data enclosed in the packet and its destination. The information it includes is the: •

destination address



packet number



originators address.

The destination address is normally an IP address. It is the IP address of the device where the data is being sent. Without this address, the hardware transmitting the data would not know where to send the data.

KEYWORDS packet: a small unit

of data.

packet header: a section of a packet of data that contains information about the contents of the packet and its destination. internet protocol (IP) address: the

unique address that is given to a device when it is connected to a network.

Each data packet in the file is given a packet number. The packets of data may not have all been sent in the correct order, this will depend on the type of transmission used; you will learn more about this in Sections 2.2 and 2.3. This means that when the destination device has received all the data packets, it can use the packet number to put them back into the correct order to recreate the file. The originators address is also normally an IP address. It is the IP address of the device from which the data has been originally sent. So, if you send data to another device, the originator's address is the address of your device. This address isn't crucial to the transmission process, but it does help to trace where data has been sent from in situations such as illegal activity, or to simply request the original device to resend the data if an error is detected. The payload of the data packet is the actual data from the file that you are sending. The data is broken up into many small units to be sent as the payload in each packet. The trailer section of the packet is sometimes known as the footer. This contains two main pieces of information. The first is the marker to indicate it is the end of the packet and also the data for any error detection systems that are being used. You will learn more about this in Section 2.2.

Questions 1 2

Can you name the three main sections of a data packet? What information does the packet header contain?

3 4

Why does data need to be broken down into packets to be transmitted?

KEYWORDS payload: the actual data that the user is sending to the receiver. trailer: a section of

a packet of data that contains information about any error checking methods that may be used.

Which part of the data packet is the actual data from the file?

35

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

ACTIVITY 2.1 Ask your teacher if you are allowed to use a packet tracer. Your teacher may want to complete this activity together as a class. Use the packet tracer to send data to another device and look at the data that the packet tracer software provides. What kind of information does it give you? What route did your packets take to get to the destination device?

2.2 Packet switching You have learnt that data is broken down into packets to be sent from one device to another. The process of transmitting these packets is called packet switching. In this process, each packet of data is sent individually from one device to another. There could be several pathways across a network that the packets could be transmitted. Each data packet could be sent along a different pathway. A router is the device that controls which pathway will be used to transmit each packet. You will learn more about how a router does this later in the chapter. Look at the diagram of a network in Figure 2.2: Router 2

and devices that are joined together using cables or wireless technology. router: a network

Router 3

Device B

Router 4 Router 5

Figure 2.2: A network

The packets of data start at device A, they could be transmitted down any of the pathways between device A and device B. Each packet can be sent using a different pathway. When a packet reaches a router, the router decides which pathway to send the packet along next. This will continue until all the packets have arrived at device B. It is likely that the packets will arrive out of order. Once all packets have arrived, they are reordered to recreate the file.

36

)

packet switching:

a method of transmitting data packets across a network. Each data packet is able to take an individual pathway across the network. network: computers

Router 1

Device A

KEYWORDS

component that examines a data packet to obtain its destination address and then forward the packet to this address.

2

Data transmission

ACTIVITY 2.2

Five packets of data need to be sent from device A to device B. The pathway the first packet takes is: •



Router 1 Router 2.

The pathway the second packet takes is: •

• •

Router 1 Router 4 Router 5.

The pathway the third packet takes is: •

• •

Router 1 Router 3 Router 2.

The pathway the fourth packet takes is: •

• • •

Router 1 Router 4 Router 3 Router 5.

The pathway the fifth packet takes is: •

• •

Router 1 Router 3 Router 5.

Draw a copy of the diagram of a network. Use coloured pens to draw the pathway that each of the packets of data takes. Self Assessment

What did you do to check if your diagram is correct? Have you tried tracing each route to see if it goes through the correct routers?

37

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

2.3 Methods of data transmission You might think that there is only one method that can be used to transmit data from one device to another, but there are actually several. You need to understand how data is transmitted using each of these methods. These include:

• • • • •

serial parallel simplex half-duplex

KEYWORDS

full-duplex .

Serial and parallel data transmission involve the number of wires that are used to transmit the data, and how many bits of data are sent at a time.

Serial data transmission In serial data transmission, data is transmitted using a single wire. Each bit of data is transmitted one at a time along the single wire. Figure 2.3 shows an example:

Device A

,_ 1

_o_ o_

serial: a transmission method where data is sent one bit at a time down a single wire. parallel: a transmission method where data is sent multiple bits at a time down multiple wires.

Device B

Each bit of data is transmitted one at a time along a single wire

Figure 2.3: Serial data transmission

There are several advantages and disadvantages of serial data transmission, see Table 2.1: Advantages

Disadvantages

As data is sent one bit at a time, it As data is sent one bit at a time, the should arrive in order of sequence. This transmission of data is slower. means there is less chance of the data being skewed. As data is sent along a single wire, there is less chance of interference. This means there is less chance of error in the data.

Additional data may need to be sent to indicate to the receiving device when the data transmission has started and stopped. These are called a start bit and a stop bit.

Only one wire is needed for a serial transmission cable, therefore, it is cheaper to manufacture and also cheaper to buy. Table 2.1: Advantages/disadvantages of serial data transmission

38

)

KEYWORD interference:

disruption, such as electromagnetism, to data when it is transmitted.

2

Data transmission

Serial transmission has less chance of data being skewed and less chance of interference. This makes it more suitable for the transmission of data over long distances.

Parallel data transmission In parallel data transmission, data is transmitted using multiple wires. Multiple bits of data are transmitted along each wire at the same time. Figure 2.4 shows an example:

---- --0

1-1

Device A

-o

0-1

1

1-1

1

1 o-o 1 1 -o 1 -o -o 0-1 - 1

ooo-

1-

Device B

oo-

1-

Multiple bits of data are transmitted at the same time, along multiple wires Figure 2.4: Parallel data transmission

There are several advantages and disadvantages of parallel data transmission, see Table 2.2: Advantages

Disadvantages

As data is sent multiple bits at the same time, the transmission of data is quicker.

As data is sent multiple bits at the same time, bits do not arrive in order and need to be reordered after transmission. This increases the risk of the data being skewed. As data is sent along multiple wires, there is more chance of interference. This means there is more chance of error in the data.

Many computers and devices use parallel data transmission to transmit data internally. Therefore, there is no requirement to convert this to serial data transmission to transmit the data across a network.

Multiple wires are needed for a parallel transmission cable, therefore, it is more expensive to manufacture and also more expensive to buy.

Table 2.2: Advantages/disadvantages of parallel data transmission

Parallel transmission has an increased chance of data being skewed and an increased chance of interference. This makes it more suitable for the transmission of data over shorter distances. This is often limited to approximately 5 metres.

39

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Question 5

A marketing company prints leaflets to deliver to people's houses. The leaflets are designed on a computer and sent to a large printer that is 3 metres away. Large numbers of leaflets need to be printed in a short period of time, to makes sure that they are ready for delivery. Would you use a serial or a parallel data transmission cable to connect the computer to the printer? Why would you choose this type of cable?

Simplex, half-duplex and full-duplex transmission involve the direction in which the

data is transmitted.

Simplex data transmission In simplex data transmission, data is transmitted from one device to another in one direction only. Figure 2.5 shows an example:

Device A

Device B

KEYWORDS simplex: a transmission method where data is transmitted in a single direction only. half-duplex: a transmission method where data is transmitted in both directions, but only one direction at a time. full-duplex: a

Figure 2.5: Simplex data transmission

You would only use this type of data transmission when there is no need to send data both ways between the devices. One example is connecting a keyboard to a computer. Simplex data transmission can be used to do this as data only needs to be sent from the keyboard to the computer, so that the computer screen can display the keys that are pressed. There is no reason why the computer would need to send data to the keyboard, so a simplex data transmission connection is used.

Figure 2.6: Simplex data transmission is used between a computer and a keyboard

40

)

transmission method where data is transmitted in both directions at the same time.

2

Data transmission

Half-duplex data transmission In half-duplex data transmission, data can be transmitted in both directions between the devices, but only one direction at a time. Figure 2.7 shows an example:

Device B

Device A

�---------------------- - -If data is being transmitted from Device A to Device B, then data cannot be transmitted from Device B to Device A, at the same time.

-------------------------➔

Device A

Device B

If data is being transmitted from Device B to Device A, then data cannot be transmitted from Device A to Device B, at the same time.

Figure 2.7: Half-duplex data transmission

You would use this type of data transmission when you need to send data in both directions between the devices, but there is no requirement for this to be at the same time. It can also be used when the communication between two devices needs to have a high level of performance. This is when two half-duplex connections can be set up between devices to allow data to be transmitted in both directions at the same time, but using two different channels of communication. Can you work out how this would be set up? l ACTIVITY 2.3 Use the internet to research how half-duplex data transmission is used to create a Wi-Fi connection. Why is half-duplex, rather than full-duplex data transmission used in Wi-Fi connections?

Figure 2.8: Wi-Fi uses half­ duplex data transmission

Full-duplex data transmission In full-duplex data transmission, data can be transmitted in both directions between the devices, at the same time. Figure 2.9 shows an example:

41

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Device A

Device B

Figure 2.9: Full-duplex data transmission

You would use this type of data transmission when it is essential for data to be both sent and received by each device, at the same time. One example is a telephone conversation. The person speaking into Device A can speak at the same time as the person speaking into Device B. It may be a little bit of a chaotic conversation if you both try and speak at the same time all the time though! However, during most conversations, people do sometimes speak at the same time, so full-duplex data transmission is needed. When a connection is created between two different devices it will either be a serial or parallel data connection. It will also be a simplex, half-duplex or full-duplex connection. This means that a connection can be, for example, a serial simplex connection, or a parallel half-duplex connection, or possibly a serial full-duplex connection. You need to understand when each of the different methods of transmission are most suitable.

Questions

Which method of data transmission sends data along a single wire? 7 Which method of data transmission sends data multiple bits at a time? 8 If a data transmission connection sends data one bit at a time, in both directions, but not at the same time, what kind of data transmission methods are used? 9 What are two advantages of serial data transmission? 10 What are two disadvantages of parallel data transmission? 11 A business manager transmits data about its customers to a central file server. The file server is 100 metres away from the business manager's office. They need to be able to send and receive customer data to and from the server, at the same time. The accuracy of the customer's data is imperative. Which methods of data transmission should be used to create the connection between the business manager's computer and the file server? Why would you choose those methods? 6

ACTIVITY 2.4

Write a data transmission scenario like the one given in Question 11. Think about which data transmission methods could be used for your scenario and why they would be the most suitable. Peer Assessment

Give the scenario to a friend and ask them which data transmission methods they would use. Are they the same methods that you thought should be used? If you have chosen different methods, discuss and come to an agreement about which methods should be used. If you chose the same methods, see if you had the same reasons for choosing those methods.

42

)

2

2.4 The universal serial bus (USB) interface The concept of USB can be a little confusing, as it is used to describe several aspects. You may have heard of a USB connection, a USB cable, or maybe you call a storage device 'a USB'. You need to understand the difference between several of these aspects. A USB interface includes items such as a USB port, a USB cable, a USB connection and a USB device. A USB device, such as a USB memory stick, is a device that uses the USB interface. It plugs into a USB port on a computer and it transmits data using a USB connection. A USB cable can be used to connect devices, such as a mouse, to a computer. A USB connection uses serial data transmission to transmit data between the devices. However, it a special type of serial data transmission connection that is used that is designed to transmit data at high speeds.

ACTIVITY 2.5

Data transmission

KEYWORDS USB: an industry standard that is used to transmit data. USB port: a socket that is a part of a device or computer that enables you to insert a USB cable. USB cable: a type of transmission media that uses the USB method to transmit data.

COMPUTER SCIENCE IN CONTEXT

USB connection: a collective name for using a USB cable plugged into a USB port to transfer data from one device to another.

Many devices are connected using a USB cable. This is because the USB interface is an industry standard, which means that manufacturers don't need to worry about compatibility issues when connecting devices. One of the most recent versions of the USB interface to be released is USB 4.

USB device: the name of a device that plugs into a USB port on a computer.

ACTIVITY 2.6

ethernet: another type of connection that can be used to transmit data within a network.

One of the issues with serial data transmission is the transmission speed is slower than parallel. Research how a USB connection is able to transmit data at a faster rate.

Research the data transfer speed of USB 4; is this different to USB 1, 2 and 3? What other differences can you find between the different versions of USB?

There are several advantages and disadvantages of the USB interface, see Table 2.3: Advantages

Disadvantages

It is a simple interface. The USB cable to device can only fit into the USB one way. Therefore, it means less errors in connecting devices are likely to be made.

The length of a USB cable is limited, normally to 5 metres.

The speed of a USB connection is relatively high, so data can be transferred quickly.

The transmission speed is relatively high for a USB connection, but it isn't as high as other types of connection, such as ethernet. (continued)

43

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Advantages

Disadvantages

The USB interface is a universal standard for connecting devices, therefore a USB port is included in many different devices. When a USB device to cable is inserted into a USB port, it is automatically detected. The first connection will normally involve the download of drivers to operate the hardware that has been connected. Each connection after this the driver should not need to be downloaded again. A USB connection can also be used to power a device, so it does not need another power source. It can also use this to charge a device, such as a mobile phone. Table 2.3: Advantages/disadvantages of the USB interface

Questions 12 What does USB stand for?

13 What type of data transmission method does a USB interface use?

14 What are two advantages of using the USB interface?

15 Can you name five devices that are connected using a USB interface?

16 What is the length a USB cable limited to? Can you think why it is limited to

this length?

2.5 Detecting errors in data transmission

The transmission of data from one device to another is often not a perfect process. In the process of transmitting the data, interference can occur. This can cause data to be lost, data to be gained and data to change. This would not be helpful and could also lead to many issues. If a password wasn't transmitted correctly, then that person may not be able to log into their account. If a person's address wasn't transmitted correctly, they may not get email that needs to be sent to them. If a person's details are not transmitted correctly to a company, they may not get a product or service that they order. The accuracy of data is often vital, therefore there needs to be a procedure in place to detect any errors in data so that actions can be taken to correct this.

44

)

Figure 2.10: Procedures need to be in place to handle errors in data transmission

2

Data transmission

There are several error detection methods that can be used, these include: •

parity check



checksum



echo check.

Each of these methods is designed to check for errors after the data has been transmitted from one device to another.

Parity check

KEYWORD

A parity check can use an odd or even check method. Each byte of data has 7 bits and 1 extra bit that is called a parity bit (see Figure 2.11). The parity bit is normally the first or last bit of data in the byte.

G

o o , o o o ,

/�

Parity bit

parity check: a type of error detection method that adds an additional bit to each byte to create an odd or even sum.

7 bits of data

Figure 2.11: The parity bit is the first bit of data in this byte

Before transmission begins, the parity check is set to be either odd or even parity. The number of l s in the 7 bits of data is totalled. In the example in Figure 2.11, the result of that would be 2. If an odd parity check is used, then a 1 is added as a parity bit. This is because all the l s in the byte now add up to 3, which is an odd number. If an even parity check is used a parity bit of 0 would have been added instead. This is because all the l s in the byte would then add up to 2, which is an even number. When the parity bit has been added to each byte, the data can be transmitted. After transmission, the receiving device will check each byte of data for errors. If an odd parity check has been used and the device finds a byte that has an even number of l s, then it knows that an error has occurred with this byte of data. The error is detected!

Questions

17 Which of these bytes would have been transmitted incorrectly if an even parity

check has been used? a 10111011 b 01110111 C 10101000 18 Which of these bytes would have been transmitted incorrectly if an odd parity check has been used? a 00110001 b 10110101 C 10001000 19 Can you think of an instance in which an error could occur in the data, but this would not be detected by a parity check?

45

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Checksum A checksum uses a calculated value to check for errors. A value is calculated from the data that wi11 be transmitted, before transmission takes place. A method such as modulus 1 1 could be used to calculate the value.

ACTIVITY 2.7 Use the internet to find out how the modulus 11 method calculates a value from the data. You do not need to be able to remember how to do this method of calculation for the exam, but it will help you to know how a checksum is calculated.

KEYWORD checksum: a

type of error detection method that performs a calculation on the data to create a checksum value. Checksum values are compared after transmission to see if they match.

Once the checksum value has been calculated it is added to the data to be transmitted with it. After transmission, the receiving device uses the same method to calculate a value from the received data. If the values match, then the device knows that no error has occurred during transmission. If the values do not match, the device knows that an error has occurred during transmission. The error is detected!

Questions 20 What is the checksum value calculated from?

What happens to the checksum value when it has been calculated before transmission? 22 Why would checksum values that do not match show that an error has occurred?

21

Echo check

KEYWORD

An echo check involves a simple comparison of the data sent to the data received. The sending device transmits the data to the receiving device. The receiving device then transmits the data it receives back to the sending device. The sending device compares the data it sent to the data it has received back from the receiving device to see if they match. If they do, then no error has occurred. If they don't match, then the sending device knows the data was received with error. The error is detected!

echo check: a type

Draw a diagram to represent how an echo check detects errors in data.

Question 23 If the data does not match that which is sent back by the receiving device, wi11 this

always mean that the receiving device did not receive the data correctly? How do you know that?

46

)

of error detection method that sends a copy of the transmitted data back to the sender to be compared with the original data sent.

2

Data transmission

Automatic repeat request (ARO) When an error has been detected after the data is transmitted, it is likely that the data will need to be retransmitted. Either the sending device will need to ask the receiving device if it received the data correctly, or the receiving device will need to tell the sending device it did or did not receive the data correctly. This will allow the data to be retransmitted if necessary.

KEY WORDS

A method called automatic repeat request (ARQ) can be used to do this. There are two main ways that an ARQ can operate and each method uses either a positive or negative acknowledgement and a timeout.

automatic repeat request (ARQ): a type of

In a positive acknowledgement method: •

The sending device transmits the first data packet.



The receiving device receives the data and checks it for errors.



Once the receiving device knows it has received the data error free, it sends a positive acknowledgement back to the sending device.



When the sending device receives this positive acknowledgement, it knows the receiving device has received the data packet error free and it sends the next data packet.



If the sending device does not receive a positive acknowledgement within a set timeframe, a timeout occurs.



When a timeout occurs, the sending device will resend the data packet. It will keep doing this when a timeout occurs, until it receives a positive acknowledgement, or sometimes a limit (such as 20 times) is set and when this limit is reached it will stop resending the data. ACTIVITY 2.9

error detection method that uses acknowledgement and timeout to see if data has arrived correctly after transmission.

acknowledgement: a

message that is sent from one device to another to indicate whether data is received correctly.

timeout: a period of

time that is set and used to wait for an acknowledgement to be received.

Draw a diagram to represent how an ARO system operates using positive acknowledgement. In a negative acknowledgement method:

• • • •

The sending device transmits the first data packet.



If the sender receives a negative acknowledgement, it knows this means the data was received incorrectly, so it can resend the data packet.



The receiving device receives the data packet and checks it for errors. If the receiving device detects no errors, no further action is taken. If the receiving device does detect errors, it will send a negative acknowledgement back to the sender.

A timeout is set by the sending device when it sends the data. This is just so that the sending device knows that if it doesn't receive a negative acknowledgement back within that set time period, it doesn't need to be still be waiting for it and can send the next data packet.

47

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

ACTIVITY 2.10

REFLECTION

Draw a diagram to represent how an ARO system operates using negative acknowledgement.

After completing activities 2.8, 2. 9 and 2.10: How have you made sure that your diagrams for an echo check and both ARO methods are correct?

Check digit You have learnt that errors, such as data loss, data gain and data being changed can occur when data is transmitted. You now know that these errors normally occur due to interference. It is also possible for errors to occur when data entry is performed. This could be manual data entry, for example, a human typing in a value, or it could be automatic data entry, for example, a barcode scanner scanning a barcode to obtain the data stored in the barcode. A method is necessary to check for errors with data entry and this method is called a check digit. This is how a check digit operates: •

A check digit value is previously calculated from the data that will be entered at some point, for example, a barcode number or an ISBN number. This number is stored with the data.



When the data is entered, for example, the barcode is scanned, the check digit is recalculated from the data entered.



If the previously calculated check digit and the stored check digit match, the data entered is correct.



If the previously calculated check digit and the stored check digit do not match, the data entered is incorrect.

Although the process is similar, you should not confuse the operation of a check digit and a checksum. Make sure that you take the time to understand the difference between the two. ACTIVITY 2.11 With a partner, discuss and write down the differences between a check digit and a checksum.

COMPUTER SCIENCE IN CONTEXT Companies will normally combine several error checking methods to make sure that the data they transmit and receive is error free. This means that the data can be checked in several ways to make sure that any error that could occur is being checked. This is because the data that many companies use is vital to their business, they want to do everything they can to make sure that it does not contain any errors caused by transmitting the data.

48

)

KEYWORD check digit: a type of error detection method that is used for data entry. A calculation is performed on the data entered to create a value. Check digit values are compared to see if the data entered is correct.

2

Data transmission

2.6 Encryption

You have learnt a lot about how data is transmitted in this chapter. You have also learnt why it is important for data to be received correctly and how errors can be detected to make sure this happens. You also need to understand that the data that is transmitted often needs to be protected during transmission. This is because data is valuable, especially when it contains our personal details and information that is personal to us. A hacker may try and steal the data during transmission so that they can use it for their own gain. One method of protection that can be used when transmitting data is encryption. Data before encryption takes place it is called plain text. An encryption algorithm, called an encryption key, is used to scramble the data and make it meaningless. This meaningless data is called cipher text. The cipher text can then be transmitted from one device to another. The receiving device uses the key to decrypt the cipher text and return it to its plain text form. This means the data will have meaning again if read. One important thing to note about encryption is that is does not stop a hacker stealing the data that is transmitted. It just means that the data that is stolen will be meaningless, as it will be encrypted and therefore scrambled. They will not understand any of the data in the file. There are two main methods of encryption that can be used symmetric and asymmetric. The process for symmetric encryption is: •

Plain text is encrypted into cipher text using an encryption key.



The cipher text and the encryption key are sent separately to the receiving device.



The same key is then used to decrypt the cipher text back into its plain text form.

KEYWORDS encryption: a

method of securing data for storage or transmission that scrambles it and makes it meaningless.

plain text: the name

given to data before encryption.

encryption key: a

type of algorithm that is used to encrypt data.

cipher text: the

name given to data after transmission.

This is the simplest method of encryption and is still used for data that is not of a high level of importance. It is sometimes used by people just wanting to encrypt the data that they store on their own computer or external storage device, as it isn't being transmitted across a network . However, people began to worry that it could be too easy for a hacker to intercept both the cipher data and the encryption key if it is sent across a network, or the internet, so a more secure method was developed called asymmetric encryption.

symmetric: a type

The process for asymmetric encryption is: • Plain text is encrypted into cipher text using a public key. This is also a type of encryption algorithm. • The cipher text is transmitted to the receiving device.

of encryption that uses two different keys to encrypt and decrypt data.



of encryption that uses the same key to encrypt and decrypt data.

asymmetric: a type

The cipher text cannot be decrypted using the public key, it is decrypted using a private key.

A person who uses an asymmetric method of encryption has a public encryption key. This is called a public key because it is made public for the encryption process. Making something public means that anyone can see and use it. Any device that wants to send you encrypted data may obtain your public key and encrypt the data using your public key. You also have a private key. Any encrypted data that your device receives that has been encrypted with your public key can be decrypted with your private key. They act as a pair. Your private key is always kept private though, your device does not make it available to any other unless authorisation is given to do so.

49

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

The process can work in reverse as well (a private key is used to decrypt and a public key is used to decrypt), and this is what can occur in processes such as digital signatures. These are used in security protocols such as SSL (secure sockets layer). You will learn more about these in Chapter 5, about applications of the internet. COMPUTER SCIENCE IN CONTEXT A bank uses asymmetric encryption for all the banking transactions that are completed on a daily basis. As you can imagine, the data that is transmitted for these banking transactions is very sensitive and personal data, so the bank has to make sure that they use a very secure method of encryption for this process.

Questions

24 What is the name given to an encryption algorithm? 25 What is the name given to data that has been encrypted? 26 Does encryption stop data being stolen by a hacker? Why or why not? 27 Why is asymmetric encryption a more secure method of encryption than symmetric?

SUMMARY Data is broken down into packets to be transmitted from one device to another. Each packet contains three parts: the packet header, the payload and the trailer. The packet header includes the destination address, the packet number and the originator's address. The payload is the data the sender wants to transmit. The trailer contains data such as the error detection method to be used. A process called packet switching can be used to send the data from one device to another across a network.

Data is transmitted using serial or parallel transmission. Data is also transmitted using simplex, half-duplex or full-duplex transmission. An interface called USB can be used to transmit data. This is often used to connect hardware such as a keyboard to a computer. Errors can occur when transmitting data due to interference. Methods are required to detect any errors in transmission. A parity check is an error detection method that uses a parity bit to detect errors. An odd or even parity check method can be used. A checksum is an error detection method that uses a calculated value to detect errors. An echo check compares data that is sent and received to see if they match, to detect errors.

50

)

2

Data transmission

CONTINUED An ARQ can be used to monitor whether data is received correctly after transmission. A check digit is an error detection method that is used for data entry. Data can be encrypted to keep it secure during transmission. Encryption can be performed using a symmetric or asymmetric method. Symmetric encryption uses the same key to encrypt and decrypt the data. Asymmetric encryption uses different key, a public and a private key, to encrypt and decrypt the data.

EXAM-STYLE QUESTIONS 1 2 3

4

5

6

COMMAND WORDS

Identify two items of data that would be included in the header of a packet of data. Explain why and how packets of data are reordered after packet switching has been used to transmit data across a network. Describe how data is transmitted using serial half-duplex data transmission. Give two benefits of using the USB interface to connect hardware devices to a computer. A company has a central file server that is located 500 m away from the main office where employees work at their computers. Employees send and retrieve files to and from the file server on a daily basis, often at the same time. Identify the type of data transmission that would be most suitable for the given context. Explain why this would be the most suitable method of transmission. Four statements are given about error detection methods. Tick (✓)to show which statement applies to which error detection method. Some statements may apply to more than one error detection method. Statement

This method checks for errors in data after it has been transmitted. This method can use an odd or even process. This method sends data back from the receiver to the sender to compare the data to check for errors. This method uses a value that is calculated from the data to check for errors.

Checksum

Echo check

[2] [2] [4] [2]

[6]

[4]

Parity check

identify: name/ select/ recognise. explain: set out purposes or reasons / make the relationships between things evident/ provide why and/ or how and support with relevant evidence. describe: state the points of a topic/ give characteristics and main features. give: produce an answer from a given source or recall/ memory.

51

)

CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED 7 The given paragraph describes how data is encrypted using

symmetric encryption. Complete the missing terms in the paragraph using the given list. Not all terms need to be used. • a different • cipher text • decrypted • encrypted • key • lock • meaningless • plain text • the same • understandable Before encryption the data is known as .............................. . This data is encrypted using an algorithm that is known as a .............................. . After the data has been encrypted it is known as .............................. . This type of data is scrambled and .............................. if it is stolen. When the data is received it is .............................. using .............................. encryption algorithm. [6]

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'.

52

I can...

See topic

describe the structure of a packet of data.

2.1

describe the process of packet switching.

2.2

describe how data is transmitted using serial and parallel data transmission.

2.3

describe how data is transmitted using simplex, half-duplex and full-duplex data transmission.

2.3

choose a suitable data transmission for a given context and explain why that is the best method of data transmission.

2.3

)

Needs more work

Getting there

Confident to move on

'

2

Data transmission

CONTINUED I can ...

See topic

describe how data is transmitted using the USB interface.

2.4

explain how errors can occur during data transmission.

2.5

describe how a parity check uses a parity bit to detects errors.

2.5

describe how a checksum value can be used to detect errors.

2.5

describe how an echo check compares data to detects errors.

2.5

describe how an ARQ can monitor if data is received correctly.

2.5

describe how a check digit can be used to detect errors involving data entry.

2.5

explain why data may need to be encrypted.

2.6

describe how data is encrypted using symmetric encryption.

2.6

describe how data is encrypted using asymmetric encryption.

2.6

Needs more work

Getting there

Confident to move on

53

)

develop an understanding of the role of the central processing unit (CPU) in a computer, including the fetch-decode-execute cycle •

learn the role of each of the components in a CPU that has a Von Neumann architecture



develop an understanding of what an embedded system is and be able to identify devices in which they are used



understand what an input device and an output device is and why they are needed



learn the role of a sensor and the purpose of a range of different sensors , including how they capture data



learn the role of random access memory (RAM) and read only memory (ROM)



learn the role of secondary storage including the operation of the different types



develop an understanding of virtual memory and how it is created



learn how cloud storage is used and the advantages and disadvantages of storing data in the cloud



study the main components and types of address that are used when connecting a computer to a network.

3

Hardware

GETTING STARTED Describe to a partner how you think a computer processes an instruction. Ask your partner how they think a computer processes an instruction. Do you both agree? If not, discuss the differences you have and come to an agreed process and write this down. You can check at the end of the chapter how accurate your initial understanding was.

THE INTERNET OF THINGS The use of computer hardware has become a major part of our daily lives. Have a quick think about how many pieces of computer hardware that you use in a day. You might find it's as many as 10 or more pieces of hardware! It is now possible to get many devices for our home that have computer hardware built into them. Can you think of any in your house? We often refer to household devices that have computer hardware built into them as smart devices. It is possible to buy a smart refrigerator. This has features such as scanning and keeping a list of all food in the refrigerator. You can quickly and simply view what is available and when it might go out of date. Think about how that could reduce food waste! Smart refrigerators are also capable of keeping a list of items that are regularly used and can even keep a groceries list and use the internet to order items as they are required. They can also provide you with recipe ideas for the ingredients that you have. How awesome is that! We have to think about so many different things in our lives, so having assistance that can keep track of simple needs like this, people often find very helpful. When people use smart devices, such as a smart refrigerator, it is often possible to connect them with other devices they own, such as their mobile telephone. This way they could get a list of what is in their refrigerator, when away from home, and can easily find out what they need to buy from the shop. The connecting of hardware devices in this way is called the Internet of Things.

KEY WORD Internet of Things: the connection of computer systems and everyday devices, using the internet, to allow data to be exchanged.

Figure 3.1: Smart refrigerators are part of the Internet of Things

55

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED

KEYWORDS

Discussion questions

central processing unit (CPU): a

1

What kind of feature would you include in a smart refrigerator that you would find helpful?

2

Can you see any problems that might arise as a result of connecting devices and the development of the Internet of Things?

3

Work with a partner and design your own smart device. What would you want it to do? What computer hardware would it need?

3.1 The role of the CPU

The CPU (central processing unit) is one of the fundamental parts of a computer. Many people say it is the most important part, as it is where all the data and instructions are processed. This means it is a little bit like your brain, as that is where you process all the data and instructions that you sense on a daily basis. All computers have a form of CPU. In devices such as personal computers (PC) and laptops, this is normally a separate component in the computer. In devices such as those found in our houses, e.g. our washing machine, a similar type of component exists called a microprocessor. This performs a similar role to a CPU, but on a smaller scale. Whereas a CPU can process thousands of complex instructions, a microprocessor will process a much more limited set of instructions. A general purpose computer, such as a PC or a laptop, has a CPU and is able to perform a wide variety of tasks. A microprocessor is often built into a system that is designed to perform a very specific task. This type of system is called an embedded system. There are examples of embedded systems in many different areas of our lives, for example, a traffic light, a washing machine and a digital alarm clock. When an instruction is processed by a computer, the method that is used to do this is called the fetch-decode-execute cycle. You need to understand what happens in the different stages of the cycle and which components are used. You'll learn some interesting information about how a computer works. How exciting! You will learn the operation of the architecture of a Von Neumann computer system, which is one of the most common types of modern architecture for a computer system.

Figure 3.2: A CPU chip

56

)

component in a computer system that processes data and instructions.

microprocessor: an integrated circuit that is able to perform many of the functions of a CPU. embedded system: a computer system that performs a dedicated function. fetch-decode­ execute cycle: the

cycle through which data and instructions are processed.

architecture: the design of a computer system, including the components it contains.

3

Hardware

ACTIVITY 3.1 Use the internet to research who Von Neumann was and why he developed the Von Neumann architecture. This is a basic representation of the fetch-decode-execute cycle: Fetch: This is the stage where the instruction is fetched into the CPU

KEYWORDS input device: a

device that allows data to be entered into a computer system.

Figure 3.3: The fetch-decode-execute cycle

Individual processes happen at each of these stages, using different components, to carry out the cycle. So, what happens at each stage? We will explore this in the next sections.

3.2 The fetch stage

Data and instructions are given to the computer through the use of input devices. You will learn about these later in the chapter. When the data and instructions are input, they are stored in RAM (random access memory). If a user wants to open a file that is stored on the hard drive, this data will be brought from the hard drive into the RAM, also. In order for the data and instructions to be processed, they need to be brought from the RAM into the CPU. This is what happens at the fetch stage of the cycle. A component within the CPU, called the program counter (PC), stores an address. This component is an example of a register. The address stored by the PC is the address of the next instruction that needs to be processed. The details of this address will be a location within the RAM. This address stored in the PC needs to be sent to another component in the CPU called the memory address register (MAR). This is another example of a register in the CPU. The address is transported from the PC to the MAR using the address bus. Once the MAR has received the address it now knows where to find the instruction in the RAM. To retrieve the instruction the MAR needs to send the address to the location in RAM. It uses the address bus again to do this. Once the address is received at the location in RAM, the data stored in this location, e.g. the instruction, is sent to a

RAM (random access memory): a

component in the CPU that holds data and programs that are currently in use. hard drive: a storage

device that stores data permanently, until it is deleted by the user.

program counter

(PC): a component in

the CPU that stores the address of the next instruction to be processed. address: a memory location in RAM. memory address register (MAR): a

component in the CPU that holds the address of the data or instruction to be located in RAM. address bus: wires used for the trans­ mission of addresses between components in a computer.

57

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

component within the CPU called the memory data register (MDR). This is also an example of a register in the CPU. The instruction is sent to the MDR using the data bus. When the MDR has received the instruction, it sends it to the current instruction register (CIR). This is another example of a register in the CPU. The MDR uses the data bus to send the instruction to the CIR. This register is part of a component within the CPU called the control unit (CU). It is the CU that is responsible for the next stage of the cycle, the decode stage. Figure 3.4 shows the operation of the fetch stage of the cycle:

I I I

CPU

ADDRESS BUS

I

I

RAM

MAR

I I

ADDRESS BUS

MDR

I I

DATA BUS

cu CIR

I

PC

,__

I

DATA BUS

Figure 3.4: How the fetch stage operates

ACTIVITY 3.2 Draw a diagram like the one given in Figure 3.4 to see if you can draw and label the process for the fetch stage of the cycle.

3.3 The decode stage The decode stage of the cycle begins when the instruction is received by the CU. The CU is the unit in the CPU that decodes the instruction. The instruction needs to be decoded so that the CPU can understand what is required to execute the instruction. To decode an instruction the CU uses an instruction set. This is a set of all the commands that are understood and can be processed by the CPU. These commands are in machine code. Once the instruction is decoded using the instruction set, it can now be executed.

3.4 The execute stage

The execute stage is when any actions that are required for the instruction are carried out. This is likely to involve some mathematical and logical calculations. If these kinds

58

)

KEYWORDS memory data register (MDR): a

component in the CPU that holds the data or instruction that are fetched from RAM.

data bus: wires used for the transmission of data and instructions between components in a computer. current instruction register (CIR): a register that is built into the CU that holds the current instruction that is being processed in the CPU.

control unit (CU):

the component in the CPU that controls all the operations in the CPU.

instruction set: a set of commands that can be processed by a certain CPU.

3

of calculations are required, the data used in the process is sent to the arithmetic logic unit (ALU). This is a component within the CPU that is responsible for any calculations. Interim values may be created whilst these calculations are being performed, the ALU has a special register built into it called the accumulator (ACC). It is this special register that will store the interim values that are created in any calculations. Once any calculations have been performed, the actions for the instruction can be performed, e.g. the file can be opened or the letter typed can be displayed. How do all the different components know what they are doing in the fetch-decode­ execute cycle? They have a conductor! This conductor is the CU. It sends signals to all the components within the CPU to tell them when they need to perform their different roles. The CU uses the control bus to send these signals. ACTIVITY 3.3 Add the ALU and the ACC to your diagram (from Activity 3.2) then label it to show the process for the decode and execute stages of the cycle. Peer Assessment Exchange diagrams from Activities 3.2 and 3.3 with a friend and use the description of the fetch-execute-decode cycle to check whether their diagram is correct.

Questions

1 2

3 4 5

Hardware

KEYWORDS arithmetic logic unit (ALU): the component in the CPU that performs all the mathematical and logical operations required when processing data and instructions. accumulator (ACC): a register that is built into the ALU that stores the result of any interim calculations. control bus: wires used for the transmission of control signals between components in a computer.

Where is data stored before it is fetched into the CPU? Which component in the CPU is responsible for making sure the fetch-decode­ execute cycle is performed correctly? What is the role of a bus? Why does the ALU need the ACC? What would have to happen if it didn't have this special register? Copy the table below and fill in a description for each component in the CPU: Component

Description

Program counter (PC) Memory address register (MAR) Memory data register (MDR) Control unit (CU) Current instruction register (CIR) Arithmetic logic unit (ALU) Accumulator (ACC) Address bus Data bus Control bus

59

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

3.5 Factors that can affect the performance of a CPU The performance of a CPU refers to how quickly the CPU can process an instruction. This is important as the more instructions that can be processed in a second, the higher the performance of the CPU. Users often want a high performing CPU, so they are not sat waiting and frustrated with their computer because it takes too long to open a document, for example. There are three main factors that can affect the performance of a CPU and this is the number of cores it contains, the clock speed and the size of the cache. A single core in a CPU contains all the components that you have learnt that are used to perform the fetch-decode-execute cycle. Therefore, if a CPU has one core, it can perform one fetch-decode-execute cycle at a time. If a CPU has two cores (this is often called a dual core processor) it can perform two fetch-decode-execute cycles at the same time, one on each core. Some CPUs have four cores (this is often called a quad core processor) and can perform four fetch-decode-execute cycles all at the same time. Imagine completing a task: if you can only do one thing at a time to complete the task, it might take you quite a long time but if you could do four things at once to complete the task, you will complete it much quicker. Therefore, if a CPU has multiple cores, its performance can be increased. Multiple cores also allow a computer to multitask. If it can process more than one instruction at a time, it can perform more than one task at a time.

KEYWORDS core: the part of the

CPU that contains all the components that are used to perform the fetch-decode­ execute cycle.

clock speed: the number of fetch­ decode-execute cycles that can be performed in a second. cache: a type of

storage that is built into the CPU, to store the most frequently used data and instructions.

Figure 3.5: Multiple cores allow a computer to multitask

60

)

3

Hardware

ACTIVITY 3.4 The performance of a CPU is not always increased by the addition of more cores. Use the internet to find out why the performance may not always be increased.

A CPU contains an internal clock that controls the speed at which instructions are processed. The speed is measured in hertz. A CPU that has a clock speed of 1 hertz is able to process one instruction per second. If your CPU had a clock speed of 1 hertz you'd be waiting rather a long time for any tasks to be completed! Most modern computers have a clock speed that is measured in gigahertz (GHz). A CPU with a clock speed of 2 GHz can process 2 billion instructions a second. That is definitely a busy CPU! If a computer has two cores, each core can process 2 billion instructions a second. ACTIVITY 3.5 It is possible to change the speed of a CPU using overclocking. Use the internet to find out what is meant by overclocking.

A CPU also contains a cache. The cache is a type of data storage within the CPU. Instructions and data that the computer uses most can be stored in the cache. This means that the CPU doesn't need to fetch this data from the CPU, just from the cache, so that process will be quicker. If the CPU can get the data and instructions quicker, the performance of processing those instructions will improve. If a computer has a larger cache, so it has more storage space to store the instructions and data it uses most, then it can store more of them, so will need to spend less time going to the RAM. COMPUTER SCIENCE IN CONTEXT Some people need very powerful processors in their computer, as they need to process a lot of data in a very short time period. One example would be an architect. They need to be able to use a computer to create a 3D model of their building design. It takes a lot of data to render these models, so a very powerful processor is needed to do this. 'Render' simply means to make the model. The computer does this by putting it together bit by bit.

Questions 6 7 8

Which CPU can process more instructions at the same time, a quad core or a dual core? How many instructions per second can a dual core 2.4 Ghz CPU process? If the cache size of a CPU is too big, this can actually have a negative effect on the performance of the CPU. Why might this happen?

61

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

3.6 Input and output devices You now know how a computer processes data, but how does it receive that data and how do we see the result of the processing? This is possible through the use of input and output devices. An input device is any device that allows data to be entered into a computer system. This data could take many forms including text, images and sound. Common examples of input devices are: •

barcode scanner



digital camera



keyboard



microphone



optical mouse



QR code scanner



scanner (2D and 3D)



touch screen (resistive, capacitive and infra-red).

Copy the table below that includes the examples of the input devices. For each input device, describe the kind of data that it allows to be input and give an example of when it is used. The first one has been done for you. Input device

Description of data input Example of use

Barcode scanner

It scans a barcode so that the data stored in the barcode can be obtained.

Digital camera Keyboard Microphone Optical mouse QR code scanner Scanner (2D and 3D) Touch screen (resistive, capacitive and infra-red)

output device: a device that can be used to obtain the results of data that has been processed. input device: a device that allows data to be entered into a computer system.

Question 9

KEYWORDS

It is used in a supermarket to get the price of a product and as part of a stock control system.

An output device is any device that allows the result of the data processing to be seen or heard. Common examples of output devices are: •

actuator



digital light processing (DLP) projector

62

)

3



inkjet printer



laser printer



light emitting diode (LED) screen



liquid crystal display (LCD) projector



liquid crystal display (LCD) screen



speaker



3D printer.

Hardware

Question

10 Copy the table below that includes the examples of the output devices. For each output device, describe the kind of data that it allows to be output and give an example of when it is used. The first one has been done for you. Output device

Description of data output

Example of use

Actuator

It is a component that outputs an action, often a type of movement, that causes another device to operate.

Can be used in an automated system to move or turn on/off another device, e.g. a light.

Digital light processing (DLP) projector Inkjet printer Laser printer Light emitting diode (LED) screen Liquid crystal display (LCD) projector Liquid crystal display (LCD) screen Speaker 3D printer

Many computer systems that you encounter in your daily life are automated systems. You can learn more about what an automated system is and how they work in Chapter 6. A type of input device called a sensor is used in an automated system. The sensor is used to capture different types of data to be processed by the system. The sensor captures analogue data from its immediate surrounding environment. This data can then be processed and analysed by a computer system. Sensors are normally set to capture data at given time intervals. This could be as constant as every single second or even fraction of a second. It could also be set to be every minute or at particular times of the day. Table 3.1 shows the different types of sensor that you need to know, a description of the type of data that they capture and an example of a how they might be used.

KEYWORDS sensor: a type of input device that is used to capture data from its immediate environment. automated system: a system that is designed to operate without the need for any human intervention.

63

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Type of sensor

Type of data captured

Example of its use

Acoustic

This type of sensors measures the level of sound in an environment.

These sensors are used in many applications that involve sound. An acoustic sensor can be used in a security system. It can be placed near a window and constantly measure the level of sound. If it captures a reading that shows a sudden increase in sound, this could mean that the window has been broken and the building may be at risk.

Accelerometer

This type of sensor measures acceleration forces. These may be static forces, such as the continual force of gravity. They can also be dynamic forces, such as those created by movement and vibrations.

These sensors are used in a wide variety of devices. Mobile phones use an accelerometer to know which way up it is faced, to automatically turn the screen on and off. They can be used to monitor for earthquakes, as they can capture the initial vibrations created. They can also be used in cars to sense when a crash has occurred, so that airbags can be inflated.

Flow

This type of sensor measures the amount of liquid, gas or steam that is flowing through or around a certain environment.

These sensors are often used in factories and sites such as nuclear power plants. They make sure that the liquid, gas or steam flows at a constant temperature through an environment, such as a pipe. This makes sure that the pipes don't rupture and break due to too much flowing through them.

Gas

This type of sensor measures the presence and concentration of a gas within the immediate atmosphere.

These sensors can be used in people's homes. They can be set to measure a certain gas, such as carbon monoxide. They constantly capture the data in the immediate atmosphere to see if too much carbon monoxide is present, which could endanger the health of anyone living in the home.

Humidity

This type of sensor measures the level of moisture in the immediate atmosphere.

These sensors can be used in farming and agriculture to make sure that the air in areas such as greenhouses has the correct level of moisture to provide the best growing conditions for the fruits and vegetables. They can also be used in places such as art galleries, to make sure that the humidity level is constant. Too much or too little can ruin paintings.

Infra-red

This type of sensor measures infra-red radiation. This type of radiation can be emitted in different amounts by both objects and people.

These sensors can also be used in security systems. This can be done in two different ways. The device containing the sensor can emit infra-red radiation and when this bounces back to the device, the readings can show from the distance it has travelled whether an intruder is present. It can also operate by capturing the infra-red radiation emitted by the intruder.

Level

This type of sensor measures whether a substance, such as a liquid, is at a certain level or amount.

These sensors can be used in a car to make sure that essential liquids, such as oil and fuel, do not get too low.

Light

These sensors can be used in automatic lighting systems. This type of sensor measures Streetlights can be fitted with a light sensor that will the ambient light in a certain environment. It can also measure allow the light to turn on in the evening, when it becomes darker. the presence of a direct light, such as a laser beam. (continued)

64

)

3

Hardware

Type of sensor

Type of data captured

Example of its use

Magnetic field

This type of sensor measures the presence of magnetic field that may be emitted by an object.

These sensors can be used to count how many cars pass through a certain area, for example into a car park. The car will disrupt the Earth's naturally magnetic field as it passes over the sensor and the data can be captured by the sensor.

Moisture

This type of sensor measures the amount of water that is present in a substance, such as soil.

These sensors can also be used by farming and agriculture, to make sure that the fruits and vegetables have the best level of water in the soil to help them grow.

pH

This type of sensor measures the pH level of a substance.

These sensors can be used by environmental agencies to make sure that local lakes and river are not being polluted.

Pressure

This type of sensor measures the force of pressure that is applied to the sensor or device. This could be the pressure created by a solid object, or it could be created by liquid or gas.

These sensors could also be used in a security system. They can be placed at the base or sides of an opening, such as a window or a door. When that window or door is opened, the pressure will decrease, and the system will recognise that an intruder has entered.

Proximity

This type of sensor measures how close an object is in comparison to the sensor. It does this by emitting electromagnetic radiation or an electromagnetic field and measures the radiation as it returns to see if there are any changes.

These types of sensors can be used in robots in manufacturing. They allow the robots to measure how close they are to different objects, when moving around a factory.

Temperature

This type of sensor measures the temperature of an object or substance by either directly touching it or capturing data from the surrounding environment.

These types of sensors are used in air conditioning systems. They allow the temperature of a room to be kept at a certain level.

Table 3.1: Different types of sensor

Figure 3.6: An accelerometer can sense a crash so that airbags inflate

Figure 3.7: Streetlights use light sensors

65

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Questions

11 Is a sensor an example of an input device or an 12 13

14 15

output device? Can you name five different types of sensor? Can you think of one application for each of the following sensors? a Light b Magnetic field c Temperature Can you think of two ways that the use of sensors is of benefit to humans? How could an accelerometer be used to protect the hard drive on a computer?

Figure 3.8: Art galleries use temperature and humidity sensors

3.7 Data storage

You need to store data in a computer system on a constant basis. This might be temporarily, whilst it is being processed, or on a more permanent basis for future use. For these purposes, there are two main categories of storage that exist in a computer, they are primary storage and secondary storage. Primary storage is a category of storage that is directly accessed by the CPU. This means that the CPU has a direct connection to it and that data is sent between the CPU and the primary storage using this connection. There are two main types of primary storage, random access memory (RAM) and read only memory (ROM). There are several characteristics of each type of primary storage, these include those shown in Table 3.2: Characteristics of RAM

Characteristics of ROM

It is volatile storage. This mean that it requires power to store data. If the power is turned off, the contents of RAM are lost. Volatile storage is sometimes referred to as temporary storage.

It is non-volatile. This means that if power is removed, the contents of the ROM are retained. Non-volatile storage is sometimes referred to as permanent storage.

It stores data and programs that are currently in use by the computer.

It stores programs that initially boot the computer, such as the bootstrap and the BIOS.

Its contents are constantly being changed as data is processed by the CPU.

The contents of ROM are fixed and do not normally change. It is possible to reprogram it, but this is a complex process and only normally attempted in circumstance when a computer system is failing to boot correctly.

It is possible to increase the amount of RAM a computer has by adding further RAM components

It is not easy to alter the ROM available in a computer system.

Table 3.2: Characteristics of primary storage

66

)

KEYWORDS primary storage: a type of storage that is directly accessed by the CPU. secondary storage: a type of storage that is designed to store data permanently, until it is deleted by the user.

ROM (read only memory): a type of primary storage that stores the start up instruction for the computer.

3

Figure 3.9: Technician changing a computer's RAM

Hardware

Figure 3.1 0: The inside of a hard disk drive

' ACTIVITY 3.6 Did you know that there are also different types of RAM and ROM? You do not need to know what these are for the exam, but it is interesting to find out what they are. Use the internet to research the different types of RAM and ROM and when they are used. Secondary storage is a category of storage that is not directly accessed by the CPU. This means that data and instructions need to be sent from secondary storage into primary storage in order for it to be processed. Secondary storage is also a type of non-volatile storage. Can you remember what this means? There are three main types of secondary storage, these are magnetic, optical and solid-state storage. Magnetic storage relies on the properties of magnetism to store data. A modern magnetic storage device normally has circular plates called platters that spin to allow data to be read and written. The platters are separated into tracks and sectors. It has a read/write head that moves across the platters to read or write the data. It uses an electromagnet to magnetise dots on each platter that store the data. If a dot is magnetised it stores the binary value 1. If a dot is demagnetised it stores the binary value 0. Each platter has billions of these magnetised dots. An example of this type device is called a hard disk drive. ACTIVITY 3.7 You have just learnt that a hard disk drive is a type of magnetic storage and how it operates. There are older types of magnetic storage called magnetic tape and floppy disks. What can you find out about them? Can you also find out what the largest storage capacity is for a hard disk drive?

KEYWORDS magnetic storage:

a type of secondary storage that uses the properties of magnetism to store data. optical storage: a

type of secondary storage that uses lasers to store data. solid-state storage:

a type of secondary storage that uses transistors to store data.

REFLECTION After completing Activity 3.7: What kind of search data did you use to find out the data for the activity? Do you think you could have improved your search data?

67

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

In 1956, a technology company called IBM sold the first hard disk drive. It had a storage capacity of just 5 MiB of data and cost $50 000! Thankfully, hard disk drives have become much cheaper to buy and have a much larger storage capacity now. Another type of storage that became available to buy around 1982 is optical storage. People originally thought optical storage would replace hard disk drives, but soon realised that they could not be made with a high enough capacity to do this. Optical storage uses lasers to read and write data to and from a circular disk. The disk spins and a read/write heads moves across the surface to allow data to be read or written. To write data, a laser burns pits into the surface of the disk. These pits are organised in a spiral track that starts at the centre of the disk. The surface of the disk between each pit is called a land. A laser is also used to read the pits and lands to obtain the data that they store. Examples of optical media are a CD, DVD and a Blu-ray. Two of those examples are read using a red laser and one is read using a blue laser, can you guess which is which?

Draw a diagram to represent the operation of optical storage.

Although optical storage is still used today, it is mostly used to archive data or as a cheap way to physically distribute files to users that require them. They didn't replace hard drives in the way that it was first thought they would. As portable devices developed, people began to realise there was a disadvantage with hard disk drives. This disadvantage came from the fact that they have moving parts. This made them vulnerable to wear and tear and also damage if they were dropped. As a result, a new type of storage was developed called solid-state storage. Solid state storage doesn't have any moving parts. Instead it is created using semiconductor chips. Solid-state storage is sometimes known as flash memory. This is because of the ways that the data is read and written to the chips, it is said that it is 'flashed' onto them, but how does that happen? Solid state storage contains cells and transistors that are laid out in a grid. The transistors can be wired together in two different ways. In a NOR flash structure, the cells are wired together in a parallel structure. In a NAND flash structure, the cells are wired together in series. The intersection of the rows and columns of transistors are the cells. One of the transistors is called a control gate and one of the transistors is called a floating gate. The control gate sits on top of the floating gate. When a solid state storage device is first created, all the transistors are set to the binary value 1. The electric current reaches each control gate and then flows through to the floating gate to be stored. When data is stored in a transistor, it is converted to the binary value 0. A solid state drive is one example of a solid state storage device. You probably use another example on a regular basis too, it's called a USB flash memory drive (also known as USB stick, memory stick or a thumb drive).

ACTIVITY 3. 9 You have learnt that a solid state drive and a USB flash memory drive are example of solid state storage. Can you think of another example?

68

)

Figure 3.11: CDs are a type of optical media

KEYWORD semiconductor chips: an electronic circuit, where transistors are set on a semiconductor material, such as silicon.

3

Hardware

COMPUTER SCIENCE IN CONTEXT Organisations have a growing need to store more and more data. This data is often vital to the operation of the organisation. Data storage development companies are constantly trying to develop storage devices that have larger storage capacities. Due to this need, researchers have started to look at other methods of data storage including a revolutionary method called holographic data storage. This type of data storage would allow approximately a terabyte of data to be stored in a single crystal that is about the size of a grain of sugar.

3.8 Virtual memory So far, all the storage that you have learnt about has been physical storage. This means that it is an actual component storage unit that you can see and touch. There is another type of storage that can be created in a computer and this is called l'irtual memory. It is called virtual memory, as unlike physical storage, it isn't a component that you can see or touch. You may have noticed that this chapter includes the term memory and storage. You may find these used interchangeably in lots of different resources. There is a slight difference between the two, but even the defined difference is a little contradictory. Technically, memory is used as a term for short term temporary storage of data, and storage is used as a term for the permanent storage of data. For example, RAM stores data temporarily and is a type of memory, random access memory. A hard disk drive is a type of storage as it stores data permanently, until the user deletes it. This seems a simple distinction , but ROM is also a type of memory, read only memory, but it stores data permanently too. Therefore, the difference is not completely clear, but it is mostly considered that memory is temporary and storage is permanent. However, you don't need to become too worried about picking the correct term! Virtual memory is also a type of memory that is created for temporary use. It is created as an extension to RAM. Sometimes, a computer is given a large number of tasks to complete at a given time. This means that it will need a lot of data to do this. All this data will need to be sent to the RAM to be ready to be processed. A computer system only has a set amount of RAM, so what happens when this RAM becomes full? It needs some extra help! This is where virtual memory can help.

Figure 3.12: A USB flash memory drive

KEYWORDS cell: the intersection of the rows and columns of transistors in solid-state storage. transistor: a device that acts as a switch or gate for electronic signals. control gate: a component that controls the flow of electric current. floating gate: a component that can store electrical charge. virtual memory:

a type of memory that can be used as an extension to the RAM. page: a unit of data.

Virtual memory is created in a computer system with a hard drive component. A section of that hard drive is partitioned off and is effectively an extra bit for RAM instead. When the RAM gets full, the computer system can transfer some data to the virtual memory to be held there until it is needed. It will choose to send data that isn't as immediately required as other data. The data that is transferred is collected in a structure called a page. These pages of data are transferred to the virtual memory to make sure there is enough room in the RAM for the immediate data that is being processed. Once the pages of data are required again, they can be sent back to the RAM to be processed. The diagram in Figure 3.13 shows the process:

69

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

There is only space for 3 pages in RAM. Page C isn't immediately needed so it is sent to virtual memory.

Four pages of data are sent to RAM

Virtual Memory

Hard drive RAM

CPU

Page A is sent to the CPU to be processed. Page C is now required, so it can be sent back to RAM.

Figure 3.13: Pages of data are transferred to the virtual memory so that RAM doesn't become full

If the RAM became full and the computer did not have the ability to transfer pages of data to the virtual memory, this could cause it to crash, as it may not be able to complete the task it is currently working on.

3.9 Cloud storage Despite a common misconception that many people have, cloud storage does not store our data somewhere up in the clouds. So how did it get that name? It is more in relation to the very large collections of data that are stored being like clouds of data, think clouds of millions of raindrops! As technology has developed, and continues to do so, people have found that they want and need to store larger amounts of data, and data storage is quite expensive to buy, keep and maintain. You might be able to make sure that your 2 Terabyte hard drive at home is safe in your house and is checked regularly for security issues, but it's likely you only have a relatively small amount of data to store. Some multinational businesses have huge amounts of data to store. This can require large rooms that are needed to house expensive hardware, such as computer servers, to store all the data that the company requires. This could be the details of millions of their customers and all the online transactions they have made to buy products. They would also need staff to maintain this equipment and keep that data safe. These kinds of costs could amount to many thousands of pounds a year for a business. Therefore, cloud storage offers them an alternative.

70

)

KEYWORDS cloud storage: data storage that is owned by a third party and accessed by the user, using the internet. server: a component that acts as a central resource for the storage of data and applications or for providing a service.

3

Hardware

Cloud storage companies created a service in which they set up very large buildings that house and maintain thousands of computer servers. They spend 24 hours a day making sure the servers are maintained and secure. A company can then pay a fee to the cloud storage company for their service, to be allowed to store their data on their servers and pass the responsibility to the company to keep it secure until it is required. The company then accesses this data, when it is required, using the internet. Cloud storage is a collection of third party hardware (hardware that is owned by another person or organisation), such as computer servers, that individuals and companies can use to store data, and for a range of other services. When data is stored within the buildings and hardware owned by the individual or business, this is known as storing the data locally. When data is stored in hardware owned by a third party and accessed using the internet, this is known as storing data remotely. Cloud storage began as a simple way to offload the responsibility of storing data. Since it was first used, it has developed into use for other services. For example, a business can now use cloud storage in connection to its website. The cloud storage company can offer a service whereby when demand is high for a website, such as they have a big sale, then they can use cloud storage to extend the capabilities of the web servers to be able to process the large amounts of data and requests that are being sent to the website. This means that the company can use hardware they do not own, on occasions when the demand for their business is high. This means they do not need to own all the hardware used, and have the extra hardware not being used, and therefore wasting money for them, when their business demand is lower. Helpful for business costs!

Figure 3.14: Data can be stored in cloud storage

COMPUTER SCIENCE IN CONTEXT Individuals are making increasing use of cloud storage. This allows portable devices to remain fairly small, as they do not need to store very large amounts of data locally within the portable device, e.g. their mobile phone. Companies such as Microsoft also offer access to software using cloud storage now, e.g. Office 365. This means that people do not need to download large software applications onto their portable devices.

Some people do have concerns about cloud storage. They think it is a big risk to give someone else the responsibility for looking after their data. Table 3.3 gives comparisons of some advantages and disadvantages of storing data in the cloud and storing it locally.

71

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Storing data in the cloud

Storing data locally

You do not have to pay for the hardware to store the data.

You will need to purchase the hardware to store your data. These costs can be high if you have a lot of data to store.

You do not have the responsibility for the security of the hardware that stores the data. However, you are relying on a third party making sure that your data is safe. If they do not do this correctly, they may put your data at risk.

You will need to make sure that your data storage is well maintained and that it is regularly checked and updated for security issues.

You can access the data and resources using different devices from anywhere that you have an internet connection. However, if your connection fails or is not available, you will not be able to access your data. If your connection is slow, this can also mean that accessing your data is slow.

You do not need an internet connection to access your data, therefore it is available at all times that you have local access to that data.

You can increase and decrease the amount of storage space you need very easily, when you need to.

You might have redundant hardware, that you have paid for, that isn't used as the amount of data that you need to store has decreased.

Table 3.3: Comparisons of storing data in the cloud and locally I

ACTIVITY 3.10

KEY WORDS

Do you store any data in cloud storage? If so , do you ever worry about doing this? Discuss with a partner about the advantages and disadvantages of storing data in the cloud, compared to local storage. Reach a conclusion about whether you think the risk is worth it.

network: computers and devices that are joined together using cables or wireless technology.

As part of your discussion research at least one more advantage and one more disadvantage and make note of these. You can then share your thoughts from your discussion with the rest of your class and see who thinks cloud or local storage is better, and why.

3.10 Network hardware

At the beginning of this chapter, you learnt about the hardware required within a computer and local to a computer that enable the temporary and permanent storage of data. You have now learnt that data can be stored remotely, in a cloud storage system, but that an internet connection is required to access the data stored in the cloud. The hardware required for this connection creates a network. You will now learn what hardware is required to create a connection to other devices and the internet. When two or more devices are connected, this is called a network. Some basic hardware devices are required to create a network, these are a network interface card (NJC), a router and you may need some transmission media.

72

>

network interface card (NIC): the component in a computer that is used to connect it to a network. router: a network component that examines a data packet to obtain its destination address and then forwards the packet to this address. transmission media: the cables that are used to transfer data in a network.

3

Hardware

Within your computer or device is a piece of hardware called a NIC. This may be a wired or wireless NIC. This means that either a cable will be plugged into the hardware to connect to a network, or it will have a wireless component that allows it to make a wireless connection. Most modern NICs are wireless NICs (WNICs).

...____

Figure 3.15: A network interface card (NIC)

KEYWORD

Each NIC is given an address called a media access control (MAC) address. This address can be used to identify a device on a network.

media access control (MAC) address: the unique address that is given to a NIC by the manufacturer.

A MAC address is assigned by the manufacturer and is never normally changed. It will remain assigned to the device whilst it is in use. A MAC address is made up of two main parts. These are the manufacturers ID code and the Serial ID code for the device. This creates a unique address for each device. The address is represented as hexadecimal and normally has six pairs of numbers, separated with either a dash or a colon, for example: 34 :4D : EA: 89: 75: B2 When a device with a network interface card transmits data across a network, it will send the MAC address of that device with the data. This means that it is possible to tell, from inspecting the data, which device on the network the data was sent from. ACTIVITY 3.11 See if you can find out the MAC address of one of your devices, such as a computer, laptop or a mobile phone. If you do not know how to find it, you can use the internet to find a tutorial.

When data is sent across a network, a hardware device can be used to make sure that the data arrives at the correct destination. You can use a hardware device called a router to do this. Will a router have a NIC? Does this mean it will have a MAC address? See if you can find out! Each device that wants to connect to the internet will also need to do this by connecting to the router. This could be a wired or wireless connection. A router is a hardware device that reads each data packet that it receives. Details about data packets and their structure was covered in Chapter 2. The router reads the data packets to find out the destination of the data. It can use the MAC address to do this,

KEYWORD data packet: a unit of data that is used to transmit data across a network.

73

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

but that will normally only be used if the data is sent to another device that is part of the same local network (this is a network that is contained within a specific area, such as your house). As a router is also used to connect a device or a local network to the internet, it is the internet protocol (IP) address of the destination device that is normally read and used to forward the data to its correct destination. This IP address can also be used to locate your device on a network, and it is also a unique address. It is different in structure to a MAC address, as it is assigned by the network, rather than by the manufacturer. In a local network, such as a home network, it is often the router that assigns the IP address to a device, when it is connected to the router.

Figure 3.16:

A home router

An IP address can have different structures, such an IPv4 or IPv6 structure. IPv4 was the first structure created for an IP address. This structure was created back in 1983 and uses 32-bits to create each numerical IP address. Even though it is now an old structure, there are still many devices that have an IPv4 address. An example of an IPv4 address is: 12.244.233.165 As more and more devices started connecting to networks, the number of available JPv4 addresses started to rapidly decline. As each IP address needs to be unique to the device, they were rapidly running out, due to the number of devices worldwide. IPv6 was created as result, to create more available IP addresses. IPv6 uses 128-bits to create an IP address. IPv6 addresses can also contain hexadecimal characters. This created much more possibilities for IP addresses and allowed them to remain unique to the device. An example of an IPv6 address is: 2001 :0db8:0000:0000:0000:ff00:0042:7879 You will also notice that an IPv4 address is separated by full stops, but an IPv6 address is separated by colons. An IP address can also be either static or dynamic. Most devices are assigned a dynamic IP address. This means that the address can change each time the device is connected to a network. The device may be given that IP address for a single session

74

>

KEY WORDS static IP: an IP address that does not change each time the device connects to a network. dynamic IP: an IP address that can change each time the device connects to a network.

3

Hardware

that it connects to the router, or it may be given it for several sessions before it changes, but it will change at some point. It is possible to obtain a static IP address for your device. This means that the IP address for your device will be the same every time that you connect your device to a network, it will not change, until you request it to be changed, it will always remain the same. It is normally your Internet Service Provider that will provide you with a static IP address for your device. ACTIVITY 3.12 Can you find out what kind of devices a static IP address is normally used for? Can you also find out what the benefit is of having a static IP address?

SUMMARY Hardware is all the physical components that you can see and touch in a computer system. The CPU is the component in a computer system that processes all the instructions and data. It uses an instruction set to do this. The CPU has several component parts, these include the ALU, CU, PC, MAR, MDR, CIR, ACC and buses. The CPU is responsible for carrying out the fetch-decode-execute cycle. The number of cores, the clock speed and the cache size can all affect the performance of the CPU. Computers also need input and output devices to be able to provide a system with data, then obtain the results when it has been processed. Sensors are a type of input device that can be used to capture data from the immediate surrounding environment. A computer has both primary and secondary storage. Primary storage is directly accessed by the CPU and consist of RAM and ROM. Secondary storage is not directly accessed by the CPU and there are three types, magnetic, optical and solid-state. Virtual memory is created by portioning part of the hard drive. It is used when RAM is full. Cloud storage is when data is stored remotely on servers and storage that is owned and maintained by a third party. A network is created when two or more devices are connected. A device needs a NIC to connect to a network. Each NIC has a MAC address. A router is used in a network to forward packets of data to their correct destination. A router can assign an IP address to each device. There are two types of IP address, IPv4 and IPv6.

75

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

EXAM-STYLE QUESTIONS 1 A student has a computer that has a Von Neumann architecture.

The CPU in the computer performs the fetch-decode-execute cycle to process data and instructions. a i Identify the name of the component where an instruction is stored immediately before it is fetched into the CPU. ii Identify the name of the component that stores the address of the next instruction that will be processed. iii Describe what happens at the decode stage of the cycle. b The computer has a 2 GHz single core processor. The students wants to improve the performance of the computer by replacing the CPU. The student selects a new CPU that is a 3.4GHz dual core processor. Identify how many cores are in the new CPU. ii Explain why the performance of the new CPU would be better. c The computer has both random access memory (RAM) and read only memory (ROM). Identify if these are examples of primary or secondary storage. ii State what each of these components store. [Total: 2 Give the most appropriate sensor for use in each of the given scenarios. A different sensor must be given for each scenario. Scenario

COMMAND WORDS [1] [1]

[3]

[1] [2]

[1] [2]

11]

[3]

Most appropriate sensor

To monitor the amount of pollution in a river. To count the number of competitors who finish a race. To detect a person who is approaching an automatic door system.

3 A small business uses optical data storage to archive their customers' data. a i Give two examples of optical storage. ii Describe how data is stored on optical storage. b The business currently has a local archive for their data. They are considering storing their customer data in cloud storage instead. Give one advantage of storing the customer data in cloud storage, rather than local storage. ii Give two disadvantages of storing the customer data in cloud storage, rather than local storage. [Total: 4 A computer connects to the internet and is assigned an IP address. The IP address has an IPv4 structure. Describe the structure of an IPv4 address.

76

)

[2] [6]

[1] [2]

11]

[2]

identify: name/ select I recognise describe: state the points of a topic/ give characteristics and main features. explain: set out purposes or reasons/ make the relationships between things evident/ provide why and/or how and support with relevant evidence. state: express in clear terms. give: produce an answer from a given source or recall/ memory.

3

Hardware

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'.

. 1 can... - -- -

--

- - - -- ·.�����--�r�I'=�--;·---.----:-: ,-;-;-;}�-·� �Conf,dent Needs ,J: ,·-. 1:.Ge · ;}/:'?.:· ·, -::�!::J·:.:,,,,�, e,.�.- ·: ° · �

--=-��-- .,.,., �.,y,,.1 .?�

L ---· _----___-------

�Y-�};'?t�--

-

----

Application software

Figure 4.3: System software manages the running of hardware; application software runs on top of system software

Software can be put into different categories, depending on their purpose and use (Figure 4.3 shows the link between hardware and software). System software manages the running of the hardware and other software, and allows

communication between these components. These are tasks that help the computer perform its functions and improve or maintain its efficiency. Two types of system software are the operating system (OS) and utility programs.

Examples of utility programs are not required but useful to know. These are programs that maintain the computer system, for example: •

System clean-up-searches for and removes un-used programs and data.



Defragmentation-rearranges files so that they are located together (contiguously) and that the free spaces is located together.

Application software allows the user to perform a task - it provides the services for the

user, for example, write a letter, view a website, etc.

Application software have generic names, as well as the brand names. It is important that you know the generic names, some of the common ones are: •

A word processor allows the user to create written documents.



A spreadsheet allows the user to perform calculations on data.



A database allows the user to store and search a set of data.



A web browser allows the user to view and navigate websites.

KEY WORDS software: a series of

instructions written in a programming language that performs a function .

system software:

a type of software that manages the hardware and software in a computer.

operating system

(OS): a program

that manages the computer, allows the user to communicate with the computer, and allows software to be run. utility programs:

system software that performs house­ keeping activities. application software:

software that allows the user to perform a useful task. word processor: a type of application software that allows the user to create text-based documents.

spreadsheet: a

type of application software that performs calculations on data. database: an example

of application software to store and manipulate data.

web browser: a piece

of software that retrieves and displays web pages.

80

)

4

Software

COMPUTER SCIENCE IN CONTEXT PCs, laptops, tablets and smartphones all have application software. The brand names may be different, but the fundamental purposes are the same. For example, you can open a word processor on a PC, a laptop, a tablet and even a smartphone.

Application software I

runs on

r::

D Figure 4.4: Digital devices come in many different forms

The application software cannot run on a computer without an operating system. The operating system cannot run unless there instructions given to it, these are provided by the firmware. The firmware cannot run unless it is told to run, this is done using the bootstrap program, which is loaded when the computer first turns on. This process can be represented as shown in Figure 4.5 on the right. ACTIVITY 4.1 Log onto a computer, tablet or mobile phone. Make a list of the different types of application software that are installed. Remember not to use brand names.

4.2 Operating system

Operating System runs on Firmware is loaded by the Bootstrap

Figure 4.5: The software on a computer.

KEYWORDS firmware:

instructions that are stored in the ROM and are loaded when the computer starts. bootstrap: the first commands loaded when a computer starts, it checks hardware and loads the firmware.

An operating system (OS) is an example of system software, you may be familiar with brands such as Windows, Linux and macOS for PCs and laptops. Other computers also have operating systems, for example, a mobile phone may have an Android OS, or iOS. The overall purpose of these operating systems is to allow you, the user, to interact with the hardware. The OS has many different roles that are described in the following sections.

81

>

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Providing an interface The OS allows the user to enter data, and outputs data to the user, all through the interface. There are different types of interface:

I

KEYWORDS interface: the



Graphical User Interface (GUI) has windows, icons, menus and pointers (WIMP).

method by which a user communicates with a computer.



A command line interface requires the user to enter text as commands. This is most useful for expert users because the commands entered must be exact. An example is Linux.

Graphical User Interface (GUI): a



It is what you will be familiar with from PCs, mobile phones, etc. This is most useful for novices because it is often intuitive. An example is Windows.

A natural language interface allows the user to enter any text commands, or speak

commands. The OS then analyses what has been entered and performs the action.

type of operating system that includes windows, icons, menus and pointers.

command line interface: a type of

operating system where the user types commands.

natural language interface: a type of

operating system that allows the user to type or speak commands.

Figure 4.6: A Graphical User Interface

Figure 4.7: An image of a command prompt

COMPUTER SCIENCE IN CONTEXT Have you every spoken a command to a computer? For example, Amazon's Alexa, Microsoft's Cortana or Apple's Siri? These are examples of natural language interfaces. You do not have to speak specific commands, the programs analyse the words you have said and decide on a response. There is more about how this is done in Chapter 6.

Managing files A user will use application software to create files. The OS allows the creation of directories that the files can be stored within. It also allows the user to move files, copy files, delete files, name and rename files, plus many other actions such as sorting by date.

Managing peripherals and drivers A computer cannot be used without input and output devices. These are called peripherals. Anyone can build a peripheral, and it will be programmed by the person

KEYWORD peripheral: a hardware device, used to input, store or output data from a computer, that is not directly part of the computer itself.

4

who made it - not the developer of the OS. This means that it may not be compatible (for example, it may use a different interpretation of binary). A driver is software that translates data from the computer to the peripheral, and vice-versa. The OS allows the installation of these drivers and the sending of data to and from it.

Managing memory

A computer uses memory to store data. This can be using secondary or primary memory. The OS manages the movement of data to and from hardware, primarily RAM. It also checks the processes being carried out and makes sure that they have enough memory allocated to perform their function. The OS will also make sure that two processes do not try and access the same memory location.

Software

KEYWORD driver: a program that controls a device, for example, a printer or a keyboard.

Figure 4.8: RAM memory modules

Managing multitasking

A single processor can only ever execute one instruction at a time. The processor does this so fast that it appears to be doing several tasks at once. For example, you might be listening to music from a computer, typing a document into a word processor, and the computer is outputting what you are doing. The OS allows this to happen by deciding which processes should be executed next and how long they can spend being processed before switching to another process. The OS does this using interrupts.

Managing interrupts

An interrupt is a signal sent to the processor to tell it that something needs its attention. The OS decides which interrupt to run and then performs the actions required. There is more about interrupts in Section 4.3.

KEYWORD interrupt: a signal

sent to the processor to tell it that its attention is required.

Providing a platform for running applications

Application software needs to run on a computer. The software could be written by anyone using any language. The OS allows the application software to run on the computer by fetching instructions from it and executing them.

Managing user accounts

Most computers need a user to set up an account. This can include preferences, as well as a username and password (text and/or biometric). The OS allows a user to set-up an account, keeps the data separate for multiple accounts, and restricts the access by using the password.

83

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

4.3 Interrupts An interrupt is a signal to the processor to tell it that something needs its attention. An interrupt can be software or hardware based. Table 4.1 has several examples of each. Software

Hardware

Division by 0.

Data input, e.g. key pressed on a keyboard, mouse click.

Two processes attempting to access the same memory location.

Error from hardware, e.g. printer out of paper.

Program request for input.

Hardware failure.

Output required.

Hard drive signal that it has read data.

Data required from memory.

New hardware device connected.

Table 4.1: Interrupt examples

An interrupt has a priority level. A high-priority interrupt needs the attention quickly, for example, hardware failure. A low-priority interrupt needs the processor but it's not urgent, for example, data input. This is managed by the interrupt handler (IH). When an interrupt is generated it is put in a queue according to its priority. The sequence of activities is: •

When the processor finishes its current fetch-decode-execute cycle (or before the starting the next FDE cycle), it checks the interrupt queue.



It checks whether there is an interrupt with a higher priority than the current task it is processing.





If it is, it: • Stores the current process and fetches the interrupt. •

Checks the source of the interrupt.



Calls the relevant interrupt service routine (ISR). This is a sequence of instructions that handle the interrupt.



When finished the stored process is returned to memory or another higher­ priority interrupt is fetched.

If it isn't, it runs another FDE cycle.

Questions

Give two examples of application software. 2 State the purpose of system software. Describe the relationship between application software and the bootstrap. 3 4 · Identify three tasks the file management of an Operating System can perform. 5 Give two examples of software interrupts, and two examples of hardware interrupts. Describe the process that happens when an interrupt is sent to the processor. 6 1

84

)

KEYWORDS interrupt handler (IH): a program that

organises interrupts into an order based upon priorities.

interrupt service routine (ISR): a program that retrieves an interrupt and performs the required action(s).

4

Software

4.4 Types of programming language When you are writing computer programs you will make use of specific software that allows you to write, edit, test and run the programs you write. Programming languages can be categorised as high-level and low-level.

High-level A high-level language uses human-language style words. These could be English words that we recognise and use day-to-day. For example, if, while, output, print, input; as people we understand these, but they are also high-level language instructions. You will be learning to use a high-level language, for example, Python, Java and VB.NET. Here are some examples of high-level language statements:

Python: print("This is a high-level language statement") VB.NET: Dim x as integer x = Console.readline() Java: numl = 10; num2 5; num3 numl + num2;

KEYWORDS high-level language: a type

of programming language that uses English-like commands.

low-level language:

a language closer to the machine's language, this could be assembly language or binary code.

portable: a program that can be run on different types and manufacturers of computers.

A program that is written in a high-level language is considered portable; you can write a program on one computer, and run it on a different computer.

Figure 4.9:

Code written in a high-level language

85

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Low-level There are two main types of low-level language, machine code and assembly language. A computer executes machine code, this is in binary (ls and Os). If you write a program in a high-level language it needs to be converted into machine code before it can executed. Different computers may have different machine code (for example, depending on the manufacturer). This means that machine code is non portable; you can write a program in machine code and it may not run on a different computer. An example of machine code is: O 1100110 Assembly language is an in-between stage. It uses mnemonics to represent code, for example, to store data in a memory location it may use the mneumonic STO. This is a mid-way stage. Each high-level language statement is converted into assembly language instructions, which are then converted into machine code.

KEYWORDS machine code:

binary code, an example of a low­ level language.

assembly language:

code written in mnemonics that allows direct manipulation of the hardware. It must be converted into binary code to run.

non portable:

a program that cannot be run on different types and manufacturers of computers.

mnemonic:

instruction code used in assembly language. Figure 4.10:

Machine code

Examples of assembly language are: LDD count ADD 1 STO count In assembly language, the program has to state which memory locations are being used. In the previous example, LDD count, the count is the memory location. One high-level language statement may need several assembly language instructions. The previous three assembly language instructions are the same as the single high-level language count = count + 1. ACTIVITY 4.2 Assembly language instructions are split into operators and operands. Find out what an operator and an operand is. Find some examples of each.

86

)

4

Software

Choosing a language High- and low-level languages have their own benefits and drawbacks. Some of these are shown in Table 4.2. High-level language

Low-level language

Easier for users (humans) to understand, read, write, amend.

More difficult for users to understand, read, write and amend.

Easier for users (humans) to debug code.

Harder for users to debug code.

Portable, machine independent.

Not portable, machine dependent.

It must be converted into a low-level language before it can be run.

Machine code does not need converting. Assembly language must be assembled before execution, but this is faster than from a high-level language.

One statement can represent many lowlevel instructions.

Several instructions are needed for each high-level language statement.

Cannot directly manipulate the hardware.

Can directly manipulate the hardware, e.g. writing to specific memory locations. This can make the program more efficient in terms of speed and memory usage.

Table 4.2: Benefits and drawbacks of high- and low-level languages

Questions 7 8

Describe what is meant by a high-level language. Three examples of program code are given. Identify whether each example is a high-level language, assembly language, or machine code. Program code

High-level, assembly or machine code

LDX 10 INC STO 10

valuel = input ( "Enter value") print(valuel + 1) 01100011 11000011 10101010

9

Harry needs to write a utility program that uses as little memory as possible. Give the most appropriate type of programming language Harry should use and justify your choice.

4.5 Translators In Section 4.4 you learnt that high-level language programs, and assembly language programs, need to be converted to machine code to be executed. This is done using a translator.

KEYWORD translator: a type of software that converts code written in one programming language into another, usually a high-level language into a low-level language.

87

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Assembler

KEYWORDS

If you have a program written in assembly language, then an assembler is used to convert the instructions into machine code for the processor the code is being run on.

Interpreters and compilers If you have written a program in a high-level language then you can use an interpreter or a compiler to translate the instructions. An interpreter: •

reads one line of the high-level language code



checks that it is syntactically correct: •

if it is not, it stops and reports an error to the user



If it is, it executes the statement and moves to the next.

Interpreters are most useful when writing the program, because it will stop at an error, allow you to correct it, and then continue executing from the same position. Interpreters are not as useful for whole-system testing, or when the program is complete. This is because all of the code needs to be interpreted every time the program is run, even if there are no errors. A compiler checks all the code, by going through one-line after the other. If there are any syntax errors, they are all reported to the user and the program is not executed. If there are no errors, then an executable file is created. An executable file uses intermediate or object code derived from the high-level language code. The actual program code is not included so if someone has the executable file, they cannot view or amend the original code. The executable file can be run without having to re-translate the code.

assembler: converts assembly language into machine code. interpreter: a translator that converts a high-level language into a low-level language. It checks one line of code and then executes it before checking the next. compiler: a translator that converts a high­ level language into a low-level language. It checks all code before running the program.

executable file: a file produced by a compiler that can be run independent of translator software and does not include the source code.

Compilers are useful when you have finished the program or need to test a working element repeatedly. This is because the code does not need to be translated each time, the executable file is run repeatedly. Table 4.3 shows the comparisons of interpreters and compilers. Interpreter

Compiler

Translates one line of code into machine code and then executes (runs) it.

Translates all lines of code into machine code, before executing the program.

Reports a syntax error as soon as it is picked up, and stops the program running until corrected.

Reports all syntax errors at the same time, the program is not run until all errors are corrected.

Useful when writing a program.

Useful when a program has been finished and is ready for testing or distribution.

Code needs to be re-translated each time the program is run.

Code does not need re-translating each time the program is run.

Does not produce an executable file.

Produces an executable file.

Source code is required to run the program.

Source code is not required to run the program, only the executable file. (continued)

4

Software

Interpreter

Compiler

Interpreter software is required to run the program.

No other software is required to run the executable file.

You can test part of a program without completing it all.

You need to have finished a section of code before testing it.

Table 4.3: Comparison of interpreters and compilers

Examples: Saria is writing a computer game program that allows a character to move through different worlds collecting coins. Which translator should Saria use when writing the code? •

It is more appropriate to use an interpreter. This will allow her to see when an error is identified, correct it and then continue running the program from the same position.



A compiler can be used, but then all the errors would appear at the start and she would need to correct all of them before seeing how any of her program runs.



An interpreter is considered more appropriate, but you could justify the use of a compiler in this situation.

Which translator should Saria use once she has finished programming the computer game and wants to sell it to users? •

A compiler should be used, because she can produce an executable file. There should be no syntax errors at this point, so correcting the code line-by-line is not required. The executable file can be distributed to people and they can then run the program without need to retranslate the instructions every time. The executable file also means that no-one will be able to see her code, so it is protected.



An interpreter would not be an appropriate choice here, because the end user would need the interpreter software and the source code, and will need to wait for it to be interpreted each time. It also means the users can access the source code, and then copy it or change it.

t ACTIVITY 4.3 Write a computer program in a language that uses an interpreter, and one that uses a compiler. You might need to use a different programming language for each one. For example, Python usually has interpreters, whilst VB.NET and Java usually have compilers. Which translator did you prefer to use?

Peer Assessment Discuss the reasons why you preferred the translator you chose. Did anyone give you some reasons that you hadn't thought of? Can you expand your own answer any further?

89

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

SKILLS FOCUS 4.1 JUSTIFYING CHOICE In an exam you may need to make a decision and then justify your choice. To answer this type question you will need to consider the context of the question and how each of the possible choices will impact the context. When you are justifying your decision you need to relate every reason back to the scenario. Consider the choice of translator. •



An interpreter is most useful during the development of a program because: •

you can fix errors in real time



the program will stop at each error to allow you to fix it



you can run small sections of the program when incomplete.



it produces a .exe file



the program does not need to be interpreted each time it is run



the program can be distributed without the source code.

editor: a feature of

Saria is writing a computer program. 2

Why is it more appropriate for Saria to use an interpreter while writing a program? Why is it more appropriate for Saria to use a compiler when the program is complete?

4.6 Integrated Development Environment (IDE) When you write a computer program you will most likely use an Integrated Development Environment (IDE). This is a piece of software that includes an editor for you to enter and amend your code. This editor may include other features such as: •

Auto-completion; you start typing a command and it suggests options for you to



Auto-correction; if you spell a command incorrect it changes it to what you meant

select the correct one.

to type.



Prettyprint; this changes the colour of words, e.g. commands and identifiers. This helps you spot key terms and whether you have entered them correctly or not.



Block minimising; you can make sections of code, e.g. procedures, minimised so there is less code to read through.

The IDE will also include the relevant translator, that you can select to translate the code. It will also provide a run-time environment; this is where the outputs from the executed code is displayed, it can be a command line or GUI depending on your language and the code entered.

90

Integrated Development Environment (IDE): a

piece of software that allows a user to write, test and run program code.

A compiler is most useful when a program is complete because:

Questions 1

KEYWORDS

)

an IDE that allows the user to enter and amend program code. auto-completion:

a feature of an editor that gives the user options when they start typing a command.

auto-correction:

a feature of an editor that identifies spelling errors and changes them. prettyprint: a feature

of an editor that changes the colour of text, for example, to highlight key words. run-time environment: a

feature of an IDE that allows a program to be run and lets the user interact with the program.

I'

I

4

Software

An IDE can also provide debugging features, or error diagnostics, these help you find the problems in your code. Some examples are: •

Break points; the user sets these points and the code stops running on that line. This lets you check the values and output from the code to that point.



Variable watch window; the values of the variables are displayed while the code is running, so they can be checked whether they are correct.



Stepping; the program will run one line at a time, and the user has to tell the program to move on to the next line, so it can be checked line by line.

You can write and run programs without an IDE. You can write your code in a basic text file without any formatting, and then run it (usually) through a command line interface by entering the correct instructions. An IDE is much more user friendly, with lots of tools to help you write, amend and correct your code.

COMPUTER SCIENCE IN CONTEXT You may not always get a choice of whether to use an interpreter or a compiler. If you use an IDE (Integrated Development Environment) it will probably come with one, or the other. If your IDE has an interpreter and you want to make an executable then you might need to download another IDE to compile it.

REFLECTION After completing Activity 4.4, it can be helpful to think about how you approached it and ways you could improve your research skills for future activities. 1

Discuss how you approached the investigation of the features. Did you test out the features, or search the internet to find out what they did? Do you think your approach was the most appropriate? Would you try a different way if the activity was repeated?

2

Discuss how this activity has helped you to identify the features. Does practically using them help you to remember them?

ACTIVITY 4.4 Open up the IDE that you use to write programs. Identify the features that are mentioned in this chapter. Are there any different ones? If so, find out what these do.

Questions 10 Name three types of translator. 11 Nasrat is writing a program in a high-level language that she wants to sell to make

money. Identify when Nasrat could use an interpreter, and when she could use a compiler. Justify your decisions. 12 Describe two features of an IDE that help the user to test the program they have written.

I

1 SELF ASSESSMENT Question 11 required you to justify your choice. Did you give generic points, or did you relate each point you made to the scenario in the question? When a context is given, always try and go back to the question each time.

91

)

CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

SUMMARY Software is created using programming languages. Two types of software are application and system software. The Operating System performs many functions including memory management, handling interrupts and providing an interface. An interrupt is a signal sent to the processor to get its attention. A high-level language uses English-like terms that need translating before it can run and a low-level language is assembly or machine code. Assembly language is turned into machine code using an assembler. High-level languages are turned into a low-level language using a compiler or interpreter. An IDE helps the user write, test and run program code.

EXAM-STYLE QUESTIONS 1

Tick one box in each row to identify if the software is an example of system software or application software. System software

Application software

Word processor Defragmentation Operating System Image manipulation System clean-up Database Web browser Spreadsheet

[5]

2 State what is meant by an interrupt. 3 Describe the difference between system software and application

software using an example of each. 4 An operating system performs memory management. a Describe memory management. b Give two other functions of an operating system.

92

)

[2]

state: express in

[3]

describe: state the points of a topic/ give characteristics and main features.

[3] [2] [Total: 5]

5 A printer sends an interrupt to the computer to say that it is out of paper. Describe the stages involved in the processor handling the interrupt. 6 The following sentence describes the requirements for application software. Fill in the missing gaps. The application software runs on the .............................. ................... .............. , this runs on the firmware, and it is loaded by the ......................................

COMMAND WORDS

[5]

[2]

clear terms.

give: produce an answer from a given source or recall/ memory.

4

Software

CONTINUED 7 Qui is writing a program using a high-level language. a Describe what is meant by low-level language, and high-level language. b Explain why a person will usually write a program using a high-level language and not a low-level language. c Give one reason why a person might prefer to write a program using a low-level language. d Qui needs to use a translator while writing the program. State what type of translator Qui should use, justify your choice. e Qui uses the translator in his Integrated Development Environment (IDE). Describe the other features of an IDE that Qui can use to write and test his program.

COMMAND WORD

[4]

explain: set out purposes or reasons / make the relationships between things evident / provide why and/or how and support with relevant evidence.

[3]

[1 l [3]

[6]

[Total: 17]

8 Explain the role of the operating system in a computer.

[8]

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'. I can...

See topic

describe the difference between application and system software.

4.1

describe the role and basic functions of an operating system.

4.2

describe how hardware, firmware and an operating system are required to run application software.

4.2

describe the role and operation of interrupts.

4.3

describe the characteristics, advantages and disadvantages, of high-level and low-level languages.

Needs more work

Getting there

Confident to move on

4.4

describe the use of an assembler, compiler and interpreter.

4.5

describe the advantages and disadvantages of a compiler and an interpreter.

4.5

describe the use of, and features of, an IDE.

4.6

93

)



learn what the difference is between the internet and the world wide web



understand what is meant by a URL and study the purpose of each of its component parts



discover the purpose and operation of the hypertext transfer protocol (HTTP) and the hypertext transfer protocol secure (HTTPS)



learn about the different functions that a web browser performs, including the use of cookies



discover how web pages are requested, retrieved and displayed on your computer or device



understand what is meant by a digital currency and how blockchain is used to track digital currency transactions



learn about a range of cyber security threats and how a range of different solutions can be used to keep data safe from these threats.

5

The internet and its uses

GETTING STARTED Think about what you already know about keeping yourself safe on the internet (e-safety). Create a poster for a younger audience to tell them how to use the internet safely and what to do if they find something that upsets them.

Figure 5.1: A parent helping a child to safely access the internet

: THE EFFECTS OF MALWARE On average, there are approximately 2500 cyber security attacks that happen each day. Malware is used in many of these attacks and over 90% of this malware is delivered using email. WannaCry is the name of a large scale cyber security attack that occurred in 2017. Malware was used to take over computer servers in systems across Britain, Spain, Russia, Ukraine and Taiwan. The type of malware used in the WannaCry attack is called ransomware. The malware blocked users and organisations from accessing files and accounts. It did this by encrypting the files. It wanted the organisations to pay money to the creators of the malware in order to be able to gain access to their files and accounts again. The payment demanded was in Bitcoin . As organisations were not able to gain access to their files and accounts until the ransom was paid, mass disruption was often caused to the

Figure 5.2: Malware prevents users from accessing their files and data

95

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED daily processes in these organisations. One example of this was the National Health Service (NHS) in Britain. British hospitals were forced to turn away some patients who could not be treated until their personal information could be accessed again. WannaCry malware was based on a set of malware code called Eternal Blue. There have been several malware attacks since WannaCry based on this same EternalBlue code. Discussion questions 1

Do you think it is the organisation's fault that the malware infected their systems and caused issues?

2

Do you think it is completely the hacker's fault for being able to put the malware on the systems?

3

How would you feel if your files were encrypted and you couldn' t access them? Would you pay the ransom, or would you take a different action?

5.1 The internet and the world wide web

The internet and the world wide web: aren't they the same thing? Although the terms are used interchangeably, they aren't the same thing. Bonus points if you knew that already! The internet is an infrastructure. This means it is all the components and cables that are used to connect one device to another. Another way that the internet can be described is that it is one huge network. More specifically, it is a type of network called a wide area network (WAN). This is a type of network that spans a large geographic area, in this case the whole world! The internet is an incredible structure if you think that homes and businesses all over the world are able to use it to connect to each other. Millions and millions of people use this huge infrastructure.

KEYWORDS internet: a very large global network that allows users to access the world wide web. infrastructure: the physical structure, such as all the components and cables, that are used to connect devices. network: computers and devices that are joined together using cables or wireless technology. world wide web: the collection of all the web pages and websites that have been made available. website: a collection of web pages, normally about a related topic or purpose.

Figure 5.3: The internet connects millions of people

The world wide web is the collective term for all the websites and web pages that are available. The world wide web is accessed by using the internet.

96

)

web page: a single page within a website.

5

The internet and its uses

COMPUTER SCIENCE IN CONTEXT T he world wide web was invented by Tim Berners-Lee in 1989. He was motivated to do so by a problem that he had. He is a Computer Scientist and found that at the time he had several computers that all had different information stored on them. He found that he would have to keep logging onto the different computers to obtain the particular information that he needed. He saw a way to solve this issue that he realised could be used universally. Lots of computers were already being connected together into networks and he realised that he could share information using an emerging technology at the time called Hypertext. By October of 1990 he had developed the three fundamental parts that create the world wide web: HyperText Markup language (HTML), uniform resource locator (URL) and the Hypertext Transfer Protocol (HTTP). By the end of 1990, the first web server was set up and the first web page displaying information about the world wide web project was created.

ACTIVITY 5.1 Have a look at what the first web page looked like. Type 'the world wide web project' into your browser and look for the 'info.cern' link.

KEY WORDS uniform resource locater (URL): another name for the text-based address for a website. Figure 5.4: HTML

5.2 Requesting and retrieving web pages A URL is a fundamental component of the world wide web. Each website and web page on the world wide web has a text based address. This address is called a URL. To access the web page, a user types the URL into the address bar of a web bro ser. A URL has three main components: the protocol, the domain name and the web page or file name.

web browser: a piece of software that retrieves and displays web pages. protocol: a set of rules for transmitting data. domain name: a specific part of a URL that contains the unique name for the web server.

97

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Figure 5.5 shows an example of a URL:

https://www. cambridge.org /education L,-1 � c.__ _J _

There is a whole process involved in requesting and retrieving web pages that you need to understand, the URL and its three components are fundamental to this process. So how is a web page requested and retrieved by our computers?

protocol

domain name

web page name

Figure 5.5: The components of a URL

To start the process, the user opens their web browser and types the URL into the address bar. The web browser then sends the URL for the website to the domain name server (DNS). The DNS is a special kind of server that stores all the different domain names (part of the URL shown in Figure 5.5) along with their equivalent IP address. The DNS looks through its database of domain names to find the equivalent IP address. As you can imagine, there are billions of websites, so these are not all stored on a single DNS. Therefore, the first DNS will search its database and if it doesn't find the domain name, it sends it to the next DNS. This will happen until the domain name is found, or if it is not found, a message is sent back to the web browser to say that the website is not found. When the DNS find the domain name, it sends the equivalent IP address back to the web browser - the IP address of the web server that stores the website. This process is summarised in Figure 5.6. DNS searches for domain

Web browser sends URL to DNS

name to find URL

its equivalent IP address

□ □ □ □ □ □ □ □ IP address

Figure 5.6: A web browser requests an IP address from a DNS

The web browser receives the IP address for the website from the DNS. It now knows where to find the website. The web browser sends a request to the web server to ask for the web page from the website. It uses a protocol called the hypertext transfer protocol (HTTP) to send the request to the web server. Each web page is created using hypertext markup language (HTML), cascading style sheets (CSS) and may include active script such as JavaScript. When the web server receives a request for a web page, it sends the data for the website, including the HTML, CSS and any active script, back to the web browser using the HTTP. The web browser then renders the HTML and CSS and runs any active script to display the web page. This process is summarised in Figure 5.7.

KEYWORDS domain name server (DNS): a special

server that contains a database of domain names and their corresponding IP address.

web server: a

network component where the web pages for a website are stored.

hypertext transfer protocol (HTTP): a

protocol that is used for the transmission of web pages and related data across the internet. hypertext markup language (HTML):

a scripting (web authoring) language that is used to create web pages.

cascading style sheet (CSS): a

scripting language that is used to create a presentation template for a web page. It includes what kind of font and colour text will appear on the webpage. active script: this is

the script that is used to produce any of the interactive elements of a web page.

5

Web browser uses the IP address to send a request to the web server to obtain the data for the web page

The internet and its uses

Web server sends the data, including HTML, CSS and active script to the web browser Request for web page

� Web browser renders the HTML and CSS and runs the active script to display the web page

Data for web page

Figure 5.7: The web browser requests a web page and renders the HTML and CSS

Questions 1

2 3

What is a URL? What is an IP address? What are the three main parts of a URL?

Another protocol can be used to request the data for the web pages that will require an additional process to take place. This protocol is the hypertext transfer protocol secure (HTTPS). This protocol has an additional layer of security that encrypts any data that is transferred. It involves the use of digital certificates. This is a certificate that the owners of the website need to apply for from a certificate authority. A certificate authority is an organisation that checks whether a website is authentic and trustworthy. If the certificate authority believe the website is authentic, they will issue them with a digital certificate. This is how the additional layer of security is created. • Before the web browser sends a request to the web server to ask for the web pages, it sends a request to the web server asking it to provide a digital certificate. • The web server sends a copy of the digital certificate to the web browser. •

The web browser checks if the digital certificate is authentic.



If the certificate is authentic, the web browser will allow communication to continue with the web server and any data that is transmitted between the two is encrypted.



If the certificate is not authentic, the web browser will report that the website is not secure.

KEYWORDS hypertext transfer protocol secure

(HTTPS): a secure version of the HTTP that encrypts data for transmission.

encryption: a method of securing data for storage or transmission that scrambles it and makes it meaningless. digital certificate: a certificate that is awarded to a website if they can prove that they are a real organisation and take measures to securely transmit their data.

certificate authority: the awarding organisation that checks if another organisation is real and secure before awarding them a digital certificate.

99

)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

This process is summarised in Figure 5.8. Web browser asks the web server to send its digital certificate

Request for digital certificate

Web server sends its digital certificate to the web browser

Encrypted data transmission

Web browser authenticates the certificate. If authentic, encrypted data transmission

Digital certificate sent

Figure 5.8: A web browser requests a digital certificate to allow encrypted data transmission

The HTTPS protocol is the standard HTTP protocol with a layer of security combined, that is either the secure sockets layer (SSL) or transport layer security (TLS) protocol. TLS is a newer version of SSL. This is the protocol that is used to create the encryption. You can check visually whether a website is secure by seeing if it uses the HTTPS protocol. If it does, you will see this at the start of the URL in the address bar in the web browser. You will also see a small padlock before the start of the URL. Most web browsers also have an option for you to view the digital certificate for the website. This is often found by right clicking your mouse on the padlock. ACTIVITY 5.2 Use the internet to research why the TLS protocol was developed to replace the SSL protocol.

Questions 4 5

What is a digital certificate and how is it used in the HTTPS protocol? Does the web browser or the web server authenticate the digital certificate?

5.3 The purpose of a web browser

You may have noticed that the web browser has a key role in the requesting and retrieving of web pages. The main purpose of a web browser is that it is a software application that allows you to access information that is available on the world wide web. As you learnt previously, it does this by requesting the HTML files and other data required to create the web page, then renders this data so that you can view the web page. One thing to note about a web browser is that some people confuse it with a search engine. This is because some web browser software development companies also

100)

KEYWORDS secure sockets layer (SSL) protocol: a

type of protocol that encrypts data for transmission. It is the protocol, that is combined with the HTTP to create HTTPS.

transport layer security (TLS) protocol: an updated

version of the SSL protocol.

render: the method

of processing all the web page data, such as HTML, to display the web page.

5

The internet and its uses

produce search engines too. One example of this is Google. Google produce a search engine called google, that you can use to find information on the world wide web, however this is not a browser. The browser that Google produce is Google Chrome. This is the software that allows you to open web pages, such as the google search engine. Why don't you test your friends and see if they know the difference?

KEYWORDS

Google

address bar: the section of a web browser where you type the web page address.

Figure 5.9: Example of a search engine

ACTIVITY 5.3

Figure 5.10: Examples of web browsers 0

Can you think of two more examples of a web browser? Use the internet to check if you are correct. Did you know that there are lots of other things that a web browser can do? This is a list of some of the main functions of a web browser, how many have you used before? •

It provides an address bar that you can use to type in a URL.



It keeps a record of all the web pages that you have visited. This is called user history.



It allows you to bookmark web pages and set web pages as your favourites. These can then be displayed on the toolbar of your web browser to allow you to access them much more quickly. It means you can just click the bookmark or favourite icon and it will take you straight to the web page.



It allows you to open multiple tabs at a time. The browser itself opens into a window on your computer. Without tabs, you would need to open multiple windows if you wanted to open more than one web page at a time. Tabs allow you to open multiple web pages in the same browser window which makes it easier to navigate between the different web pages that you have open.



It allows you to navigate between web pages. The buttons that are most commonly available on a web browser are forward, back and reload the page.



It stores cookies and manages the process of transmitting them. You will learn more about cookies next!

user history: a record made on your web browser of all the web pages that you have visited.

a link that can be created to allow you to quickly find a web page again. bookmark:

a website function that allows you to open multiple web pages in the same window. tab:

a viewing area that is created in which a software application or file can be opened. window:

navigate: move around web pages, or move back or forward to previous web pages. cookie: small text file that is used to store personal data, by a web browser.

101 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

The main features are shown in Figure 5.11. Navigation buttons

Tab

Address bar

Main window: This is where you will see the HTML rendered and the web page displayed

Settings: This is where you will find your history and bookmarks and favourites (you may also find these on a toolbar below the address bar)

Figure 5.11: The main features of a web browser

Cookies! Sadly, not the tasty kind, but a useful function of a web browser. So, what exactly is a cookie? A very simple explanation is that it is a small text file that is used to store data, normally about you. They are very useful as they can store data that you may regularly use on the internet. This means that you do not need to enter this data every time. Examples of this are: •

Storing your username and password for accounts such as your social media.



Storing your bank card details for buying products and services online.



Storing products in a virtual shopping cart when you are buying multiple products from an online company. It can also save the items in your cart so that you can buy them at a later date if you don't want to buy them now.

Cookies can be used to tailor your online experience with websites. Some websites allow you to format the website in the way that you want it to look, for example, changing the colour of text and boxes that appear on the web page. Cookies can also be used to track the different content that you look at on the world wide web. For example, if you look at web pages about your favourite hobby or interest, you will find that advertisements appear on web pages that are about your favourite hobby too. This is called targeted advertising.

1/"l? \

Figure 5.12: Many websites use cookies

5

Cookies are created when you visit a web page and then they are stored by your web browser. There are two main types of cookie, session cookies and persistent cookies. Session cookies are temporary files that are created when you visit a web page. As soon as you close your web browser, these cookies are deleted. If you open your web browser again and go back to the same web page, the web page will not recognise you. That means that it will not be sent any cookies by your web browser, about your personal details or preferences, as this type of cookie are not saved by the browser once it is closed. You might have experienced this type of cookie when you are online shopping. You may have added several items that you wanted to buy to a shopping cart on a website, you then close your web browser. You then open your web browser at a later date and go back to the web page, only to find that the items you put in the online shopping cart are no longer there. This is because it is a session cookie that is used to temporarily store them. This process is summarised in Figure 5.13.

The internet and its uses

KEYWORDS session cookie: a type of cookie that is deleted when the web browser is closed. persistent cookie: a type of cookie that is stored by the web browser until it is deleted by the user or because it has expired.

User visits the web page that is stored on the web server

Session cookies are temporarily stored by user's web browser until the browser is closed and the session ends. The cookies are then deleted.

Session cookies are sent from web server to user's web browser Figure 5.13: Session cookies

Persistent cookies are permanent files that are created when you visit a web page. These are stored by your web browser onto the hard drive of your computer. When you visit the same web page again, the cookie file is sent back to the web server that stores the web pages to provide the data about your personal details or preferences. This will allow your login details to be automatically entered, for example. These cookies will remain stored on your hard drive until you manually delete them, or your browser deletes them because they have expired. Each persistent cookie file is sent with an expiration date. When this expiration date is reached, the web browser will delete this cookie from your hard drive. This process is summarised in Figure 5.14.

103 >

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

User visits the web page that is stored on the web server

Persistent cookies are permanently stored by user's web browser until the user or the web browser deletes them.

Persistent cookies are sent to the web server every time the user visits the web page

Persistent cookies are sent from web server to user's web browser

Figure 5.14: Persistent cookies

Internet users have mixed feelings about cookies. This is because they can have a very useful role but can also be used for improper activities. Cookies do build up an online profile about your details and preferences. Some people feel this is an invasion of their privacy. Other people also believe that this data can be gathered to build a profile about you and add to the risk of your identity being stolen. If you are worried about this being a possibility, you can limit the use of cookies in your online activity by changing the settings for your web browser.

Questions 6 7 8

What is a cookie used for? What is the difference between a session cookie and a persistent cookie? Why do some people have an issue with cookies being used?

Figure 5.15: Cookies can be a privacy concern

COMPUTER SCIENCE IN CONTEXT Each company that creates a web browser will often have a slightly different aim as its focus. Some web browser development companies focus on the security of the transmission of data, whereas others focus on how quickly the web pages are rendered and displayed.

104)

5

5.4 Digital currency

When you pay for products and services using the internet, you will normally use a digital currency. A digital currency is one that exists electronically (see Figure 5.16). It is a method of payment that is similar to paying with coins and bank notes. However, rather than exchanging physical bank notes and coins to make the payment, the currency is exchanged digitally using computers. There are several different forms of digital currency, the most popular are payments using credit cards, mobile phones and smart watches. The most common of these is using credit cards when making payments using the internet.

The internet and its uses

KEYWORD digital currency: a

currency that exists electronically rather than physically.

When the data about the payment with the digital currency is sent from one computer to another, it is encrypted to keep it secure. The method of encryption used is what you learnt about previously, in Section 5.2, using the HTTPS protocol. The payment details for the use of a digital currency can be stored in a persistent cookie. That means that each time you visit the website to buy a product, your payment details will be automatically entered so you don't need to type them in each time.

Figure 5.16: Digital currency exists electronically and can be sent between computers

One type of digital currency that you may have heard of is Bitcoin. This type of digital currency is more specifically known as a cryptocurrency. The banks that we use to manage our money on a daily basis are called centralised systems. This means that there is an authority at the centre managing the process in which they are used. In this case, the bank is the authority. A cryptocurrency is a decentralised Figure 5.17: A cryptocurrency is a digital currency system, this means that there is that is managed by a decentralised system no central authority, like a bank, managing the process of payments. Payments are also encrypted using this type of currency. As there is no central authority managing the system of payments with this type of digital currency, a different system called blockchain is used to keep track of the payments. In its most basic form, blockchain is a list of all the records made with the digital currency. This is called a digital ledger (Figure 5.18). Each time a payment is made with the digital currency, a record is added to the ledger that includes a digital signature with the time and date that the payment is made. In blockchaining, once these records are added to the digital ledger, they cannot be changed. Data that is stored in a digital

KEYWORDS cryptocurrency:

a type of digital currency that uses encryption procedures.

blockchain: a

method that is used to track all the transactions made with a cryptocurrency.

digital ledger: a database that is a list of all the transactions recorded by the use of blockchain.

105 >

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

ledger is also encrypted. This prevents anyone being able to change the data. However, anyone who wants to view the data in the digital ledger is able to do so.

I Blockchain Digital Ledger I Payment 1 Payment 2 User sends payment using a type of digital currency called a cryptocurrency. The data is encrypted before it is sent.

Payment 3

The payment arrives with the intended user and only exists electronically.

The details of the payment are added to digital ledger, including a digital signature, time and date stamp. The data is stored for the digital ledger is encrypted and cannot be changed.

Figure 5.18: A blockchain keeps a digital ledger of transactions

COMPUTER SCIENCE IN CONTEXT There are as many as 2000 different digital currencies that exist. Many of these are different types of cryptocurrency. How many do you think you could name?

5.5 Cyber security

Whilst the internet and the world wide web can be a very fun and interesting place, it does also have some issues and threats that you definitely need to be aware of. You need to know how these cyber threats are created, what the motivation is behind those who use them, and what kind of security solution you can put in place to try and prevent them from happening. One thing to note is that each security solution may not be a complete prevention, sometimes it is better to have several solutions in place. Also, perpetrators are always looking to develop ways to beat security solutions, so no solution will be 100% effective in preventing an attack. However, if you don't have any security solutions in place, you are putting your personal data at a far greater risk of these cyber threats. So, what are the cyber threats that you need to know?

Brute-force attack You may have heard someone being described as a brute person. This normally means people think they are strong and forceful. This is exactly what a brute-force attack is on your computer, a strong and forceful attack. Imagine that someone is banging on a locked door, pushing and shoving it in every way that they can, until the door gives way and opens. In a brute-force attack, a perpetrator tries to break into your computer or account. They do this by repeatedly entering different password combinations until they manage to enter the correct one. They may try to do this manually, by typing in each password combination themselves. They could also do this by developing a

1()A \

KEYWORDS perpetrator: a

person that carries out an illegal or immoral action.

brute-force attack: a type of cyber threat that involves repeatedly inputting a password until the correct one is found, to try and break into an account or device .

5

The internet and its uses

software program that will automatically cycle through many different combinations until the correct one is found. The perpetrator usually does this to gain access to your computer or account in the hope that they can either steal some personal data that they can use for criminal activity, or they may try to use your account to purchase items online as though it was their own account. There are several cyber security solutions that you can put in place to help prevent a brute-force attack on your computer or account. The first is to make sure that you have a strong password to protect your data. A strong password is created by mixing different uppercase and lowercase letters, numbers and symbols. Ideally mixing these in a way that does not form any kind of word or phrase. A long string of a mixture of all these characters is the best protection that you can give your data. This will make it much more difficult for any perpetrator or software program to guess your password. It can be easy to find out some simple information about you, for example, that you have a rabbit called Mr Snuffles. Therefore, if your password is mrsnuffles0 1, this is not going to be difficult for a perpetrator to guess. Make life a bit more difficult for them, your data is precious! An example of a strong password is: 1gH6dk@dnlwm!dosTsjlpa Many web browsers now have a function that will suggest a strong password for you, mixing a combination of characters like this. They will also save the password for you, so you don't need to keep remembering the string of characters. Another security solution that can be used to help prevent a brute-force attack is limiting the number of times a password can be entered before the account is locked. You may have had this issue before. You type in what you think you had as a password for the account, but it is rejected, so you try another and that gets rejected, then you try a third one and that is rejected, and you now get a message saying you are locked out of your account. How frustrating! However, be very thankful for this security solution, however annoying it can be. It is likely that for a perpetrator to brute-force their way into your account, it will take more than three guesses at your password. Therefore, if the number of attempts is limited before the account is locked, this can prevent many guesses being made to try and find out the password. A third security solution that can be used is a biometric password. A biometric device is one that needs your biological data to be input. An example is a fingerprint scanner, which requires your fingerprint to be input. Our biological data is unique to us, it is highly unlikely that you will find another person that has exactly the same fingerprint as you. Therefore, if you secure your computer or account with a biological password, such as your fingerprint, no amount of guessing your password would allow a perpetrator to brute-force their way into your account. They would need to somehow obtain your fingerprint, which is a much more difficult task. A fourth security solution that can be used is two-step verification (sometimes known as two-factor authentication). This is a method that puts two tasks in place in order to enter an account. The first task is entering the password, but then a second step is added that will require an additional input task to enter the account. The second piece of data is often a code or word that is sent to you that you will need to enter. This is normally sent to either your mobile phone number or your email address. This means that a perpetrator will not only need to guess the password for your account, but that they will also need to have access to your mobile phone or your email, this is an added difficulty. Some banks also have a small card reading device that provide you with the data for the second step. You put your bank card into the reader, enters a PIN code

KEYWORDS biometric password: a type of password that uses a person's biological data, such as their fingerprint. biometric device: a device that allows a user to record and input a biometric password. two-step verification: a process that involves inputting two different kinds of data to enter an account or device.

107 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

or password and this generates the code for the second step for you to input. It is advisable that you look at the privacy and security settings for your online accounts, especially ones like your email and social media. Many companies have an option for you to turn on the feature of two-step verification which helps keep your personal data more secure. In summary: Multiple guesses are made at your password to try and break into your computer or account. To steal your precious personal data or to use your What is the aim? account to buy products online. What security solutions A strong password, a limited number of attempts at entering a password, a biometric password and can be used? two-step verification. What happens?

ACTIVITY 5.4 T hink about one of your passwords that you use to access an account online. How strong do you think that password is? Do you think that you could improve that password? Create a three-slide presentation that can be given to your peers to tell them how to create a strong password and what the importance is of doing so. Peer Assessment

Take a look at your partner's presentation. Do you think the information is presented clearly? Have they made it clear how to create a strong password? Do you think they have missed any information about doing this? Do you think they have made it clear how important it is to set a strong password? Have they included information about what might happen if a person does not set a strong password? Tell your partner your answer to these questions when you have looked at their presentation.

Data interception Billions of pieces of data are sent across the large network that is the internet on a daily basis. A lot of this data is people sending their personal data to do things like buy products and services, and log into their online accounts. Perpetrators would very much like to get hold of their information so that they can use it in criminal activity, such as identity theft and fraud. A way that they will try and do this is by intercepting data packets as they are transmitted across the network from one device to another. This is often done by using a piece of software called a packet sniffer, this is normally installed onto a piece of hardware that the packets will pass through, for example, a router. This software is used to examine packets of data that are sent across a network to see if they contain data that looks useful. If they do, the software will report the useful data packets it has found back to the perpetrator.

'1"\0

\.

KEYWORDS data packet: a unit of data that is used to transmit data across a network. packet sniffer: a piece of software that is used to examine the contents in a packet of data.

5

The internet and its uses

The main security solution that you can use to keep data secure that is sent over a network is encryption. Data is normally encrypted using the SSL protocol that you learnt about earlier in Section 5.2. This security solution will not stop the data packets from being intercepted, but it will mean that if the data packets are intercepted, the data contained in the packets will be meaningless to anyone who tries to read them. Remember, you can check to see if a website encrypts your data before transmission by looking to see if the URL uses HTTPS. It is also often possible, in your web browser settings, to set your web browser to only connect to websites that use encryption to transmit data.

Figure 5.19: If your data is intercepted by someone, will it be encrypted? Check if the URL uses HTTPS

Have you ever gone into a cafe or a store and thought, 'Excellent, free Wi-Fi!' and you immediately connect to it? Perpetrators can also use this kind of incentive to get you to connect to the network through a system of theirs. Any data that you send using this connection can be intercepted by the perpetrator. It is advisable, if you see a free Wi-Fi connection, to ask the cafe or store if it is their free Wi-Fi before you connect to it. In summary:

KEYWORDS

What happens?

Data packets are intercepted and examined through the use of software such as a packet sniffer.

What is the aim?

To steal your precious personal data for criminal activity such as identity theft or fraud.

What security solutions can be used?

Encryption such as the SSL protocol and visually checking the URL of a website to see if it uses the HTTPS protocol.

ACTIVITY 5.5 Use the internet to find out how a virtual private network (VPN) can be used to help prevent data interception.

Distributed denial of service (DDoS) attack To carry out a DDoS attack, a perpetrator will first create a botnet (bot network, see Figure 5.20). This is done by sending mahvare to many computers to try and get you to

distributed denial of service (DDoS) attack: a type of

cyber threat that targets a web server to cause it to crash and prevent access to the web pages that it stores.

botnet: a network of

bots that are created to carry out a DDoS attack.

malware: a type of malicious software that is downloaded onto a user's computer or device.

109 >

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

accidentally download it. Once you have downloaded the malware, the computer can then be used as a bot by the perpetrator. Whilst the bot is not being used it is often called a zombie. Once the perpetrator wants to carry out the attack, they 'wake up' all the zombies to be used as bots. Each bot will begin sending multiple requests to access a web server. They are all set to send requests to the same web server all at the same time. This floods the web server with too many requests and it begins to struggle to deal with each request. The web server can only deal with a certain number of requests at a time and if it is sent too many it will begin to slow down and eventually crash. This will mean that users can no longer access the website. This causes a denial of service to any normal requests to access the web server. This type of attack is normally carried out on a web server, but it could be used to target other types of server and network hardware. There are several reasons a perpetrator may carry out a DDoS attack. They may make a demand for money to the company to get them to pay to stop the attack from happening. They may want to punish the company for something that they perpetrator thinks they have done wrong, such as an unethical issue. This would be in an act of revenge or activism. The main security solution that a company can use to stop a DDoS attack occurring on their web server is to use a proxy server. A proxy server can be used as a barrier to a web server by getting all the requests for the web server to pass through the proxy server first. The proxy server can examine each request and forward it on to the web server to allow access. If the proxy server begins to receive many requests, it can begin to allow them to pass at a slower rate to avoid the web server being flooded with all the requests at the same time. This may mean access to the website is slower, but still possible by users that want to legitimately access it. A proxy server can also use a feature called caching. This feature can help prevent a DDoS from being successful as once the proxy server has received a request the access the website from a certain IP address, it will stop any repeated requests for a short period of time from the same IP address. Therefore, if a bot is sending multiple requests, not all of them will be passed onto the web server as some will be stopped by the proxy server. This makes it more difficult for a perpetrator to flood the web server. As a user, you can try and prevent your computer ever being used as a bot in a DDoS attack by regularly scanning your computer with anti-mahvare software. This is a type of software that scans all of the files in your computer to see if any of them are known to be malware. It does this by comparing each file against a known list of malware to see if any of the files on your computer match. If it finds a file that matches, it will put it in a special area called a quarantine area. It will then inform you that it has found what it thinks is malware and will ask you if you want to delete the file. By scanning your computer with anti-malware software on a regular basis, you can help make sure that your computer is free from any malware that might be used to turn it into a bot in a DDoS attack.

110 )

KEYWORDS bot: the name given

to a computer that has had malware downloaded onto it that will cause it to be used in a DDoS attack.

zombie: the name

given to a bot that has malware downloaded onto it to allow it to be used in a DDoS attack, but it currently isn't being used in this way. It is effectively a dormant or sleeping bot. proxy server: a

method of cy ber security that examines requests sent by devices to access the web pages stored on a web server.

anti-malware: a type

of software that scans a computer or device with the purpose of finding and removing malware.

5

The internet and its uses

Botnet

Malware



- -�



/

ta

Webserver

Figure 5.20: A botnet can cause a DDoS attack In summary: What happens?

Malware is sent to lots of computers to turn them into bots to create a botnet. The perpetrator then uses the botnet to send many requests to a web server, all at the same time.

What is the aim?

The aim is to cause the web server to crash. The perpetrator may be doing this to demand money for it to stop , or as an act of revenge or activism.

What security solutions can be used?

The company can use a proxy server to act as a barrier that filters requests to the web server. You can scan your computer with anti-malware on a regular basis to try and prevent it being used as a bot.

ACTIVITY 5.6 Use the internet to find out about a huge DDoS attack that was carried out on 21st October 2016, and which companies it affected.

111 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Hacking

KEYWORDS

Hacking is the act of trying to gain unauthorised access to data. A perpetrator that does this is known as a hacker. They can do this by using a range of technical skills that allow them to break into a computer or a network. This can be done by going through methods such as a brute-force attack (this is sometimes known as cracking) or by exploiting vulnerabilities in a computer or a network, which are areas that the hacker can identify that lack the protection of security solutions.

hacking: the act of gaining unauthorised access to data. This is normally done to steal or corrupt the data.

Hackers will gain access to a system for several reasons. This could be to steal your data to try and steal your identity, as an act of revenge, to corrupt your data or to leak confidential data about a company or project, or an act of activism. The main way that you can stop your computer being hacked is to have as many security solutions in place as possible. One of the main security solutions that can be used is a firewall A firewall is a barrier that can be used between your data and the rest of a network. It can be software based or hardware based. Any data that is sent into and out of your computer is examined by the firewall. Rules can be set for this data by giving your firewall a set of criteria to examine the data against. The data that is sent through the firewall is compared to the criteria. The firewall can be set to accept the data and allow it to pass through the firewall, or reject the data and stop it from passing through the firewall, depending on whether it does or does not meet the criteria. This added security solution may help identify data that a hacker has sent that looks malicious and reject this data to stop the hacker getting into the computer or network. A firewall can also be used to close certain ports to a network. A hacker may look to find a vulnerability, such as an open port, to get into a network. A firewall can be set to close as many ports as it can that are not being used, to try and prevent a hacker exploiting an open port to gain access.

hacker: the name given to a perpetrator that carries out an act of hacking. firewall: a cyber security method that is used to examine incoming and outgoing traffic from a computer or network. port: an entry point into a computer or network.

One kind of vulnerability that hackers may try to exploit is out of date software. Sometimes, a software company may find that they have an issue with their software that could allow a hacker to gain unauthorised access. If you have downloaded this software, you have also created this vulnerability on your computer. As software companies become aware of these issues, they develop their software and issue updates to protect against hackers. It is therefore vital that you update your software on a regular basis when software updates are released. This helps limit any vulnerabilities you have on your computer that a hacker can exploit. A way to make sure that your software is always up to date is to set your software to automatically update. This means that as soon as a software update is released, your computer will automatically download the update and you don't need to remember to do this. You can also password protect all your data with strong or biometric passwords to help stop a hacker gaining unauthorised access to your data. And you can add two-step verification to all your accounts. In summary:

Figure 5.21: Good security will protect

computers against hackers

What happens?

A hacker gains unauthorised access to your data by exploiting a vulnerability in your computer or network.

What is the aim?

The aim is to steal, corrupt or leak your data for criminal activity.

What security solutions can be used?

A firewall, automatic software updates, strong or biometric passwords and two-step verification.

112 )

5

Questions 9

KEYWORDS

What is a hacker?

10 How can you prevent a hacker gaining access to your data?

Malware Malware is a term used to describe any malicious software that is designed to disrupt your computer or data. There are several types of malicious software that you need to know about: virus, worm, trojan horse, spyware, adware and ransomware. See Table 5.1. Malware

Description

Virus

This is a computer program that is downloaded onto your hard drive. Once it has downloaded it replicates itself and corrupts your stored data or uses up all the available memory in your computer, causing it to slow down and crash.

Worm

This is a computer program that also replicates itself. It has a different aim to a virus though. It looks to find vulnerability holes in a network to use to replicate itself. In doing this it will clog up the bandwidth of a network and slow the network down.

Spyware

This is a computer program that is downloaded onto your hard drive and is designed to record your actions on your computer. A common form of spyware is a keylogger. This records all the key presses that a you carry out on your keyboard. This data is then sent to the perpetrator where it can be analysed to identify patterns in your data. Patterns in your data could reveal personal data such as your passwords. This can allow access to your online accounts for fraud and identity theft.

Trojan horse

This is a computer program that is used to disguise other malware. It is designed to look like a harmless piece of software, such as an application or game, but it contains other malware such as a virus or spyware. Once the trojan horse is downloaded onto your hard drive, it releases the other malware that it contains.

Adware

This is a computer program that is designed to automatically created pop up and banner adverts when you are online. These adverts are often unwanted and can be irritating and frustrating. The adware creators are given money by the companies that appear in the advertisements when you click on them.

Ransomware

Table 5.1:

The internet and its uses

This is a computer program that is downloaded onto your hard drive or other hardware. It is designed to encrypt your data and stop you from gaining access to it. The creators of the ransomware will demand a ransom (a set amount of money) for the data to be decrypted. They will often threaten to release and leak all your stored data if the ransom is not paid.

virus: a software based cyber threat that replicates itself with the aim of corrupting data or filling up the available memory space in a computer, causing it to crash. worm: a software based cyber threat that replicates itself across a network using vulnerabilities that it finds, with the aim of clogging up the bandwidth. trojan horse: a software based cyber threat that is used to disguise other malware to try and smuggle it into a computer or network. spyware: a software based cyber threat that spies on a user's action whilst using a computer, such as logging their key presses. adware: a software based cyber issue that automatically creates popup advertisements. ransomware: a software based cyber threat that encrypts a user's data to stop them gaining access to it until a ransom (money) is paid.

Different types of malware

113 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

There are several security solutions that you can use to protect against the threat of the different types of malware.

KEY WORD

An anti-virus software can be used to scan your computer for viruses. This is a type of anti-virus: a type of software that scans all of the files in your computer to see if any of them are known to software that scans a be a virus. It does this by comparing each file against a known list of viruses to see if computer for viruses any of the files on your computer match. If it finds a file that matches, it will put it in a with the purpose of special area called a quarantine area. It will then inform you that it has found what it finding and removing thinks is a virus and will ask you if you want to delete the file. By scanning your them. computer with anti-virus software on a regular basis, you can help make sure that your computer is free from any •:, , 1 ·:: 1' 11: ,, !{Iii! It Ill! ti le) i !11 l i Iii•!! 1, ! ,, ,,. •'

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Unsupervised means that data is input, and then the program learns from the data. An example of this is clustering. The data is plotted on a graph, and then the program identifies which items of data are close to each other. In image recognition, the shapes in the images could be input and then the features plotted, the program can then group the images according to these features. This is done without any human interaction needed.

COMPUTER SCIENCE IN CONTEXT Components in a computer game can make use of machine learning. For example, an Al chess player. The program will alter the moves that it makes based on the games it plays. This simulates how a human learns to play the game, they learn which moves work and which don't. This could be supervised learning if they are told which moves are the best to make. It could be unsupervised learning where it can play other people or computer programs, and change its own data and rules without being told what to do.

Figure 6.11: A person playing a computer game

ACTIVITY 6.3 Find and play a computer game where you are competing against the computer. Discuss how you think the computer's character was controlled. Did it just repeat the same movements over and over, or did it change what it did based on your move? Discuss how you think it was created and programmed.

11A \

6

Automated and emerging technologies

REFLECTION After completing Activity 6.3, it can be helpful to think about how you approached it and ways you could improve your research skills for future activities. 1

How did you approach this task? Did you play the computer game without thought to the character? Did you try lots of different moves to see how the computer reacted?

2

What programming knowledge did you use to discuss how the computer's character was programmed?

Expert systems

KEYWORDS

An expert system is a special type of system that attempts to emulate the expertise of a human, for example, an engineer, or doctor. The system asks the user questions to determine the solution or answer. Depending on each answer, the system will ask a different question.

expert system: a

For example, a program to help you fix a printer might first ask: 'Is there a green light on the printer?' If the user says No, then they may be told, 'Press the button to turn the printer on.' If the user says Yes, then they may be asked, 'Is there a red light underneath the paper picture?' An expert system has four key features: 1 2 3 4

A knowledge base. This is a list of facts, for example, there is a green light below the power symbol. A rule base that links the facts. For example, If the green light is on then the printer has power. Inference engine. This is the part of the program that decides which question to ask next, or which answers it gives. The user interface. This is the part that outputs questions and statements to the user, and allows the user to enter data .

system that attempts to replicate the knowledge of an expert. knowledge base:

part of an expert system that stores the facts. rule base: part of

an expert system that stores the rules based upon the knowledge.

inference engine:

part of an expert system that makes the decisions.

COMPUTER SCIENCE IN CONTEXT Organisations often use expert systems to allow people to find help without having to communicate with people. These are usually repetitive problems that people may encounter. If you have a home internet connection and it is not working, then troubleshooting can tell you what actions to perform to fix it.

139)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

ACTIVITY 6.4

Create an expert system to determine the difference between a cat and a dog. Ask the user questions depending on their previous answers. This can be written as a computer program using a programming language of your choice, or as a flowchart showing which questions to move to depending on each answer. Peer Assessment

Test each other's expert systems. How useable was the system? Were there any questions that you couldn't answer? Did it give you the correct answer?

Questions 1 0 Define the term artificial intelligence. 11 Describe what is meant by machine learning.

1 2 State the purpose of an expert system. 13 Give two examples of where expert systems can be used. 14 An expert system has an inference engine and interface. Describe the two other component parts of an expert system.

SUMMARY An automated system performs actions without human intervention. An automated system has sensors, a microprocessor and actuators. Robotics is the creation and management of machines that perform actions that humans perform. A robot contains a mechanical structure, electrical components including parts of an automated system, and it can be programmed to perform specific actions. Robots can be found in a range of areas, for example, medicine and transport, and have advantages and disadvantages in each context. Artificial intelligence is an area of computer science that aims to develop systems that mimic human intelligence. Machine learning is one area of artificial intelligence where a program can amend its own data and algorithms. An expert system attempts to simulate a human expert in a specific area. An expert system is made up of a knowledge base, rule base, inference engine and interface.

140 )

6

Automated and emerging technologies

EXAM-STYLE QUESTIONS

COMMAND WORDS

[1] 1 a Give one example of where an expert system can be used. b Complete the sentences about expert systems by filling in the missing words. An expert system is made up of four parts. The .............................. base is the set of .............................. The .............................. base is a set of logical rules. The .............................. .............................. applies the two bases to decide what questions to ask next and to work out the response. The .............................. is the elements that allow the user to .............................. data and to output data to the user. [7]

give: produce an answer from a given source or recall/ memory.

[Total: 8]

2 Identify three characteristics of a robot.

[3]

3 A car has a proximity detection system. If an object is within a set distance from the car, an alarm is sounded in the car. Describe how the automated system detects objects and alerts the driver. 4 An artificial intelligence program uses machine learning. Describe machine learning using an example. 5 A factory that builds furniture is thinking about buying robots to replace the workers. Discuss the advantages and disadvantages of the factory replacing the workers with robots. 6 Identify two ways that robotics can be used in transport. 7 Describe how machine learning can be used to develop speech recognition systems. 8 A farmer is thinking about implementing software into his machines to turn them into automated systems, for example, a tractor that navigates its own way around the field to plough the field. a Identify one other automated system the farmer could make use of. b Give two benefits to the farmer of using automated systems. c Give two drawbacks of implementing automated systems in the farm.

identify: name/

select I recognise.

describe: state the points of a topic/ give characteristics and main features.

[6] [2]

[6]

[2] [4]

[1] [2]

[2] [Total: 5]

9 A film company want to video animals in the wild acting naturally. They decide to create life-like robots that use artificial intelligence to react naturally with their environment. The robots have cameras inside that record the interactions. a Describe how artificial intelligence can be used to allow the robots to react to their environment. b Discuss the use of robots to record the animals.

[6]

[6] [Total: 12]

141 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'. I can...

See topic

describe what an automated system is.

6.1

describe the hardware used within an automated system.

6.1

describe the role of sensors, microprocessors and actuators used in automated systems.

6.1

describe the advantages and disadvantages of an automated system in a given scenario.

6.1

define the term robotics.

6.2

give examples of the use of robotics.

6.2

describe the characteristics of a robot.

6.2

describe the advantages and disadvantages of robotics in a given scenario.

6.3

define the term artificial intelligence.

6.4

describe the main characteristics of an AI system.

6.4

describe machine learning.

6.4

describe the key features of an expert system.

6.4

describe the use of an expert system for a given scenario.

6.4

142 )

Needs more work

Getting there

Confident to move on

learn about the use of, and stages in, the program development life cycle •

use decomposition to split a system into sub-systems



create structure diagrams, flowcharts and pseudocode algorithms



explain how a bubble sort and linear search works



describe and produce algorithms that include finding the maximum, minimum and average values



understand the need for validation and verification and write programs that use both



identify appropriate test data for an algorithm



complete a trace table for an algorithm



learn how to check a program for errors and amend the program



learn how to explain the purpose of an algorithm.

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

GETTING STARTED Set up an obstacle course using chairs and other objects. Write down a set of instructions to guide a friend through the obstacle course, for example, stating how many steps to take, which way to turn, etc. Give the instructions to a friend and ask them to follow the instructions safely (e.g. stop if they are about to hit something). Amend the instructions until your friend can successfully get through the obstacle course.

THE USE OF ALGORITHMS Consider what is meant by an algorithm. If you search for algorithm then you will find answers such as a process, or a set of rules, that are followed. T his does not mean they are limited to computers. You can find algorithms in all areas of life. You will have followed many of these without even considering that they are algorithms. For example, in mathematics you will have followed a series of steps to solve a problem. Algorithms can take many forms, and use a variety of words or structures. Computers follow algorithms. Programs are written as a series of instructions that the computer then follows. Algorithms for software might be millions of lines long, and they have to make use of specific instructions to tell the processor what to do. A computer can only run machine code, that is binary. If you enter a command into the computer, this has to be converted into binary for the processor to execute (run) it. Different programming languages have different focuses. Some different types are shown:

Declarative T his declares rules and you can ask it questions and it will give an answer based upon the rules. For example, here are some facts: person(ali)

Ali is a person.

person(jennifer)

Jennifer is a person.

person(tyler)

Tyler is a person.

friend(jennifer, tyler)

Jennifer is friends with Tyler is a person.

frie nd(tyler, ali)

Tyler is friends with Ali.

From this you could ask who Jennifer is friends with, and it will return Tyler.

Object-oriented This allows the user to create objects that have features (attributes) and processes (methods). For example, you could have a car as an object. Its features are colour, engine size, number of doors. Its processes are move forward, move backwards, turn.

Event driven Some programs use buttons, text boxes and other items that the user can interact with. An event driven language has code that is only run when one of these items is clicked, or changed. T he code is not run from start to finish, each item has its own code.

144)

7

Algorithm design and problem solving

CONTINUED Procedural

This has statements that are run in the order that they are written. It makes use of subroutines (procedures and functions) that can be called from other parts of the program. This is the type of language that you are most likely to start learning to program with.

Figure 7 .1: A person reading programming statements

Discussion questions 1

What are the key features of an event driven language?

2

Why do you think there is a need for different types of programming language? Can you think of any types of problem that lend themselves to one type of language?

7 .1 Program development life cycle When a person, or organisation, creates a new computer program they will use a structured, organised plan of how to create the program. This is called the program development life cycle. There are several varieties of life cycle, including cyclic, spiral, waterfall and rapid development. These all include the stages analysis, design, coding and testing.

KEYWORDS program development life cycle: a series of

structure step / activities that are followed to produce a system. analysis: the first stage of the program development life cycle that involves investigating the problem.

145 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

7.2 Analysis

This first stage involves looking at the problem and the system that is needed. The problem is explored, and the requirements of the program are identified. Decomposition is used to split the problem into subproblems. Subproblems allow the developers to identify the requirements for each component part, and then tackle these separately in the next stage. Once you have decomposed the problem, each of the subproblems can be implemented as a subprogram.

7.3 Design

Once the requirements have been identified, the program designers can begin planning how the program will work in the design phase. This can include an overview of the program using a structure diagram, and the designing of algorithms using flowcharts and pseudocode.

Structure diagram A structure diagram is developed by decomposing a program into its subprograms. The diagram has the name of the program at the top, and below this its subprograms. Each subprogram can be split down further as well if required.

Example 1 A calculator needs to allow the user to enter numbers and the symbol, calculate the result and output this.

decomposition: taking a system and splitting it into smaller sub-systems, which can in turn be split into smaller sub-systems.

design: the second stage of the program development life cycle, which involves decomposition of the problem and algorithms created ready for implementation. structure diagram: a hierarchical diagram that shows the decomposition of a system.

process: an action

The name of the program is at the top. The boxes below are ready for subprograms (Figure 7.2). One way of splitting up a small program is to think of inputs, processes and outputs. A calculator has an input, processes and output, so these can be added to the diagram (Figure 7.3).

KEYWORDS

that is performed, for example, X

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 2

Chess

The name of the program is at the top (Figure 7.8). The program could be decomposed into inputs, processes and outputs, but this is a large program so it can be split down by different functions instead. The first part is that there are two players who need entering, this is given the name 'New players'. Then the game is set up ('New game'). The players can then move their pieces ('Make move'). The program will check if someone has checkmate ('Check won') (Figure 7.9):

Figure 7 .8: A structure diagram for a chess program

Figure 7. 9: Subprograms for the chess program

These can then be split further. They are each given their own sub-diagram here so that they are easier to view (Figures 7.10-13):

Figure 7.10: The New players subprogram

Figure 7 .12: The Make move subprogram

Check player move check

Check player move checkmate

Figure 7 .13: The Check won subprogram

1,1A \

Figure 7 .11: The New game subprogram

7

Algorithm design and problem solving

ACTIVITY 7 .1 Can you split any of these subprograms down further? In 'Check won' (Figure 7 .13) what should happen if the result is checkmate? Should there be an output? What if there is check but not checkmate? Should this be output?

Peer Assessment Compare your subsystems with a friend. Did you have the same answers? If so, are they both valid structure diagrams even though they are different?

Once you have decomposed your program into subprograms, you will need to design an algorithm for each part. T his could be the level 1 (the first row below the top box) like in the calculator example. It could be for a lower level, like in the game of chess. Each box should become an individual algorithm. When you write your program, each of these individual algorithms might be a separate function or procedure (see Chapter 8, Section 12). Together, these individual algorithms should come together to create the whole system.

Questions 1 2 3

4

Describe the process of decomposition. A program asks the user to enter two numbers. The program then adds the numbers together and outputs the total. Draw a structure diagram for the program. A satellite navigation system needs to ask the user to input their destination. It then finds the route to the destination and outputs the instructions to the user. Draw a structure diagram for the system. A login system asks the user to enter their username and password. It checks these are valid and either outputs that they are correct, or incorrect and prompts to re-enter. Draw a structure diagram for the system.

Flowcharts

KEYWORD

A flowchart is a diagrammatic representation of an algorithm. Figure 7.14 shows some of the set of standard symbols.

flowchart: a diagrammatic representation of an algorithm.

Start/Stop

Process

Input/ Output

Figure 7 .14: Flowchart symbols

A flowchart shows each step of a process, in the order that each step is performed. Each shape has one statement within it, for example, input number, or add 1 to x. The shapes are joined with arrows to show the direction of flow and the content inside each box can be written as words, or as pseudocode statements. Table 7.1 shows examples of how the flowchart symbols are used.

149 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Shape

Description

Start/stop

A flowchart begins with a Start box, with one arrow from it.

+

Examples

A flowchart ends with a Stop box, with one arrow going into it.

±

Figure 7.15: Start/Stop

Input

A single input of a value with an identifier for that value. One arrow should go into the box, and one arrow should come out.

I I

L

input number

t

7

L input letter

Figure 7.16: Input

Output

An output of text in speech marks, and/or the identifier of a value

I I

L output number

t

I

L output "error"

t L output "number is" & number

1

Figure 7.17: Output

I

(continued)

150 )

7

Shape

Description

Process

An action that is being performed, usually a mathematical calculation. One arrow goes into the box, and one arrow comes out of the box.

Examples

number = number + 1

message= "hello" & "world" Figure 7 .18:

Decision

A question with two outcomes, yes or no (or true or false). The question is a comparison from: = equal to > greater than

Algorithm design and problem solving

Process

is 1 > 2?

< less than

YES

NO

>= greater than -----answer= num1 + num2 >------ ---�

is symbol -?

YES >-----.ianswer = num1 -num2 f-----------------1

YES >----.., answer = num1 / num2 >-------------
-----.i answer= num1 * num2 f---- ---�

output answer

stop Figure 7 .20: A flowchart for a calculator

1S2 }

7

Algorithm design and problem solving

Example 2 Figure 7.21 shows a flowchart for a password validation program.

Start

input password

is password length> 8

NO

output "invalid too short"

YES

does password include at least 1 letter and 1 number

NO

output "invalid must have at least 1 letter and at least1 number"

YES Stop

Figure 7 .21: A flowchart for a password validation program

t ACTIVITY 7 .2

Flowcharts can be used for more than writing programs. Work in pairs to produce a flowchart for making a cup of tea, or coffee, or another drink.

153 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Questions 5

6

7

Write the name of each flowchart symbol in the shape. a

b

C

d

I I �

Draw the flowchart symbol for each statement: a Start b INPUT x INPUT y C d IS x>y? e X =x+y f Stop Draw a flowchart to take three numbers as input, find and output the largest number.

7 .4 Pseudocode Pseudocode refers to any code that is not written on a computer to run. There is no one set pseudocode, because if there was then this would be code with a specific language. Instead it's a term for any readable code-like statements that all programmers will understand. This means that it uses keywords, and constructs such as IF statements, WHILE loops, etc. These constructs occur in almost all languages, so any programmer would be expected to read them and translate them into the actual programming language they are using.

Example pseudocode: INPUT Numberl IF Numberl < 10 THEN OUTPUT "too small" ELSE OUTPUT "valid" ENDIF

This uses the keywords INPUT, IF and OUTPUT. These can then be translated into whatever language the programmer is using. Here the pseudocode program is converted into Python, VB.NET and Java.

1S4)

KEY WORD pseudocode: code1 ike statements that are used to design an algorithm but do not follow any specific language.

7

Algorithm design and problem solving

Python

numberl = input() if number < 10: print("too small") else: print("valid")

VB.NET numberl = console.readline() if number < 10 then console.writeline("too small") else console.writeline ("valid") endif

Java

number = Integer.parseint(scanner.nextLine()); if (number < 10) { System.out.println("too small"); }else{ System.out.println("valid");

There are many different valid pseudocode formats. Some will always use capitals for the commands, e.g. INPUT, IF, FOR. Some will use f- instead of an = for assignment. If you write your pseudocode in almost perfect 'code', i.e. you actually write Python code, because it is not to be run and you can have all sorts of syntax errors it is still pseudocode. What is important is that the program is split into steps that can be easily converted into a real program. Table 7.2 shows some examples of valid and invalid pseudocode. Valid pseudocode

Invalid pseudocode

INPUT Value FOR X = 0 to 9 OUTPUT Value + X NEXT X numl = input num2 = input if numl > num2 then print(numl) else print(num2) Endif

Input the value X Loop 10 times In each loop output the loop number added to the input value input = input = if numl if numl

numl num2 is greater than num2 then output numl is not greater than num2 then output num2

Table 7.2: Valid/invalid pseudocode examples

The syllabus includes information about the pseudocode conventions that will appear within examinations. The pseudocode conventions in this book don't always exactly follow the conventions you will see in your exams, but they are still valid. Remember that your syntax doesn't have to be perfect - it is your logic that is important.

155 )

CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

PROGRAMMING TASK 7.1 A computer game stores a number for the user to guess. The user has up to 10 attempts to guess the number. After each turn the program outputs whether the number they guessed is smaller, larger, or equal to the number they are trying to guess. If they have 10 guesses without getting it correct, tell them what the answer is. If they get it correct, output the number of attempts it took them. Getting started 1

Play the game with a partner. Discuss the different steps that you follow. Use this to Identify the inputs, processes and outputs required by this problem.

2

Recap the different components of a structure diagram and the purpose of decomposition.

3

Read an algorithm you have previously written that makes use of: input, output, selection and loops. Revisit the steps you identified in Task 1, which of the four areas is needed in each part.

Practice

1

Decompose the system into its subsystems by creating a structure diagram.

2

Draw a flowchart for the game.

3

Convert your flowchart into pseudocode.

Challenge

1

Is your code efficient? Are there any variables that are used that don't need to be? Can you reduce the number of lines of code?

2

Amend your program so that each time it runs, a random number is generated for the user to guess.

Find an example of a flowchart and turn it into a pseudocode algorithm.

Questions 8 9

Describe the purpose of pseudocode. Tick one box in each row to identify if the statements are appropriate pseudocode statements, or not.

156 )

REFLECTION After completing Programming Task 7.1: How did you approach the programming task? Did you skip the getting started or did you jump straight to the practice? Did that approach work? Will you consider the getting started next time? Did you tackle the challenge yourself? If not, would you revisit this when you are feeling more confident in this topic?

7

Algorithm design and problem solving

Statement

Valid

Invalid

X = X + 1 INPUT z IF y < 6 THEN add 3 to the value entered store the value entered in the variable newValue valuel = INPUT ( "Enter a number") IF number is more than 10 WHILE numberl 0 10 Write a pseudocode algorithm to:

• • •

take three values as input multiply the numbers together output the result. 11 Write a pseudocode algorithm to: • take 10 numbers as input (using a loop) • add together the values • output the total with an appropriate message.

7.5 Coding Once you have decomposed your problem into subproblems, and you have designed the algorithms using flowcharts and/or pseudocode then you can start writing the program in your chosen programming language. This is often referred to as coding. This will also include some iterative testing. This is testing that is carried out while the program is being developed, for example, if you write the program code for one of the subproblems, then you will test it with a range of different data to make sure it is fully working before moving onto the next step.

7.6 Testing When you have finished your program, you need to carry out testing to make sure it: •

fully works



does not crash



meets all requirements.

You will need to identify appropriate test data to use to test the program. There are four types of test data:

• • • •

Normal - data that the program should accept. Abnormal - data that the program should not accept. Extreme - data that is at the edge of what is allowed .

KEYWORDS coding: the writing

of a program using one or more programming languages.

testing: repeated use

of a system to try all different possibilities to make sure the system is fully working and cannot be broken.

test data: the input

data that is used to test a system.

normal test data:

data that a program should accept.

abnormal test data:

data that a program should not accept.

extreme test data:

data that is on the edge of what is allowed.

boundary test data: data that is on

the edge of being accepted, and data that is on the edge of not being accepted.

Boundary - data that is on the edge of being accepted and being rejected .

157 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 1 A program allows the user to enter their age as a whole number between 10 and 100 years. Test data type

Example data

Normal

Any number between 10 and 100 inclusive,

Abnormal

e.g. 10,20,50,100,etc. Any data that is not a number between 10 and 100,

Extreme

e.g. 9, -1,101,200,"age","30", 12.2. The largest number accepted - 100.

Boundary

The smallest number accepted - 10. Either side of the largest bound - 100 and 101. Either side of the smallest bound - 9 and 10.

Example 2 A user needs to enter a password at least 8 characters long. Test data type

Example data

Normal

Any set of 8 or more characters,but they must be text (have speech marks),

Abnormal

e.g. "abcdefgh" "12fghj567812". Any set of characters with 7 or less characters,

Extreme

e.g. "1234567" , "seven". Any with 8 characters only,

Boundary

e.g. "12345678","ajrkdhJK". Either side of the 8 character bound,7 characters or 8 characters, e.g. "1234567","12345678","abcdefg","iJHFD7hJ",

ACTIVITY 7 .4 In pairs find a computer game to play. Anything as simple as a puzzle game, to a full 3D adventure game. Discuss how this game might have been tested. What data would be used as inputs?

Questions 12 Identify three different types of test data.

13 Why can you have the same test data as normal and extreme types of test data? 14 What is the difference between extreme and boundary test data?

15 A program asks the user to input a number between 1 and 10 (inclusive).

7

Algorithm design and problem solving

Identify test data for each of the test data types in the table: Test type

Test data

Normal Abnormal Extreme Boundary

7.7 Common algorithms

KEYWORDS

A search algorithm checks a set of data to identify whether a specific value exists in the data, or not. One example of this is a linear search. A sorting algorithm takes a set of data and rearranges it to be in a specific order, e.g. in ascending alphabetical order. One example of this is a bubble sort.

search algorithm: a

series of steps that searches for a specific value in a set of data.

sorting algorithm:

COMPUTER SCIENCE IN CONTEXT Sorting data and searching for data are activities that a very large proportion of programs will use at some point. For example, outputting a list of data may need sorting into order. A user may enter a username and the program needs to search for this in the set of valid usernames.

a series of steps that will rearrange a set of data into an order, e.g. ascending numerical data.

T here are many different searching and sorting algorithms, each one has its benefits and drawbacks depending on the problem. This could be the number of data items it has to sort through, or whether the data is already in order to search for a value. It is up to the programmer to identify the algorithm that is most appropriate for their program to make sure it is as efficient as possible (both in the time it takes to run, and the amount of memory it needs to perform this task).

Linear search

KEYWORD

In a program you might need to look for a specific value in a set of data. A linear search will check each item one at a time, starting with the first item and continuing

linear search: a

until it either finds the item, or it checks the last value.

ACTIVITY 7.5 Get a set of playing cards. Select 10 random cards and place them face down on the table in a row. Perform a linear search to see if the Ace of Spades is in the set. 1

Turn over the first card.

2

Is it the Ace of Spades?

3

If it is, then stop searching, you've found it.

4

If it isn't, turn over the next card. Repeat from 2.



A

search algorithm that visits each item of data in turn to check whether it is the data being looked for.

•V 159)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 1

Search this set of data for the number 4.

Is

Is

Compare the first number (5) with the search value (4). They are not the same. Compare the second number (3) with 4. They are not the same.

Compare the third number (9) with 4. They are not the same.

Compare the fourth number(4) with 4. They are the same. It has been found.

Example 2

Search this set of data for the character"#". I "a" I "v" Compare the"a" with"#". They are not the same.

, .. , ..

Compare the"v" with"#". They are not the same. Compare the"!" with"#". They are not the same. There are no more values, so"#" is not found.

Example 3

Searching an array (Chapter 8, Section 15 on arrays).

The array dataArray stores a set of data under one identifier. Each element in the array has an index. I Index

Data

Search the array for the number 6 Is DataArray[ 0 J = 6?

No, DataArray[ 0 J = 1

Is DataArray[2 J = 6?

Yes, DataArray[2) = 6

Is DataArray[1 J = 6? 6 was found in index 2.

No, DataArray[l) = 5

This can now be written as an algorithm:

FOR Arrayindex = 0 to LENGTH(Array) -1 //loop through each element //check if the current index is the data searched for IF DataArray[Arrayindex) = SearchValue THEN //if it is, output the index where it is found OUTPUT "Found at & Arrayindex " ELSE //if it not found, increment arrayindex to check the next value Arrayindex � Arrayindex + 1 ENDIF NEXT Arrayindex

160 )

7

Algorithm design and problem solving

This algorithm is inefficient because if it finds the search value then it still continues searching. This is useful if you want to know whether the search value appears more than once. You can make the algorithm more efficient by stopping as soon as the value is found, for example:

Different programming languages use different characters to indicate the start of a comment (there is no closing character). For example,#,//, /* and '. You have to use one of these characters when writing pseudocode, but any one of these is acceptable.

Found� FALSE Arrayindex � 0 //run while the value is not found, and you have not checked //all elements WHILE Found = FALSE AND Arrayindex < LENGTH(Array) DO //check if the current index is the data searched for IF DataArray[Arrayindex) = SearchValue THEN //if it is output where it was found OUTPUT "Found at " & Arrayindex //set found to be true to stop the while loop running //again Found� TRUE ELSE //if it is not found, increment Arrayindex to the next value Arrayindex � Arrayindex + 1 ENDIF ENDWHILE

Bubble sort When writing a program you may need to sort a set of data into a specific order, for example, ascending numerical order or descending alphabetical order.

KEYWORD

One method of sorting data is using a bubble sort.

bubble sort: a

A bubble sort takes the first 2 values; value 1 and 2, and compares them. If they are the wrong way around it swaps them. It then puts these back and takes values 2 and 3 and compares them. If they are the wrong way around it swaps them. This repeats until it has worked all the way through the list once. It then starts again with the first two values. It is called a bubble sort because it acts like a bubble moving across all the elements to the end, then starting from the beginning.

sorting algorithm that moves through the list repeatedly swapping values in pairs.

There are two ways to tell the algorithm when to stop. 1

2

The algorithm has been through the entire list, the number of elements in the list -1. So if there are 10 elements, the algorithm runs 9 times. If there are 100 elements, the algorithm runs 99 times. If there are XElements, the algorithm runs XElements - 1 times. This is the easiest way to program it, but it is not efficient. All elements might be in the correct order to begin with, but it is still going to run through the same number of times. Either the algorithm has run through the list XElements - 1 times, or it has run through the list, checking all of the elements, and it has not made any changes.

161 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

>

ACTIVITY 7 .6 Get a set of playing cards. Select 10 random cards and place them face down on the table in a row. Perform a bubble sort to put the cards in ascending numerical order. 1

Turn over the first two cards.

2

If the 1st is larger than the 2nd, swap them. Otherwise, do nothing.

3

Turn the cards back over.

4

Turn over the 2nd and 3rd cards.

5

Repeat step 2.

6

Repeat turning over the cards and swapping until you have been through all 10 cards once.

7

Did you make any swaps? If so, start again from step 1. If not, stop because the cards should be in order.

A bubble sort can be written as a pseudocode algorithm. There are different versions of the algorithm. Here are two different versions.

Version 1 Stopping only when it has run array length -1 times. //loop array length - 1 number of times FOR NumberPasses � 0 to LENGTH(DataArray) - 1 //loop through each element in the array FOR Index� 0 to LENGTH(DataArray) - 1 //check if the data is in the correct order IF DataArray[Index] > DataArray[Index + 1] THEN //if not swap the items Temp� DataArray[Index] DataArray[Index] � DataArray[Index + 1] DataArray[Index + 1] � Temp ENDIF NEXT Index NEXT NumberPasses

Version 2 Stopping when there are no changes or when it has run array length - 1 times. NumberPasses� 0 //continue until one pass has no changes (changes = false) //or it has looped array length - 1 times WHILE Changes = FALSE or NumberPasses DataArray[Index + 1] THEN //if not swap the items Temp r DataArray[Index] DataArray[Index] r DataArray[Index + 1] DataArray[Index + 1] r Temp Changes r TRUE ENDIF NEXT Index ENDWHILE SKILLS FOCUS 7.1 BUBBLE SORT OF NUMERICAL DATA When you are performing a bubble sort, first identify the order required, e.g. ascending or descending. Then identify the data item being sorted, e.g. is it a number, a letter, a set of words, etc. For example: sort the numbers 6 2 5 1 into ascending numerical order. There are 4 numbers that need sorted into ascending numerical order. This means you keep on sorting until either: a

you have passed through all numbers 3 times

or b

you have passed through all the numbers once without making any changes.

To help guide your working it's often useful to draw a table for each of the items. Draw a table with the four values:

Is

Pass 1. Work through the data items, comparing each pair in turn. If the data is in the wrong order, swap them. Data

Instructions

6

2

6

2

2

6

2

6

2

5 5 5

2 2

5 5 5 5 6

1 1

Compare the first two values.

1

They are in the wrong order so swap them.

1

Compare values 2 and 3.

1

They are in the wrong order so swap them.

6

1

Compare values 3 and 4.

1

6

They are in the wrong order so swap them.

163)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED Now you have completed 1 pass, check if it should stop! Compare to the two criteria: you have passed through all numbers 3 times [False, only 1 pass has been made]

a

or you have passed through all the numbers once without making any changes [False, there has been at least one change]. Pass 2. Work through the data items, comparing each pair in turn. If the data is in the wrong order swap them. b

Instructions

Data 2

5

1

2

5

1

2

5

1

2

1

5

2

1

5

6 6 6 6 6

Compare the first two values. They are in the correct order. Compare values 2 and 3. They are in the wrong order. Swap them. Compare values 3 and 4. They are in the correct order.

Should it stop? Compare to the two criteria: a or

you have passed through all numbers 3 times [False, only 2 passes have been made]

you have passed through all the numbers once without making any changes [False, there has been at least one change]. Pass 3. Work through the data items, comparing each pair in turn. If the data is in the wrong order swap them. b

Instructions

Data 2

1

5

2

1

5

1

2

5

1

2

5

1

2

5

1

2

5

6 6 6 6 6 6

Compare the first two values. They are in the wrong order. Swap them. Compare values 2 and 3. They are in the correct order. Compare values 3 and 4. They are in the correct order.

Should it stop? Compare to the two criteria: a

you have passed through all numbers 3 times [True, 3 passes have been made so

stop].

164 )

7

Algorithm design and problem solving

CONTINUED Questions

1 2

3

How many swaps were made in this bubble sort? Why did it stop after 3 passes? How would you change this process to put the data into descending numerical order?

SKILLS FOCUS 7.2 BUBBLE SORT WITH CHARACTERS INTO DESCENDING ORDER

Put the characters "z" "c" "f' "a" "h" into descending alphabetical order. First identify the data and method. This is string data, and into descending alphabetical order. There are five characters, so keep on sorting until either: a or

you have passed through all characters 4 times

b you have passed through all the numbers once without making any changes. Draw a table with the given characters: z

C

f

h

a

Pass 1. Work through each of the data items once. If the pair is in the incorrect order, swap them. z

C

z

f f

z

f

a

C

a

h h

C

h

a

Should it stop? It has not run 4 times. It has made changes. Repeat. Pass 2.

I:

Should it stop? It has not run 4 times, and it made a change. Repeat. Pass 3.

Should it stop? It has not run 4 times. It has made 1 change. Repeat.

I: 165 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

>

CONTINUED Pass 4.

le

la

Should it stop? It has run 4 times - stop. Questions

1 2

How many comparisons were made that did not result in swaps? How would you change this algorithm to work with strings instead of multiple characters, e.g. 'zoo' 'farm' 'cat' 'horse' 'animal'?

PROGRAMMING TASK 7.2 A program asks the user to enter a set of 20 numbers. The user can then enter a number for the program to search for in the set of data. The program will output if it is found, or not. The program should then put the data into ascending order and output the newly arranged data.

Getting started

1

Practise the linear search process using a set of cards. Lay them out and search them in turn to identify if a specific one is present.

2

Practise the bubble sort process using a set of cards. Lay them out and put them into the correct order following the bubble sort instructions.

3

Recap the programming skills; input, output, selection and iteration. Focus on how to loop 20 times to enter 20 numbers.

4

Read the linear search and bubble sort algorithms with a partner. Follow each instruction in the algorithm.

Practice

1

Identify the inputs, processes and outputs for the problem.

2

Create a structure diagram for the problem.

3

Write a pseudocode algorithm to take in the set of 20 numbers from the user.

4

Amend the algorithm to allow the user to input a number to search for, and then the code to perform a linear search on the data and output the result.

5

Amend the program to perform a bubble sort on the data, and output the arranged program.

Challenge

1

Move the linear search into its own subroutine (procedure or function) so it can be called from anywhere in the main program.

2

Move the bubble sort into its own subroutine and call it from the program.

7

Algorithm design and problem solving

Questions 16 Perform a linear search for the number 6 in the following data:

10

5

6

8

l

2

17 Perform a linear search for the letter "f" in the following data:

b u 1 p f a g h 18 Perform a bubble sort to put the following data into ascending numerical order: I 5 6 2 9 0 1 19 Perform a bubble sort to put the following data into descending numerical order: 60 2 40 52 3 5 20 Explain the difference in efficiency between the two different bubble sort algorithms.

Totalling

KEYWORD

Totalling is adding a group of values together to give a total.

totalling: statements

For example, a person buys items at a supermarket. The items cost: $0.50, $1.00, $1.00, $15.50, $21.30 The total is 0.5 + 1 + 1 + 15.5 + 21.3 = $39.30 To do this in a program you need to: • Initialise a variable to store the total, e.g. Total

CONTINUED 2

Recap how to calculate an average of a set of numbers.

3

30 numbers will need entering. Recap how to loop 30 times.

Practice 1

Write an algorithm to allow the teacher to enter the marks for all 30 students.

2

Amend the program to calculate and output the smallest (minimum) mark.

3

Amend the program to calculate and output the largest (maximum) mark.

4

Amend the program to calculate and output the average mark.

Challenge Extend the program to count how many got below the average, and how many got above the average number of marks. Extend the program to work out how many students got each level. 80 or more = distinction. 60 or more = merit. 40 or more = pass. Below 40 = fail.

Questions

Explain the difference between totalling and counting. 22 A program allows numbers to be entered between 20 and 200, and finds the smallest and largest entered. Identify appropriate values to initialise the variables Smallest and Largest. 23 Write an algorithm to input 40 numbers and output the total and average. 24 Write an algorithm to input 100 numbers and output the smallest and largest. 21

Validation on input

Validation is the checking of data that is input to make sure it is reasonable, and/or within set bounds. For example, making sure that a number is entered for an age or limiting the range of numbers that can be entered.

ACTIVITY 7. 7 Have you ever entered data to be told that it is invalid? What were you trying to enter, and why was it incorrect? Visit some websites that need you to enter some data (but stay safe and make sure it is not personal data). What restrictions do they have? Are there some spaces that you need to enter data in? Do some of them give you a set structure to fill in, for example, a date as __ / __ / ____? Are these all controlled with validation rules?

There are different types of validation.

172 )

KEYWORD validation: the

checking of data to make sure it is reasonable and within set bounds.

7

Algorithm design and problem solving

Range check

A range check assesses whether data is within one or two bounds. For example, an age must be between 0 and 100. A date must be before today's date. Range checks can be programmed using selection to produce an error, or within a loop that keeps asking you enter a value until it is valid.

Example 1

KEYWORD range check: a type of validation that makes sure data is between the minimum and maximum.

Using selection: This algorithm will check whether a number is higher than 1 and less than 10. Number 10 THEN OUTPUT("Invalid") ELSE OUTPUT("Valid") ENDIF

Example 2

Using a loop:

This algorithm will check if a number is higher than 1 and less than 10. It will continually ask for a value to be input until the number is valid. Number 10 DO OUTPUT("Invalid please try again") Number 3 This is FALSE so run the ELSE OUTPUT the value in number2

'

7

Algorithm design and problem solving

SKILLS FOCUS 7.4 TRACE TABLE WITH LOOPS When you are following an algorithm that includes a loop (iteration), some of the code will be repeated. To follow the code run one line at a time as before, and when you get to the end of the loop, go back to the start of the loop. For example: trace the following algorithm with the input values 4, 3, 2, 1, 0. 01 02 03 04 05 06 07 08 09 10

Count 0 is TRUE. Run lines 05, 06 and 07. INPUT InputValue InputValue Value3 THEN OUTPUT(Value2) ELSE OUTPUT(Value3) ENDIF OUTPUT(Valuel + Value2 + Value3) 1 2

First test the algorithm with a set of data that you come up with (if they are not provided for you). For example, test this algorithm using 1, 2 then 3. Create a trace table by following the algorithm with the data input. Value1

Value2

Value3

OUTPUT

1

2

3

3

6 3 4

Repeat the process with a different set of data, for example, this time using 10, 5, 1. Complete the trace table.

184 )

7

Algorithm design and problem solving

CONTINUED Value1

Value2

Value3

OUTPUT

10

5

1

10 16

Keep on repeating this process until you can identify the pattern. In this case it is outputting the largest number input and then outputting the total of the 3 numbers input. Questions 1

2 3

Two sets of data were used to run this algorithm. If you had to choose a third set what would you choose? How do you know when to stop testing the algorithm with different data? Describe the processes in this algorithm and state its purpose using a trace table. Quantity� 0 Total� 0 Value� 0 Small� 999 WHILE Quantity < 5 DO INPUT Value IF Value >= 10 AND Value

structured evidence that leads to a given result.

7 Algorithm design and problem solving

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'. · --- - ·- ---:-i-�--·-·------�· ·--- .--.- -- - -- - - - -·· - -- --. · ,--· 1 Needs more ; Getting ':· r---1:Confident to 1 :1 See '" I can... :. . · ,--·-' I to�i.c .· ·. ___,:w '1 · . '' • .• ., • 'IC• :: , ., ,. ' . · ·· : ve· 2 o l!J1. ere,. .. t on f-ri\!, r h k_ _.__ ···'i[ --- - � - ·- __ ·---·-----· -------�,l _�:

--11-�--� . -, 1r•

identify the stages in the program development life cycle.

7.1

use decomposition to split a system into sub-systems.

7.2

create structure diagrams, flowcharts and pseudocode algorithms.

7.3

explain how a bubble sort and linear search works.

7.7

describe and produce algorithms that include finding the maximum, minimum and average values.

7.7

understand the need for validation and verification and write programs that make use of each.

7.7

identify appropriate test data for an algorithm.

7.6

complete a trace table for an algorithm. check a program for errors and amend the program. explain the purpose of an algorithm.

7.8

7.10 7.9

195 )

learn how to write programs using pseudocode •

use variables and constants



learn about the appropriate use of basic data types



write programs that use input and output



write programs that use sequence



write programs that use arithmetic operators



write programs that use selection including IF and CASE statements



write programs that include logical and Boolean operators



write programs that use iteration including count-controlled, pre-condition and post-condition loops



write programs that use totalling and counting



write programs that perform the string handling methods length and substring



write programs that use nested statements



understand the purpose of subroutines



understand the differences between procedures and functions



write programs that use subroutines



understand the purpose and use of parameters



write programs with subroutines that take parameters

8

Programming

CONTINUED •

write programs with the library routines MOD, DIV, ROUND and RANDOM



understand what makes a program maintainable



add features to programs to improve the maintainability



understand the use of arrays as data structures



write programs using 1-dimensional arrays



write programs using 2-dimensional arrays understand the need to store data in files



write programs to read data from a file



write programs to write data to a file.

GETTING STARTED Find a computing program (or part of a program) that is written in the programming language you will be using in-lesson. Work with a friend to identify what each of the different lines of code do. Present your findings to the class by showing them each line of code and explaining its purpose.

PROGR AMMING LANGUAGES There are lots of different procedural programming languages, for example, Java, VB.NET, Python, C++ and many, many more. They all have different commands, requirements for brackets, some need semi-colons at the end of each line of code. There are, however, a set of programming fundamentals that work in the same way in most (there are always one or two that try to be different) languages. Once you know what these fundamentals are, and how these work, then to program in a new language you just need to check the syntax which that specific language uses. For example, a FOR loop (a type of count­ controlled loop that you will learn about later in the chapter) that will output the numbers 1 to 10. In pseudocode (a generic non-language specific language) this could be:

FOR Count� 1 TO 10 OUTPUT (Count) NEXT Count

laolidienn() 111.dieren Matro • �rnq As Lonq 'Ze:ilenanaahl der Tabell� • arng � !lyte 'SJM,ltenan:r:ahl der Ta!Mlle • nrnq As Strino 1Naae der Tabelle < �reich detin.u:rt nq - Cell■ caow:i .Count, 1) ,!nd(xlOp) .Row ng • Cells fl, COlwana.Count),tnd(xlloLett.),Colw.n nq • Ac:tiveSheet,N.urie, "•" , "RlCl" ' ":R" ' :r:rnq' "C"' arng AceiveWorkboOJc. Pi•otCache■. Create (SourceType: •xlConaolid&tio Array(nrnq, "llen.entl"), Version:•xlPivotTableV crea"tePivotT•ble TableDe:JJl.ination:•"", Tablell DefaultVeraion:••l PivotTableVer■ionli AotiveSbeet. PivotTableWiaard TableDe■tination:•Act Aotive!lheet.Pivot.Tablas("PivotTable2") . Pivot?ielda(• xlH1dde1' Act1.veSheet. PivotTable• ("P1.votTable2") , P1votrieldo("5• XlH1dden With Act1veSheet. PivoeTables ( "P1voeTable2"). Pivot.Fields .Odentation • :dltovP'ield ::1:��:eet,Pivot.Table•("P1votTable2"). RowAn.sLayout xlTabularRov Active Sheet. Pivot.Table• {"P1votTable2").Repeat.All.LatMl• xlltepeat ActivaSheet. PivotTabl••("P1VOtTable2"), Pivotrielda("Zeile") ,Subt

�:!::�,�:!::•( -!:!1:;.::!·

• �t�:!::�.!:�::�t��;:� f�;!::�T:�:;�) , r,1,e false ral••• ruse, ra1aa, ra1aa, raise, Fal••• fal '1'ctive5he�t. Pu•o�Tablea ("P1Vot?ablel"), P1vot.F1el number2 and print(numberl) elif number2 > number3: print(number2) else: print(number3)

number") number") number") numberl > number3:

Java public static void main(String args[]){ Scanner scanner = new Scanner(System.in); System.out.println("Enter a number"); Integer numberl = Integer.parseint(scanner.nextLine()); System.out.println("Enter a number"); Integer number2 = Integer.parseint(scanner.nextLine()); System.out.println("Enter a number"); Integer number3 = Integer.parseint(scanner.nextLine()); if(numberl > number2 && numberl > number3){ System.out.println(numberl); }else if(number2 > number3){ System.out.println(number2); }else{ System.out.println(number3);

PROGRAMMING TASK 8.2 A computer program needs writing to act as a calculator. The program should take in two values and a symbol (e.g. +, -, *or/). Depending on the symbol entered, the calculator should perform that calculation. For example, if 3 5 + is entered, then the result should be 8 (3 + 5 = 8).

Getting started 1

Identify the inputs that the system will require.

2

Identify appropriate variables to store the inputs in.

3

Write a program to ask the user to enter the two numbers and symbol, and store these in variables.

Practice 1

Discuss in pairs which type of selection statement would be most appropriate for checking the symbol input.

2

Edit your program to use your chosen selection statement to check the symbol the user has entered. Depending on the symbol, perform the required calculation and output the result.

230)

8

Programming

CONTINUED Challenge

1

Discuss in pairs how the inputs could be repeatedly asked for until a valid entry is given. For example, keep entering a symbol until one of the valid ones is entered.

2

Implement your idea for repeatedly asking for the symbol to be input until a valid one is entered.

3

Include additional mathematical operations, for example, power of, modulus division.

Questions 8 9 10 11

Describe what is meant by selection. Identify the two different examples of selection. Write a program that takes two numbers as input and outputs the largest. Write a program that outputs a question (e.g. a maths question), takes an answer from a user and outputs if they are correct or not. 12 Ask the user to input a colour. The program should then output a different message if the user enters the word "yel 1 ow", "green" or "blue". If neither of these are entered, the program should output a different message. Use a CASE statement.

8. 7 Iteration An iteration or loop is a programming construct where statements are run either a finite number of times, until a condition is true or while a condition is true. There are three types of loop: count-controlled, pre-condition and post-condition.

Count-controlled This type of loop uses a counter to run a set number of times. The most common count-controlled loop is the for loop. This has the structure: FOR variable� start value TO endvalue

Code that runs repeatedly

NEXT variable

The loop will run from the start value to the end value, increasing by 1 each time. If the start value is 1 and the end value is 10, it will run 10 times (1, 2, 3, 4, 5, 6, 7, 8, 9 and 10).

Example 1 Output the numbers 1 to 10: FOR X � 1 TO 10 OUTPUT(X) NEXT X

KEY WORDS a programming construct. Code is run multiple times either a finite number of times (count­ controlled), until a condition is true (post-condition), or while a condition is true (pre-condition). iteration:

loop: another name for iteration. count-controlled loop: a type of

iteration. Code is run a finite number of times. Usually a for loop. pre-condition loop:

a type of iteration. Code is run while the condition is true. The condition is checked before running any code in the loop, therefore the code might never run. post-condition loop:

a type of iteration. Code is run until a condition is true. The condition is checked after the code in the loop is run, therefore the code always runs once.

231 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

VB.NET For x = 1 To 10 Console.WriteLine(x) Next

Python for x in range(l, 11): print(x)

Java public static void main(String args[]) { for(Integer x = l; x

8

Programming

Example 3 Add together the first 100 numbers: Total 0 FOR Number 1 TO 100 Total Total + Number NEXT Number f-

f-

f-

VB.NET Dim total As Integer = 0 For number = 1 To 100 total = total + number Next

Python total = 0 for number in range(l, 101): total = total + number

Java public static void main(String args[]) { Integer total = O; for(Integer number = l; number = l; number--) { System.out.println(number);

Example 2 Output the numbers from 11 to 20, increasing by 0.5 each time. (No example is given for Python as it does not support stepping in decimals.) FOR Value � 11 TO 20 STEP 0.5 OUTPUT(Value) NEXT Value

VB.NET For value = 11 To 20 Step 0.5 Console.WriteLine(value) Next

Java public static void main(String args[]) { for(Double value = 11.0; value

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Python number = 1 while number < 11: print(str(number)) number = number + 1

Java public static void main(String args[]) { Integer number = 1; while(number < 11) { System.out.println(number); number++;

Example 3 Asking the user to enter a number until they guess the stored number correctly: Number 10

Java public static void main(String args[]){ Integer number = l; do{ System.out.println(number); number++; }while(number = 100 Then number = number + 1 End If End While

Python arrayData = [] #insert code to populate array number = 0 count = 0 while number < 10: datainArray = arrayData[count] count = count + 1 if datainArray >= 100: number = number + 1

Java public static void main(String args[]) { Integer[] dataArray = new Integer[l000]; //insert code to populate array Integer number = 0; Integer count = 0; Integer datainArray = 0; while(number < 10) { datainArray = dataArray[count]; count +=l; if(datainArray >= 100) { number +=l;

253)

)

CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example 3 Output only the vowels in a message input if user selects option 1: OUTPUT("Enter 1 or 2") INPUT Choice IF Choice = 1 THEN OUTPUT("Enter a word") INPUT Word FOR Count� 0 to LENGTH(Word)-1 Character� SUBSTRING(Word, Count, 1) IF Character = "a" OR Character = "e" OR Character = "I" OR Character = "o" OR Character = "u" THEN OUTPUT(Character) ENDIF NEXT Count ENDIF This has a FOR loop inside an IF, and another IF inside the FOR loop.

VB.NET Dim choice As Integer Console.WriteLine("Enter 1 or 2") choice = Console.ReadLine Dim word As String Dim character As String If choice = 1 Then Console.WriteLine("Enter a word") word = Console.ReadLine For count = 0 To Len(word) character = mid(word, count, 1) If character = "a" Or character = "e" Or character = "i" Or character "o" Or character = "u" Then Console.WriteLine(character) End If Next End If

Python choice = int(input("Enter 1 or 2")) if choice == 1: word = input("Enter a word") for count in range(0, len(word)): character = word[count:count+l) if character == "a" or character == "o" or character == "u": print(character)

254)

"e" or character

"i" or character

8

Programming

Java public static void main(String args[]){ Scanner scanner = new Scanner(System.in); System.out.println("Enter 1 or 2"); String word; String character; Integer choice = Integer.parseint(scanner.nextLine()); if(choice == 1){ System.out.println("Enter a word"); word = scanner.nextLine(); for(Integer count = O; count < word.length(); count++){ character = word.substring(count, count + 1); if(character.equals("a") 11 character.equals("e") 11 character. equals("i") 11 character.equals("o") 11 character.equals("u")){ System.out.println(character);

Questions

24 Give one example of a nested statement. 25 What will the pseudocode statement LENGTH ("Hello World!") return? 26 What will the pseudocode statement SUBSTRING("HELLO WORLD! " , 6, 5) return? 27 Write a program to take a string input from the user, count out how many numbers are in the string and output the count. 28 Write a program to output a string value backwards.

KEYWORDS subroutine: a self­

8.12 Subroutines A subroutine is a self-contained piece of code that has an identifier (name), and it can be called from anywhere in the main program. When you decompose a problem into sub-systems, each of the sub-systems can be written as an individual subroutine. You can then call that subroutine when you need to use it. Subroutines are useful because they reduce code. You write the subroutine once, and then you can call it as many times as you need to, instead of having to re-write it every time. Each time you re-write it there is a chance of an error, so this reduces the chances of this error. There are two types of subroutine: procedures and functions. A function returns a value to the program that called it. A procedure does not return a value. Procedures and functions can both take one or more values as parameters. These are values that are sent to the subroutine. Parameters will be introduced after the basics of procedures and functions.

contained piece of code that has an identifier and can be called from elsewhere in a program.

procedure: a

subroutine that does not return a value to the program that called it.

function: a subroutine

that does return a value to the program that called it. parameter: a value that is sent to a subroutine.

255 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Procedures

A procedure runs the code inside it, and does not return a value. The structure of a procedure is: PROCEDURE identifier() code to run inside the function END PROCEDURE

The identifier is then used in the main program.

Example 1 A procedure to output the numbers 1 to 10: PROCEDURE OutputlTol0() FOR Count� 1 to 10 OUTPUT(Count) NEXT Count END PROCEDURE

The main program can then call the procedure with the code: OutputlTol0()

VB.NET Sub Main() outputlTol0() End Sub Sub outputlTol0() For count = 1 To 10 Console.WriteLine(count) Next End Sub

Python def outputlTol0(): for count in range(l, 11): print(str(count)) outputlTol0()

Java public static void outputlTol0() { for(Integer count = 0; count < 11; count++) { Systern.out.println(count); public static void rnain(String args[]) { outputlTol0();

256)

8

Programming

Example 2 A procedure to take two numbers from the user and multiply then together:

PROCEDURE Multiply() OUTPUT ("Enter a number") INPUT Numl OUTPUT("Enter a second number") INPUT Num2 Total� Numl * Num2 ENDPROCEDURE The procedure can be called in the main program with the code: multiply()

VB.NET Sub Main() multiply() End Sub Sub multiply() Dim numl As Integer Console.WriteLine("Enter a number") numl = Console.ReadLine Dim num2 As Integer Console.WriteLine("Enter a second number") num2 = Console.ReadLine Dim total As Integer total = numl * num2 End Sub

Python def multiply() : numl = int(input("Enter a number")) num2 = int(input("Enter a second number")) total = numl * num2 multiply ()

Java public static void multiply() { Scanner scanner = new Scanner(System.in); System.out.println("Enter a number"); Integer numl = Integer.parseint(scanner.nextLine()); System.out.println("Enter a number"); Integer num2 = Integer.parseint(scanner.nextLine()); Integer total = numl * num2; }

public static void main(String args[]) { multiply();

257 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Function

A function returns a value to the program that called it. This can be by either using the RETURN command, or saving a value to the function's identifier. Once a value is returned, the function stops running, so it cannot have any code after otherwise this will not run. It has the structure: FUNCTION identifier() Code to run in the function RETURN value ENDFUNCTION When the function is called it returns a value, so something needs to happen with this value. It could be output, e.g. OUTPUT(function identifier) or it could be saved in a variable, e.g. variable identifier= function identifier

Example 1 Write a function to ask the user to enter two values, add them together and return the value: FUNCTION Multiply() OUTPUT("Enter a number") INPUT Numl OUTPUT( "Enter another number") INPUT Num2 RETURN Numl * Num2 ENDFUNCTION To output the return value the main program can use: OUTPUT(Multiply())

VB.NET Sub Main() Console.WriteLine(multiply()) End Sub Function multiply() Dim numl As Integer Console.WriteLine("Enter a number") numl = Console.ReadLine Dim num2 As Integer Console.WriteLine("Enter a second number") num2 = Console. ReadLine Return numl * num2 End Function

258 )

8

Programming

Python def multiply() : numl = int(input("Enter a number")) num2 = int(input("Enter another number")) return numl * num2 print(str(multiply()))

Java public static Integer multiply() { Scanner scanner = new Scanner(System.in); vSystem.out.println("Enter a number"); Integer numl = Integer.parseint(scanner.nextLine()); System.out.println("Enter a second number"); Integer num2 = Integer.parseint(scanner.nextLine()); return(numl * num2); }

public static void main(String args[]) { System.out.println(multiply());

Example 2 Write a function to total all the values in an array with 50 elements and then return the total: FUNCTION TotalValues() Total ._ 0 FOR X ._ 0 TO 49 Total ._ Total + Array[X] NEXT X RETURN Total END FUNCTION

To store the return value in a variable in the main program: Total = TotalValues()

VB.NET Sub Main() Dim total As Integer total = totalValues() End Sub Function totalValues() Dim arrayData(49) As Integer 'insert code to populate array Dim total As Integer = 0 For x = 0 To 49 total = total + arrayData(x) Next Return total End Function

259 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Python def totalValues(): arrayData = [] #insert code to populate array total = 0 for x in range(0, 50): total = total + arrayData[x] return total total = totalValues()

Java public static Integer totalValues() { Integer[] arrayData = new Integer[50]; //insert code to populate array Integer total = 0; for(Integer x = 0; x < 50; x++){ total = total + arrayData[x]; return total; } public static void main(String args[J){ Integer total = totalValues();

Scope

The scope of a variable is the areas within a program that it can be accessed. There are two scopes: global and local. If you declare a variable (or constant, or array) as global then it means it can be accessed by any part of the program. That includes the main program and any subroutines. In most languages this means declaring it at the top of the program.

Example 1 Declaring a global variable, then outputting its value twice. Once in the main program, and once in a procedure call call. GLOBAL Data PROCEDURE OutputData() OUTPUT(Data) ENDPROCEDURE //main program Data� 1 OUTPUT(Data) OutputData()

260)

KEY WORDS scope: the sections in the code where the variable, or constant, can be accessed. global scope: the variable or constant can be accessed from any part of the program. local scope: the

variable or constant can only be accessed in the subroutine it is declared within.

8

Programming

VB.NET Module Program Dim data As Integer Sub outputData() Console.WriteLine(data) End Sub Sub Main(args As String()) data = 1 Console.WriteLine(data) outputData() End Sub End Module

Python data = 1 def outputData(): print(str(data)) print(str(data)) outputData()

Java class outputting{ static Integer data = l; public static void outputData(){ System.out.println(data); }

public static void main(String args[]){ System.out.println(data); outputData();

If you declare a variable (or constant, or array) as local, then it can only be accessed in the part of the code where it is declared. If you declare it first in a subroutine, then it can only be accessed within that subroutine. If you declare it in the main program, it can only be accessed in the main program.

Example 2 Creating a local variable to the main program and outputting it twice. Once in the main program, and once from a subroutine where it is sent as a parameter. PROCEDURE OutputData(DataParameter) OUTPUT(DataParameter) ENDPROCEDURE Data num2) { System.out.println(numl); }else{ System.out.println(num2)

Subroutines Subroutines help to split the code down into sections, especially when one subroutine may need to be called multiple times. This means that if you need to make any changes then you only need to make them once. For more on subroutines, look back at section 8.12.

ACTIVITY 8.5 Open a computer program that you have written . Check its maintainability. Edit the program to improve the maintainability. Present your before and after program and explain how you improved its maintainability.

Questions 34 Explain how subroutines help make a program maintainable.

35 Describe two other ways of making a program maintainable. 36 Write a program statement to generate a random number between 1 and 5. 37 Identify the result from the statement ROUND ( 3. 142, 1).

269 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

8.15 Arrays

An array is a data structure. It allows you store multiple pieces of data in one structure with one identifier. In an array, each data item must be of the same data type. If it stores integers, then all values must be integers. If it stores strings, then all values must be strings.

1-dimensional arrays A ]-dimensional array has just one row of data. The best way to visualise an array is with a table:

KEYWORDS array: a data

structure where you can store multiple data items, of the same data type, under one identifier.

1-dimensional array:

an array that has only one index.

index: the number of the space in the array.

This array has 5 spaces. Each space has an index. In this array the first data item is in position 0, the data value is 10. In the second array space (index 1), the number 5 is stored. Arrays can be 0-indexed or I-indexed. This depends on the programming language that you use. Some arrays start with Oas the first space. Some arrays start with 1 as the first space. Arrays use brackets after the identifier to indicate the index you want to access. For example, Array [OJ is accessing the first element in the array named Array. MyData[ 3 J is accessing the fourth element in the array named MyData.

Putting data into an array You need to know the array identifier and the position where you want to store the data.

Example 1 Store the colour "red" in the first position of the array named Colour: Colour[O) � "red"

VB.NET Dim colour(O) As String colour(O) = "red" Python colour = [" " , " "J colour[OJ = "red"

270)

8

Programming

Java

public static void main(String args[]) { String[] colour = new String[l]; colour[□] = "red";

Example 2

Store the colour "yellow" in the second position of the array named Colour: Colour[l] � "yellow"

VB.NET Dim colour(l) As String colour(l) = "yellow"

Python

colour [ 11 11 , " 11 ] colour[l] = "yellow"

Java

public static void main(String args[]) { String[] colour = new String[2]; colour[l] = "yellow";

Example 3

Store the number 2 O in the sixth position of the array named Numbers: Numbers[S] � 20

VB.NET Dim numbers(9) As String numbers(S) = 20

Python numbers = [0,0,0,0,0,0,0,0,0,0] numbers[S] = 20

Java

public static void main(String args[]) { Integer[] numbers = new Integer[lO]; numbers[S] = 20;

271 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Getting data out of an array To access data in an array you need to know the identifier and the position of the data you want. This will be a value, so you need to do something with this value, e.g. store it in a variable.

Example 1 Output the first value in the array Colours: OUTPUT(Colours[0))

VB.NET Console.WriteLine(Colours(0))

Python colours = ['red') print(colours[0))

Java public static void main(String args[J) { String[) colours = new String[l0); System.out.println(colours(0J);

Example 2 Store the second value in the array Colours in a variable: TheColour � Colours[l)

VB.NET theColour

colours(l)

Python colours ['red', 'yellow' J theColour = colours[l)

Java public static void main(String args[]) { String(] colours = new String[l0J; colours[0] = "red"; colours[l) = "yellow"; String theColour = colours[l);

272 )

8

Programming

Example 3 Add 10 to the third value in the array Numbers: Valuer 10

+

Numbers[2]

+

numbers(2)

VB.NET value = 10

Python numbers = (0,1,2,3,4] value = 10 + numbers[2]

Java public static void main(String args[]) { Integer[] numbers = new Integer[5]; numbers[0] 0; 1; numbers[l] numbers[2] = 2., numbers[3] = 3; numbers[4] = 4; Integer value = 10 + numbers[2];

Using variables as indices The index in the array might be a variable that stores a number.

Example Ask the user which array element to output from the array colours: OUTPUT("Enter the array element you want to output") INPUT ToOutput OUTPUT(Colours[ToOutput])

VB.NET Dim colours(9) As String colours(0) "red" colours(l) "yellow" colours(2) = "black" "green" colours(3) Console.WriteLine("Enter the array element you want to output") Console.WriteLine(colours(Console.ReadLine))

Python colours = ['red','yellow','black', 'green'] print(colours[int(input("Enter the array element you want to output"))])

273 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Java public static void main(String args[]) { String[] colours = new String[l0]; colours[□] "red"; colours[l] "yellow"; colours[2] "black"; "green"; colours[3] System.out.println("Enter the array element you want to output"); Scanner scanner = new Scanner(System.in); Integer choice = Integer.parseint(scanner.nextLine()); System.out.println(colours[choice]);

Using iteration to read and write If you have a set of values in an array you can use iteration to loop through each of the elements in turn. For example, you might want to output all of the values one at a time. You could add together all of the values in an array and output the total. You might want to take 10 values in from the user and store each one in the array. These are all best done using a count-controlled loop. This is because you usually know how many values you want to enter, or how many values there are in the array that you want to work through.

Example 1 Output all 10 elements in the array Colours: FOR Count� 0 TO 9 OUTPUT(Colours[Count]) NEXT Count

VB.NET Dim colours(9) As String colours(0) = "red" colours(l) "yellow" "black" colours(2) colours(3) = "green" colours(4) = "blue" colours( 5) = "white" "orange" colours(6) "purple" colours(7) colours(8) = "grey" colours(9) = "maroon" For count = 0 To 9 Console.WriteLine(colours(count)) Next

8

Programming

Python colours = ['red','yellow','black', 'green','blue', 'white', 'orange','purple', 'grey','maroon' l for count in range(0, 10): print(colours[count])

Java public static void main(String args[]) { String[] colours = new String[l0]; colours[0] = "red"; colours[l] = "yellow"; colours[2] "black"; colours[3] "green"; colours[4] "blue"; "white"; colours[S] colours[6] = "orange"; colours[?] = "purple"; colours[B] = "grey"; colours[9] = "maroon"; for(Integer count = 0; count < 10; count++) { System.out.println(colours[count]);

Example 2 Ask the user to input 20 numbers and store each in the array Numbers: FOR counter r O TO 19 OUTPUT("Enter a number") INPUT Numbers[Counter] NEXT counter

VB.NET Dim numbers(20) As Integer For count = 0 To 19 Console.WriteLine("Enter a number") numbers(count) = Console.ReadLine() Next

Python numbers = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0J for count in range(0, 20): numbers[count] = int(input("Enter a number"))

275 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Java public static void main(String args[)) { Integer[) numbers = new Integer[20); Scanner scanner = new Scanner(System.in); for(Integer count = 0; count < 20; count++) { System.out.println("Enter a number"); numbers[count) = Integer.parseint(scanner.nextLine());

Example 3 Searching the values in the array values that has 50 values, for the data input by the user: ValueToFind � INPUT("Enter the value to find") FOR Count � 0 TO 49 IF Values[Counter) = ValueToFind THEN OUTPUT("Found it") ENDIF NEXT Count

VB.NET Dim values(49) As Integer 'insert code to populate array Console.WriteLine("Enter the value to find") Dim valueToFind As Integer = Console.ReadLine For count = 0 To 49 Console.WriteLine("Enter a number") If values(count) = valueToFind Then Console.WriteLine("Found it") End If Next

Python values = [ J # insert code to populate array valueToFind = int(input("Enter the value to find")) for count in range(0, 50): if values[counter) = valueToFind: print("Found it")

Java public static void main(String args[)) { Integer[) values= new Integer[50); //insert code to populate array Scanner scanner = new Scanner(System.in); Integer valueToFind = Integer.parseint(scanner.nextLine());

276

>

8

Programming

for(Integer count = O; count < 50; count++) { System.out.println("Enter a number"); if(values[count] == valueToFind) { System.out.println("Found it");

2-dimensional arrays

KEYWORD

A 2-dimensional array is best viewed as a table with rows and columns. Index

0

0

1

2

3

4

10

5 15 10

90 74 85

26 62 4

87 5 24

3

1

7

2

2-dimensional array:

an array that has two indices.

In a 2-dimensional array there are two indices. For example, from the table: Position[O, OJ is 10. Position[O, 2] is 7. Position[4, 2] is 24.

Putting data into an array You need to know which position, i.e. both indices, the across and the down.

Example 1 Store "red" in the first position in the array Colours: Colour[O, OJ � "red"

VB.NET colours(O,O)

"red"

Python numbers = [[''] * 5 for i in range(lO)] numbers[OJ [OJ = "red"

Java public static void main(String args[]) { String[][] colours = new String[lO][10]; colours[OJ [OJ = "red";

277 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Example 2 Store 10 in the array Data, in element 4 across and 3 down: Data[4, 3]

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

ACTIVITY 9 .1 Consider your school. In pairs identify the fields that your school will store about you. Write a list of the fields. Compare your pair's answers with another pair. Were there any differences? Did you add any more to your list?

Data types

KEYWORD

Each field has a specific data type. This identifies what that field can hold. These are similar to the data types you learnt about in programming (Chapter 8).

data type: the characteristics of a piece of data. Common data types are string, integer, real and Boolean.

Table 9.1 shows the common database data types: Data type

Description

Examples

Text

Any combination of letters, symbols and/or numbers.

"Hello"

Alphanumeric

The numbers are treated as text and not numeric, i.e. you can't add them together. These are always speech marks around the data.

Character

A single letter, symbol or number. If it is a number it will be treated as text, i.e. you cannot add to it.

Boolean

One of two options usually True / False or Yes / No. The data does not have speech marks around it.

Integer

A whole number.

"2JK8D" "2198" "Hi!!" II

H"

ll ll y 11

1 ''

"?"

KEYWORDS

True

Boolean: a data type. True or False.

False 123

integer: a data type. Whole numbers.

999

real: a data type.

0 -1928

Real

A number with at least one decimal place.

0.0 1.2 9.99 100.92 -2.9384

Date/time

A date and/or a time.

1/1/2020 8:30 2/3/2020 16:00

Table 9 .1: Database data types

298 )

Decimal numbers.

9

Primary key

Databases

KEYWORD

A primary key is a unique field in a database. This means that it cannot appear twice in different records. It is used to uniquely identify a record. For example, if you want to find a specific person in a database and you enter their name, there could be dozens of people with the same name. If they had an ID number that is unique to only them, then you can access their record straight away.

primary key: a unique identifier for a record.

Look at this database again: Book Name

Author

Publisher

Genre

Fiction

P icking daisies

J. Frank

Cambridge horticulture

Gardening

False

Night stars

K . Mars

Si-fi books

Science fiction

True

Dreaming of the sun

P. Yu

Si-fi books

Science fiction

True

Cooking for fun

W. Crisp

Cookery penguin

Cookery

False

Could any of these five fields be unique? •

Book name: there could be two books with the same names.



Author: one author could write more than one book.



Publisher: one publisher could publisher more than one book.



Genre: more than one book could have the same genre.



Fiction: more than one book could be False, and more than one could be True.

This means that none of these fields is a suitable primary key. So instead we add a key field: Book ID

BookName

Author

Publisher

Genre

Fiction

1

Picking daisies

J. Frank

Cambridge horticulture

Gardening

False

2

Night stars

K. Mars

Si-fi books

Science fiction

True

3

Dreaming of the sun

P. Yu

Si-fi books

Science fiction

True

4

Cooking for fun

W. Crisp

Cookery penguin

Cookery

False

The field Book ID becomes the primary key.

Defining a single-table database To define a single-table database you will need to decide: 1

2 3

the fields that you need the data types for each field the primary key.

299)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example: A shop that sells wool needs to store the items it has in stock. Each item has; a name, e.g. "Sparkle wool", a colour, e.g. "red", a weight, e.g. 2, a price, e.g. $3.99 and a quantity in stock, e.g. 23. To define a single-table database for the shop, you need to:

1. Identify the fields that you need Read the description again and for each item it describes select a field name. Description

Field name

Each item has; a name, e.g. "Sparkle"

Item name

a colour, e.g. "red"

Colour

a weight, e.g. 2

Weight

a price, e.g. $3.99

Price

a quantity in stock, e.g. 23.

Quantity

2. Identify the data types for each field Look at the example data and the description and select the most appropriate data type from the table. Field name

Explanation

Data type

ltemName

"Sparkle" - this is letters therefore string or character. T here is more than one letter so it is not character.

Text

Colour

"red" this is letters and there is more than 1 character. Text

Weight

2 - this is numeric, there is no decimal so it is not real.

Integer

Price

$3.99 - this is numeric, there is a decimal so it is not integer.

Real

Quantity

23 - this is numeric, there is no decimal so it is not real.

Integer

3. Identify a primary key None of these fields are unique, you could have two with the same name, same colour, etc. Therefore a new ID field needs adding to become the primary key. Field name

Data type

IDNumber

Text

ltemName

Text

Colour

Text

Weight

Integer

Price

Real

Quantity

Integer

300)

9

Databases

COMPUTER SCIENCE IN CONTEXT Every time someone creates a new database they have to go through the same process you have just been through. Consider a library. When they set up a new database they have to program the database with the fields and data types that they need to use.

PROGRAMMING TASK 9.1 A clothes store needs a single-table database to store data about its stock. It needs to store the barcode of each item, the name of the product, the colour, size, quantity in stock and whether an order for more products has been made or not.

Getting started 1

Explain what is meant by a record and a field in a database.

2

Identify four data types and describe the data they store.

3

Identify what is meant by a primary key.

Practice 1

Identify the fields for your database table.

2

Identify the data types for your fields.

3

Identify the primary key for your table.

4

Create a paper-based table for this system and complete several records.

Challenge This task goes beyond the range of the specification. Open a database software, e.g. Microsoft Access, and find out how to create a table and add data to it. Create the database for the shop.

Questions 1

Complete the table by giving an example of each type of data.

Data type

Example

Boolean Integer Text Character Real Date/time

301 >

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

2

Describe the format of a database table. Identify the purpose of a primary key. a A social media website stores the following information about its users: username (e.g. daisy l23), password (e.g. HWHRU2D), online name (e.g. Daisy), date account created (e.g. 9/9/2019), number of friends (e.g. 38). Identify the fields and data types for a single-table database for the website. b Identify an appropriate primary key for the table.

3 4

9.2 SOL

KEYWORDS

SQL stands for Structured Query Language. This is a standard language that is used across most types or database to perform actions such as: •

define tables



change tables



add data to tables



search for data from tables (query)



perform calculations using data from tables.

When you write some SQL code you are writing an SQL script. This is series of statements that are commands that are then executed and one or more values are returned.

9.3 SELECT ... FROM This allows you select a set of fields from a table. All of the data in each field will be returned. This table is called Books. Book ID

BookName

Author

Publisher

Genre

Fiction

1

Picking daisies

J. Frank

Cambridge horticulture

Gardening

False

2

Night stars

K. Mars

Si-fi books

Science fiction

True

3

Dreaming of the sun

P. Yu

Si-fi books

Science fiction

True

4

Cooking for fun W. Crisp

Cookery penguin

Cookery

False

SELECT field FROM table

302 )

standard language used to define and manipulate databases.

script: a set of statements that are executed.

In this specification you only need to know the last two of these: search for data and perform calculations using data.

Select has the format:

Structured Query Language (SOL): a

9

Single field:

Databases

The command

SELECT BookName•,-------------------------1 SELECT is followed FROM Books----------------------------, by the field name.

This query will return:

Picking daisies Night stars Dreaming of the sun Cooking for fun

The command FROM is followed by the name of the table .

... ...

IMPORTANT: The field names and table name must be exact. If the field name in the table is 'Genre' then putting 'genre' in the query is incorrect. It is case sensitive.

Multiple fields:

SELECT BookName, Genre FROM Books

... ...

Notice how there are no commas or any other symbol between each field.

This will return

Picking daisies Night stars Dreaming of the sun Cooking for fun

Gardening Science fiction Science fiction Cookery

The order the fields appear in the query are important. The data will be returned in the order they appear in the query. Example:

SELECT BookName, Author FROM Books

The case, spellings - and order are all important in the answer. Putting commas after each one is incorrect . Putting them one after another on a line is incorrect. Each record is on a new line. Each field is separated by a comma (,).

-

Each record is on a new line, Picking daisies and Gardening are on the same line because they are part of the same record.

will return book name then author: Picking daisies Night stars Dreaming of the sun Cooking for fun

J. Frank K. Mars P. Yu W. Crisp

303 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

whereas: SELECT Author, BookName FROM Books will return author then book name: Picking daisies Night stars Dreaming of the sun Cooking for fun

J . Frank K. Mars P. Yu W. Crisp

COMPUTER SCIENCE IN CONTEXT SOL is known as a standard . This means that it is used (almost) universally, no matter what software you are using, or type of database. This means that anyone who knows SOL can use any type of database simply by entering the same SOL code.

Questions These questions use the following database table, PRODUCTS, about products for sale in a shop. ID number

Name

12GH 59RF 3WR

Saturn Vanilla Peanuts Jazz Signet

52D 6SE

Type Chocolate Fudge Nuts Fruit Fudge

Cost

Quantity in stock

0.56 1.9 9

100 20 2 33 5

2.56 0.23 1.48

5

Write the results returned by the following SQL script: SELECT ID number FROM PRODUCTS

6

Write the results returned by the following SQL script: SELECT Name, Type FROM PRODUCTS

7

Complete the SQL script to display the prices of all the products. SELECT .......................................... FROM PRODUCTS

8

Complete the SQL script to display the ID number and name of all the products. ID Number, .......................................... FROM PRODUCTS

9

9

Databases

Complete the SQL scripts to display the Name, Cost and Quantity in stock for all items. ................................., Quantity in stock PRODUCTS

9.4 SELECT ... FROM ... WHERE Including a WHERE clause in the SELECT statement allows you to select only specific data. For example, you only want gardening books, or items that cost more than $3.00.

Single condition (single WHERE)

KEYWORD

This has only one condition. The condition needs a logical operator. These are the same operators that you use in programming (Table 9.2).

logical operator: a

Operator

Description

Example WHERE

=

Equal to.

WHERE Fiction = True


0

>=

Greater than and equal to.

WHERE Quantity> = 100

Not equal to.

WHERE Cost4.0

symbol that performs a comparison resulting in True or False. Can be equals, not equal to, less than, less than or equal to, greater than, greater than or equal to.

Table 9.2: Logical operators

The following queries will use the following table, Orders: Order ID

FirstName

1A 1B

LastName

Numberltems

TotalCost

Qirat

Raja

20

21.99

No

Simon

Tong

2

3.99

Yes

1C

Mei

Liu

1

6.00

Yes

1D

Jenny

Silver

29

59.65

No

Posted

Select where has the format: SELECT SUM field FROM table WHERE condition Equal to SELECT FirstName, LastName, Posted FROM Orders WHERE Posted = Yes This will return: Simon

Tong

Yes

Mei

Liu

Yes

305 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Not equal to SELECT Order ID, Posted FROM Orders WHERE Posted Yes

This query returns: 1A

No

1D

No

Less than SELECT Order ID FROM Orders WHERE Numberitems < 10

This query returns: 1B 1C

Less than or equal to SELECT Numberitems, TotalCost FROM Orders WHERE TotalCost 20

This query returns:

Jenny

Silver

Greater than or equal to SELECT Posted, FirstName WHERE TotalCost >= 3.99

This query returns: Oirat

No

Simon

Yes

Mei

Yes

Jenny

No

306)

9

Databases

Questions

These questions use the following database table, MARKS, about students and their marks in tests. Student ID

Subject

Test name

Percentage

Grade

123

Science

Physics 1

10

Fail

596

Computer Science

Programming 2

53.3

Pass

123

Maths

Trigonometry 6

10

Pass

023

Maths

Trigonometry 6

50

Pass

802

Science

Physics 1

25

Fail

806

Computer Science

Programming 2

46.6

Pass

023

Maths

Trigonometry 7

81

Merit

596

Science

Physics 1

50

Pass

10 Write the results returned by the following SQL script:

SELECT Student ID, Subject FROM MARKS WHERE Subject = "Programming 2"

11 Write the results returned by the following SQL script:

SELECT Student ID, Subject, Grade FROM MARKS WHERE Grade = "Pass"

12 Complete the SQL script to display the Test name, percentage and grade where the

percentage is more than 50 . .......................................... Test name, Percentage, .......................................... FROM ..........................................

WHERE Percentage .......................................... 13 Complete the SQL script to display the student ID, subject and percentage where

the subject is Science. SELECT Student ID, .........................................., .......................................... MARKS SUBJECT

14 Complete the SQL script to display the student ID, test name and percentage

where the percentage is less than or equal to 25. Test name, Percentage

WHERE .......................................... 1 AND Posted = Yes This query returns:

I 1B OR

SELECT FirstName, TotalCost, Posted FROM Orders WHERE TotalCost < 5 OR Posted = No This query returns: Oirat

21.99

No

Simon

3.99

Yes

Jenny

59.65

No

308)

9

Databases

Selecting values in, or not in, a condition The fields in the SELECT do not need to include those in the WHERE. Example: SELECT FirstName, LastName FROM Orders WHERE Posted = Yes This will return the first name and last name of orders where posted is true. It does not return the field posted. It will return:

I

Simon

Tong

Mei

Liu

COMPUTER SCIENCE IN CONTEXT If you log into a website then the code behind the scenes runs a query to find out what your username and password are, and then compares what you entered to these details. This is likely to use an SOL SELECT ... FROM ... WHERE statement.

Questions These questions use the following database table, WEATHER, that store weather readings. Date

Time

Temperature

Wind speed

Humidity

11/12/2019

10:00

20.3

22

59

11/12/2019

13:00

23.7

15

63

11/12/2019

15:00

24.0

13

61

11/12/2019

18:00

23.9

16

60

12/12/2019

15:00

18.4

20

52

12/12/2019

18:00

17.2

18

48

15 Write the results returned by the following SQL script: SELECT Temperature, Wind speed, Date FROM WEATHER WHERE Date = 11/12/2019 AND time < 15:00 16 Write the results returned by the following SQL script: SELECT Date, Time, Humidity FROM WEATHER WHERE Temperature > 20 AND Wind speed < 20

17 Write the results returned by the following SQL script: SELECT Date, Time FROM WEATHER WHERE Temperature > 20 OR Wind speed >= 20

309)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

18 Complete the SQL script to display the time when the date is 12/12/2019 and the humidity is more than 50. SELECT .......................................... FROM ..........................................

WHERE .......................................... = 12/12/2019 .......................................... Humidity > 50

19 Complete the SQL script to wind speed and temperature, when the wind speed is either below 15 or above 20. Wind speed, .......................................... FROM WEATHER WHERE Wind speed ........................... 15 ........................... Wind speed ........................ 20

PROGRAMMING TASK 9.2 These questions will need your shop database table from Programming Task 9.1.

Getting started 1

Identify the command words in an SOL search script.

2

Identify four logical operators and describe the function of each.

3

Identify two Boolean operators and describe the function of each.

Practice 1 a Complete the SOL script to return the name of all the products in the store.

SELECT ....................................... FROM ....................................... 1 b Identify the values that will be returned from your query in 1 a. 2a Complete the SOL script to return the name of all products where an order for more products have been made.

SELECT ....................................... FROM ....................................... WHERE .......................................

2b Identify the values that will be returned from your query in 2a. 3a Complete the SOL script to return the product barcode, colour and size where the quantity in stock is less than 10 and an order for more products has not been made.

SELECT ....................................... , FROM ....................................... WHERE ....................................... AND ....................................... ....................................... ....................................... 3b Identify the values that will be returned from your query in 3a.

310 )

9 Databases CONTINUED Challenge

T his task goes beyond the range of the specification. Find out how to write SOL queries in the database software you have used. Write the queries for practice and run them in your database.

9.5 Order by

This command allows you to state which order the result will be displayed in. There are two options, ascending (ASC) and descending (DESC). The default is ascending. The order by statement comes after the SELECT . . . FROM or SELECT . . . FROM . . . WHERE. The following queries will use the following table, Orders: Order ID

First Name

LastName

Numberltems

TotalCost

Posted

1A

Oirat Simon Mei Jenny

Raja Tong Liu Silver

20

21.99

2

3.99

1

6.00

29

59.65

No Yes Yes No

1B 1C 1D

Example 1: SELECT OrderID, Numberitems FROM Orders ORDER BY Numberitems ASC This query will return: 1C 1B

2

1A

20

1D

29

Example 2: SELECT OrderID, TotalCost, Posted FROM Orders WHERE Posted = Yes ORDER BY TotalCost DESC This query will return: 1C

6.00

1B

3.99

Yes Yes

311 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Questions These questions use the following database table, WEATHER, that store weather readings. Date

Time

Temperature

Wind speed

Humidity

11/12/2019

10:00

20.3

22

59

11/12/2019

13:00

23.7

15

63

11/12/2019

15:00

24.0

13

61

11/12/2019

18:00

23.9

16

60

12/12/2019

15:00

18.4

20

52

12/12/2019

18:00

17.2

18

48

20 Write the results returned by the following SQL script:

SELECT Temperature, Wind speed, Date FROM WEATHER ORDER BY Temperature 21

Write the results returned by the following SQL script: SELECT Date, Time, Temperature FROM WEATHER ORDER BY Humidity DESC

22 Complete the SQL script to display the date, wind speed and humidity in

ascending order of wind speed. Date, Wind speed, Humidity WEATHER Wind speed

23 Complete the SQL script to display the date, time and temperature, in descending

order of humidity. SELECT Date, Time, .......................................... FROM WEATHER ORDER BY ..........................................

24 Complete the SQL script to display the temperature, wind speed and humidity in

descending order of temperature.

Wind speed, .......................................... FROM ..........................................

9.6 SUM SUM command will add up the field that is written after it. It is written in the select statement in the format: SELECT SUM(field) FROM table

312 )

9

Databases

You can also use WHERE conditions. e.g. SELECT SUM(field) FROM table WHERE condition The following queries will use the following table, Orders: Order ID

FirstName

LastName

Numberltems

Total Cost

Posted

1A

Oirat

Raja

20

21.99

No

1B

Simon

Tong

2

3.99

Yes

1C

Mei

Liu

1

6.00

Yes

1D

Jenny

Silver

29

59.65

No

Example 1: SELECT SUM(Numberitems) FROM Orders This query will return: 52 It is calculated from adding together all of the number of items (20 + 2 + 1 + 29).

Example 2: SELECT SUM(TotalCost) FROM Orders WHERE Posted = No This query will return: 81.64 It is calculated from adding together all the total costs where posted is No (21.99 + 59.65).

9.7 COUNT This will count how many records meet the criteria, or how many fields are in the table. Count is in the format: SELECT COUNT(field) FROM table The following queries will use the following table, Orders: Order ID

FirstName

LastName

Numberltems

Total Cost

Posted

1A

Oirat

Raja

20

21.99

No

1B

Simon

Tong

2

3.99

Yes

1C

Mei

Liu

1

6.00

Yes

29

59.65

No

1D

Jenny

Silver

313 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

Example 1:

SELECT COUNT(OrderID) FROM table

The query will return: 4

Example 2:

SELECT COUNT(Nurnberitems) FROM table WHERE Posted = Yes

The query will return: 2

Example 3: SELECT COUNT(OrderID) FROM Orders WHERE Nurnberitems > 10 The query will return: 2

SKILLS FOCUS 9.1 SUM AND COUNT SUM and COUNT are both mathematical operations that perform different functions. SUM This performs addition of a group of values. Example 1, a set of data. 1 +3 + 8 +9+3 =24 Example 2, a table of data.

10 2 9

30 4 5

The SUM is 10+2+9+30+4+5=60 Example 3, an SQL query. This query will use the following table, SALES.

314 )

9

Databases

CONTINUED Order ID

Customer ID

Total

1 2 3 4 5

6 2 8 2 4

20.00 16.25 8.99 3.00 11.50

SELECT SUM(Total) FROM SALES The command word SUM tells you it needs you to add values together. The field in the brackets, Total, tells you to add together the Total column. 20.00 + 16.25 + 8.99+3.00+ 11.50= 59.74 When you are answering questions such as what does this script return when SUM is being used, the only answer is the number. In Example 3, the answer to the question would just be: 59.74 Example 4, table with criteria using the table SALES. SELECT SUM(Total) FROM SALES WHERE Customer ID = "2" This time there is a criteria. Only records with Customer ID being 2 are needed. Order ID

Customer ID

Total

1 2 3 4

6 2 8 2

5

4

20.00 16.25 8.99 3.00 11.50

There are two records with Customer ID 2. The total for these two records are added together. 16.25+3.00= 19.25 The SQL script will return: 19.25

COUNT This counts the number of records (rows). This is not related to the values in the fields, just how many records there are that meet the criteria. Example 1, a set of data. 1, 3, 8, 9, 3. There are 5 values.

315 >

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED Example 2, a table of data. 10 2 9 30 4 5 There are 6 values Example 3, an SQL query. This query will use the following table, SALES. Order ID

Customer ID

Total

1 2 3 4

6 2 8 3 4

20.00 16.25 8.99 3.00 11.50

5

SELECT COUNT(Total) FROM SALES The command word COUNT tells you that you are counting records. The field in the brackets, Total, tells you which to count. 20.00, 16.25, 8.99, 3.00, 11.50 The value returned will be: 5 When you are answering questions such as what does this script return when COUNT is being used, the only answer is the number. In Example 3, the answer to the question would just be: 5 Example 4, table with criteria using the table SALES. SELECT COUNT(Total) FROM SALES WHERE Customer ID = "2" This time there is a criteria. Only records with Customer ID being 2 are needed. Order ID

Customer ID

Total

1 2 3 4

6 2

5

4

20.00 16.25 8.99 3.00 11.50

316 )

8

2

9

Databases

CONTINUED Count how many records have Customer ID 2. There are 2 records. The SQL script will return: 2 Questions

These will use the following table, PRODUCTS: ID number

Name

Type

Cost

Quantity in stock

12GH

Saturn

Chocolate

0.56

100

59RF

Vanilla

Fudge

1.99

20

3WR

Peanuts

Nuts

2.56

2

52D

Jazz

Fruit

0.23

33

6SE

Signet

Fudge

1.48

5

1 2

What is the difference between SUM and COUNT? What will be returned when the following SQL script is run? SELECT SUM(Quantity in stock) FROM PRODUCTS

3

What will be returned when the following SQL script is run? SELECT COUNT(ID number) FROM PRODUCTS

4

What will be returned when the following SQL script is run? SELECT SUM(Cost) FROM PRODUCTS WHERE Quantity in stock > 10

5

What will be returned when the following SQL script is run? SELECT COUNT(Name) FROM PRODUCTS WHERE Cost < 2.00

ACTIVITY 9 .2 T here are other mathematical functions that SOL can perform. Find at least one other example of a mathematical function and how to write an SOL script using it. Take one of the example databases and write a script using your function. Peer Assessment Swap your new function and your script with a partner. Research the new function your partner has used and check whether their script is accurate. If not, discuss the error and how to solve it.

317 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

PROGRAMMING TASK 9.3 T hese questions will need your shop database table from Programming Task 9.1.

Getting started 1

Identify the commands to order a query in descending order.

2

identify the commands to add together a set of values.

3

Identify the commands to count how many records there are.

Practice 1 a Complete the SOL script to return the name of all the products in the store in descending order of quantity in stock.

SELECT ....................................... FROM ....................................... ORDER BY ....................................... 1 b Identify the values that will be returned from your query in 1 a. 2a Complete the SOL script to return the total cost of all products. SELECT ....................................... ( ....................................... ) FROM ....................................... 2b Identify the values that will be returned from your query in 2a. 3a Complete the SOL script to return how many items have been ordered for more products.

SELECT ....................................... ( .................................... ) FROM ....................................... WHERE ....................................... 3b Identify the values that will be returned from your query in 3a.

4

Complete the SOL script to return how many items are red, and have more than 100 in stock, in ascending order by the number in stock.

SELECT ....................................... ( .................................... ) FROM ....................................... WHERE ....................................... AND ....................................... .......................................

Challenge This task goes beyond the range of the specification. Write each of the queries in the practice section in your database and execute them to see the results.

318 )

REFLECTION How did you approach Programming Task 9.3? Did you have other queries with you to check your syntax and to help you answer the questions? How will you make sure you remember the commands?

9

Databases

Questions

These questions use the following database table, ORDERS, that stores details about orders from a shop. Order ID

FirstName

LastName

15

Keanu

Kawai

5

20.59

16

Keanu

Kawai

10

101.12

17

Eka

Loke

3

30.50

18

Keanu

Kawai

2

14.00

19

Ariana

Wang

4

21.10

20

James

Smith

6

44.60

20

156.90

1

10.00

21

James

Smith

22

Ajay

Gupta

Numberltems

TotalCost

25 Write the results returned by the following SQL script:

SELECT SUM(Nurnberitems) FROM ORDERS

26 Write the results returned by the following SQL script:

SELECT COUNT(Nurnberitems) FROM ORDERS

27 Write the results returned by the following SQL script: SELECT COUNT(Numberitems) FROM ORDERS WHERE Nurnberitems > 10

28 Write the results returned by the following SQL script:

SELECT SUM(TotalCost) FROM ORDERS WHERE FirstName = "Keanu"

29 Complete the SQL script to display how many orders James Smith has made.

SELECT .......................................... (FirstName) FROM ORDERS

WHERE FirstName = "James" .......................................... LastName = "Smith" 30 Complete the SQL script to calculate the total cost of orders where 5 or more

items have been ordered. SELECT .......................................... (TotalCost) FROM ORDERS

Nurnberitems .......................................... 5

31 Complete the SQL script to calculate how many orders cost more than 50.00 SELECT .......................................... (Nurnberitems)

FROM .......................................... WHERE ..........................................

319 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

SUMMARY A database stores data about objects such as items, people, orders. A field is one piece of data in a table. A record is a set of fields about one object.

Each field has a data type. T he text or alphanumeric data type stores any combination of letters, numbers and symbols. T he character data type stores one letter, number or symbol. T he Boolean data type stores one of two values, either True or False. T he Integer data type stores whole numbers. T he real data type stores decimal numbers. T he date/time data type can store a date, time, or a date and time. A primary key is a unique identifier in a table. A primary key is used to uniquely identify each record.

SQL stands for Structured Query Language and is a standard for querying databases.

. . . FROM returns all the data in the field given. SELECT . . . FROM . . . WHERE returns all the data in the field where the WHERE condition is true. SELECT

ORDER BY can be ASC (ascending) or DESC (descending) and will return the data in the order specific by the field given. SUM will total the values in the given field.

coUNT will return how many records meet the criteria.

-

COMMAND WORDS

EXAM-STYLE QUESTIONS Define the terms record and field. Give an example of each. 2 Describe the following data types and give an example for each. 1

• • • •

Boolean Real Date / time Text 3 A cinema stores data about the films it is showing. It stores the screen number (for example, 1), the film (for example, The Dark), the date and time of the showing, the number of seats sold (e.g. 150). Define the single-table database for the cinema by identifying the fields, data types, and primary key for the table.

320

>

[2]

define: give precise meaning.

describe: state the

[4]

[7]

points of a topic/ give characteristics and main features.

9

Databases

CONTINUED 4 A hairdressers uses a database, APPOINTMENTS, to store upcoming appointments. Part of this database is shown: Appoint- Date ment ID

12 13 14 15 16 17 a

1/2/2020 1/2/2020 1/2/2020 1/2/2020 2/2/2020 2/2/2020

Time

Empieyee ID

Customer first name

Customer Appointlast name ment type

14:00 14:30 16:00 9:45 11:15 12:30

JP

James Ajay Eka Keanu Ariana Osandi

Smith Gupta Loke Kawai Wang Bandara

AD AD

JP JP AD

Cut Cut and dry Colour Cut and dry Cut Colour

Identify how many records are in the table.

[1]

identify: name/ select/ recognise.

[2]

state: express in clear terms.

[1]

b Identify how many fields are in the table. State what is meant by a primary key, and identify the primary key in the table APPOINTMENTS. d Identify the output from this SQL script:

COMMAND WORDS

c

SELECT EmployeeID, Appointment type FROM APPOINTMENTS [2]

e Identify the output from this SQL script: SELECT COUNT(AppointmentID) FROM APPOINTMENTS WHERE Appointment type = "Cut" [1] f

Complete the SQL script to return the first and last name of all customers with appointments on 1/2/2020. ........................ Customer first name, Customer last name FROM APPOINTMENTS WHERE .............................. ........................

g Complete the SQL script to return the number of appointments JP

[4]

has on 1/2/2020.

SELECT .............................. (Employee ID) APPOINTMENTS Employee ID .............................. [5] [Total: 16]

321 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED 5 A single-table database, SALES, stores details of people who have bought

books online.

Sales ID

Book ID Date

5

10

3/3/2020 1GHF2

1

6.99

6

151

3/3/2020 34FDD

2

10.00

7

230

3/3/2020 34FDD

1

12.00

8

230

3/3/2020 1GHF2

1

12.00

9

10

3/3/2020

2

13.98

10

88

4/4/2020 15DTB

2

10.50

11

209

4/4/2020 1GHF2

3

12.00

12

151

4/4/2020 34FDD

5

25.00

13

28

4/4/2020

2

20.00

Customer ID

P0OO1

34FDD

Quantity bought

Total Cost

a Identify the most appropriate data types for the following fields: • Sales ID • Date • Customer ID • Quantity bought • Total Cost b Give the result from the following SQL script:

[5]

give: produce an answer from a given source or recall / memory.

SELECT Date, CustomerID FROM SALES WHERE CustomerID = "1GHF2" [2]

c Complete the following SQL script to return the customer ID and total cost of each order where more than 1 book were ordered. SELECT Customer ID, ............................................................ FROM ............................................................ WHERE Total Cost ........................... [4] d Give the result from the following SQL script. SELECT Sales ID, BookID FROM SALES WHERE Date = 4 /4/2020 AND Total Cost



know the standard symbols for a range of different logic gates



understand the function of each different logic gate



represent a logic circuit using a truth table and a logic expression



represent a truth table as a logic expression and a logic circuit



represent a logic expression as a logic circuit and a truth table



represent a problem statement as a logic expression, logic circuit and a truth table.

10

Boolean logic

GETTING STARTED Electricity flows through the components of a computer so that it is able to operate. This electricity needs to be controlled in some way so that binary data can be represented. Pretend you are in an elevator and your favourite person walks in. You have 30 seconds to impress them before you arrive at your floor with your knowledge about how a computer controls the flow of electricity. Try and think about everything you know about this already and practise your 30 second speech with your friend now. Ready, steady, go!

FUELLING A COMPUTER As humans, we need food and water to fuel our body each day. Computers need their own fuel to operate and this is electricity. However, the electricity that we supply a computer with has one set voltage. The electricity flow through the different parts of the computer at this set voltage. This would be okay if we only needed the computer to represent data as a single value, e.g. 1. Computers represent data in binary form, so this has two different values, 0 and 1. Therefore, how do we make the electricity have two different states, rather that the single state in which is enters the computer? Easy! It's done through the use of logic gates. Most logic gates in a computer have two input values. These can be two Os, two 1s or a 1 and a 0. Each logic gate has a single output, either a 1 or a 0. The 1 is when the electricity is at a high voltage and the 0 is when the electricity is changed to a low voltage. This means the electricity can flow into a logic gate and will leave the logic gate in either a high or low state. The computer now has two states and these are used to represent the necessary binary values . One way of thinking about the role of a logic gate is to think of it as a switch. It allows the voltage to be switched to a high or low state.

KEYWORDS voltage: the pressure that forces the charged electrons to flow in an electrical circuit. logic gate: a very small component in a computer system that controls the flow of electricity.

It seems quite absurd that the data stored by our computer is just a mixture of high or low voltage electricity, but there is a feeling of wonder that such complex processes in a computer are built upon this simple concept.

,.

0 I

l ----,----

0

l_

Figure 10.1: Logic gates have an output that is either O or 1

325 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED Discussion questions

1

Why do you think that controlling the flow of electricity through a computer is referred to as Boolean logic?

2

What do you think is the purpose of a logic gate?

3

Do you think a computer would be able to operate without the use of logic gates? Why?

10.1 The role of logic gates You learnt in Chapter 1 how data is converted from analogue data to digital data so that it can be processed by a computer. Therefore, you understand that the data that is processed by a computer has two values, 0 and 1. A computer is provided with electricity to function and it needs a way to change this electricity from high voltage (1) to low voltage (0) and vice versa, to be able to represent each binary value that is required. It can do this through the use of logic gates. The reason why this chapter is called Boolean logic is because a Boolean value only has two different states, e.g. true or false, or in a logic gate's case O or 1. Logic gates can have several inputs and depending on the type of logic the gate uses, it will change these inputs in one single output. All the logic gates that you will learn about will have a maximum of two input values. A computer uses thousands of logic gates to output the high or low voltage that is needed to process and store the large quantity of data that it is provided with on a daily basis. The logic gates that you will learn about are the NOT, AND, OR, NAND, NOR and XOR gates.

10.2 The NOT logic gate The NOT gate is the simplest logic gate. This logic gate has only one input and one output. It is used to reverse the input into the gate to output the opposite value. So, if high voltage (1) is input, the output will be low voltage (0). If low voltage (0) is input, high voltage (1) is output. Figure 10.2 shows how to draw a NOT logic gate: Input

-{:>o-

Output

Figure 10.2: A NOT logic gate

A truth table can be used to represent the logic of a logic gate. It shows all the combinations that can be used as input values and what the output value will be for those input values. When doing this it is easier to give the input and output a character as a label, for example, the input can be labelled A and the output can be labelled X. This is a completed truth table for a NOT logic gate:

326)

KEYWORD truth table: a method to show all the different outcomes of an electrical circuit or system, dependent on the inputs it receives.

10

Boolean logic

KEYWORD A logic expression can be used to represent the logic of a logic gate. It shows the logic as a mathematical equation. The logic expression for a NOT gate is: X=NOTA When you are doing further research and practice with Boolean logic, you may find that there are other symbols and notations that can be used in logic expressions. An alternative notation for a NOT gate is:

logic expression: a mathematical representation that is used to represent an electrical circuit or system.

X=A The line over the top of the characterA represents it is NOTA.An interesting point of knowledge to impress your friends with is that the line is called vinculum.

Questions 2

Draw a NOT logic gate. Complete the truth table for the NOT logic gate.A is the input and Xis the output:

3

Write the logic expression for a NOT logic gate.

1

10.3 The AND logic gate TheAND logic gate has two inputs and one output. The only time the output is 1 is when both the inputs are 1.A fun way to think about logic gates is that they are a doorway that has a guard. You and your friend are the inputs and you need the output to be high voltage (1) for the guard to allow you to be able to pass through the doorway. The criteria the guard has set for you to be able to get through the doorway for anAND logic gate is that you and your friend must both have a ticket. If neither of you has a ticket, or only one of you has a ticket, then you will not be allowed through the doorway. Figure 10.3 shows how to draw anAND logic gate: Input 1 Input 2

=D-

Output

Figure 10.3: An AND logic gate

327 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

This time input 1 is labelledA, input 2 is labelledB and the output is labelled X. This is a completed truth table for anAND gate: A

B

X

0

0

0

0

1

0

1

0

0

1

1

1

The logic expression for anAND logic gate is: X=AANDB An alternative notation for anAND gate is: X=A.B The dot symbol(.) between theA and theB represents theAND in this expression.

Questions 4 5

6

Draw anAND logic gate. Complete the truth table for theAND logic gate: A

B

0

0

0

1

1

0

1

1

X

Write the logic expression for an AND logic gate. ACTIVITY 10.1 Look at the truth table that you have completed for question 5. From the results of the logic operations, do you think that an AND gate performs an addition, subtraction, multiplication or division mathematical operation? Why? Peer Assessment Discuss your thoughts from the activity with a partner and see if you agree on the mathematical operation that the AND gate performs. If you don't agree, discuss each of your reasons for your choice and work out who is correct. Did you both arrive at this answer in the same way? Discuss how you worked out your answer.

328)

10

Boolean logic

10.4 The OR logic gate The OR logic gate has two inputs and one output. The output is 1 when either or both the inputs are 1. The criteria the guard has set for you this time to be able to get through the doorway for an OR logic gate is that you or your friend must have a ticket, but both of you don't need one. If neither of you has a ticket, then you will still not be allowed through the doorway. Figure 10.4 shows how to draw an OR logic gate: lnput1 Input 2

j)- Output

Figure 10.4: An OR logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X. This is a completed truth table for an OR gate: A

B

X

0

0

0

0

1

1

1

0

1

1

1

1

The logic expression for an OR logic gate is:

X=A ORB An alternative notation for an OR gate is:

X=A+B The plus symbol(+) between the A and the B represents the OR in this expression.

Questions 7 8

9

Draw an OR logic gate. Complete the truth table for the OR logic gate: A

B

0

0

0

1

1

0

1

1

X

Write the logic expression for an OR logic gate.

329)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

ACTIVITY 10.2

Look at the truth table that you have completed for question 8. From the results of the logic operations, do you think that an OR gate performs an addition, subtraction, multiplication or division mathematical operation? Why? Peer Assessment

Discuss your thoughts from the activity with a partner and see if you agree on the mathematical operation that the OR gate performs. If you don't agree, discuss each of your reasons for your choice and work out who is correct. Did you both arrive at this answer in the same way? Discuss how you worked out your answer.

10.5 The NAND logic gate The NAND logic gate has two inputs and one output. The output is 1 when either input is O or one of the inputs are I. If both inputs are 1, the output is 0. The criteria the guard has set for you this time to be able to get through the doorway for a NAND logic gate is that if both you and your friend are wearing trainers, you will not be allowed through the doorway. If neither of you, or only one of you is wearing trainers, then you will be allowed through the doorway. Figure 10.5 shows how to draw a NAND logic gate: lnput1 =C>- Output Input 2

Figure 10.5: A NANO logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X. This is a completed truth table for a NAND gate: A

B

X

0

0

1

0

1

1

1

0

1

1

1

0

The NAND logic gate is just a simplification of an AND gate followed by a NOT gate (Figure 10.6):

=0------t>o---

Figure 10.6: A NANO gate is a simplification of an AND gate and a NOT gate

330)

10

Boolean logic

If you look at the truth table for the NAND gate, you should notice that the outputs are the opposite of what they are in the AND truth table. This is because the NOT gate takes the output of the AND table as its input, then reverses it to the opposite value. The logic expression for a NAND logic gate is: X=A NANDB An alternative notation for a NAND gate is: X=A.B The dot symbol(.) between the A and theBand then the line over both inputs and the dot, represents the NAND in this expression. COMPUTER SCIENCE IN CONTEXT You may remember that you studied how data is stored using solid-state storage in the hardware chapter. In Chapter 3, you learnt that NAND gate technology is one of the technologies used to create solid-state storage.

Questions 10 Draw a NAND logic gate. 11 Complete the truth table for the NAND logic gate:

A

B

0

0

0

1

1

0

1

1

X

12 Write the logic expression for a NAND logic gate.

10.6 The NOR logic gate

The NOR logic gate has two inputs and one output. The only time the output is 1 is when both inputs are 0. The criteria the guard has set for you this time to be able to get through the doorway for a NOR logic gate is that neither of you are wearing trainers. If either or both of you are wearing trainers, then you will not be allowed through the doorway. Figure 10.7 shows how to draw a NOR logic gate: Input 1 Input 2

D-

0 utput

Figure 10.7: A NOR logic gate

331 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Input 1 is labelled A, input 2 is labelled B and the output is labelled X. This is a completed truth table for a NOR gate: A

B

X

0 0 1 1

0 1 0 1

1 0 0 0

TheNOR logic gate is just a simplification of an OR gate followed by a NOT gate (Figure 10.8):

=D-[>er-

Figure 10.8: A NOR gate is simplification of an OR gate and a NOT gate

If you look at the truth table for theNOR gate, you should notice that the outputs are the opposite of what they are in the OR truth table. This is because theNOT gate takes the output of the OR table as its input, then reverses it to the opposite value. The logic expression for aNOR logic gate is: X=ANORB An alternative notation for aNORgate is: X = A+B The plus symbol (+) between the A and the B and then the line over both inputs and the +, represents theNORin this expression.

Questions 13 Draw a NOR logic gate. 14 Complete the truth table for theNOR logic gate:

A 0 0 1 1

B 0 1 0 1

X

15 Write the logic expression for aNOR logic gate.

332)

10

Boolean logic

10. 7 The XOR logic gate The XOR logic gate is also known as the EOR gate. This is because it is known as the exclusive OR gate. It has two inputs and one output. The only time the output is 1 is when one of the inputs is 1. If both inputs are O or 1, then the output is 0. The criteria the guard has set for you this time to be able to get through the doorway for a XOR logic gate is that one of you is wearing trainers. If neither or both of you are wearing trainers, then you will not be allowed through the doorway. Figure 10.9 shows how to draw a XOR logic gate: Input 1 � Output Input 2�

Figure 10.9: An XOR logic gate

Input 1 is labelled A, input 2 is labelled B and the output is labelled X. This is a completed truth table for an XOR gate: A

B

X

0

0

0

0

1

1

1

0

1

1

1

0

If you look at the truth table for the XOR gate, you should notice that the outputs are very similar to what they are in the OR truth table. The only difference is that if both inputs are 1, the output is 0. The logic expression for a XOR logic gate is:

X=AXORB An alternative notation for an XOR gate is:

X=A(±)B The plus symbol ( +) within a circle, between the A and the B, represents the XOR in this expression.

Questions 16 Draw an XOR logic gate. 17 Complete the truth table for the XOR logic gate: A

B

0

0

0

1

1

0

1

1

X

18 Write the logic expression for an XOR logic gate.

333 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

SKILLS FOCUS 10.1 REPRESENTING LOGIC CIRCUITS A logic circuit is a combination of several logic gates that are linked. Figure I 0.10 shows a simple logic circuit: A B

y C Figure 10.10: A simple logic circuit

There are three different inputs to this logic circuit: A, B and C. There is one output from this logic circuit that is labelled Y There are three different logic gates in this logic circuit: NOT, OR and AND. You need to be able to complete a truth table for a logic circuit, so let's learn how to do that. First you need a truth table to complete. As this logic circuit has three inputs, so there can be eight different combinations to consider: A

B

C

0

0

0

0

0

1

0

1 1

0

0

0

0

1

1 1

0

0

1 1 1 1

y

1

1

If you look at the values in the truth table, what do you notice about the order of each combination? If you think about each row as a 3-bit binary value, you should notice that they increment from 0 to 7 in denary. For example, 000 = 0, 001 = 1, 010 = 2, 011 = 3, etc. In the logic circuit, as the output from the OR gate and the NOT gate become the inputs for the AND gate, it helps to give these a label so that it is easier to track values for them. In this example, Figure 10.11, the labels D and E are used. A B

y C Figure 10.11: A simple logic circuit with labels D and E added

334)

10

Boolean logic

CONTINUED You can add these labels into the truth table to work out what these interim values are: A

B

0 0 0 0

0 0

1 1 1 1

1

1

0 0 1 1

C 0 1 0 1 0 1 0 1

D

E

y

You can now begin to fill in the values in the truth table. You need to complete the output for the OR gate in the column labelled D. You have learnt that the logic of an OR gate is that if either or both inputs are 1, the output is 1. You are just looking at the values in columns A and B for this, as these are the inputs to the OR gate. You can ignore what is in column C for now. This is the truth table with column D completed: A

B

0 0 0 0

0 0

1 1 1

1

1 1

0 0 1 1

C 0 1 0 1 0 1 0 1

D

E

y

0 0

1 1 1 1 1 1

You need to complete the output for the NOT gate in the column labelled E. You have learnt that the logic of a NOT gate is that it reverses the input value to be the opposite value. You are just looking at the values in column C for this, as this is the input to the NOT gate. You can ignore what is in the other columns for now. This is the truth table with column E completed: A

B

0 0 0 0

0 0

1 1 1 1

1 1

0 0 1

1

C 0 1 0 1 0 1 0 1

D 0 0 1 1 1 1 1 1

E

y

1 0

1 0

1 0

1 0

335 )

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

CONTINUED You can now complete the final output column that is the output for the logic circuit, this is column Y You have learnt that the logic of an AND gate is that the only time the output is 1 is when both inputs are 1. You are just looking at columns D and E for this, as they are the inputs to the AND gate. This is the truth table with the final output column completed: A

B

C

D

E

y

0

0

0

0

1

0

0

0

1

0

0

0

0

1

0

1

1

1

0

1

1

1

0

0

1

0

0

1

1

1

1

0

1

1

0

0

1

1

0

1

1

1

1

1

1

1

0

0

You now know how to complete a truth table for a logic circuit, excellent! Questions

1

Complete the truth table for the given logic circuit in Figure 10.12: A----� Q

Figure 10.12: Complete the truth table for this logic circuit

A

B

C

0

0

0

0

0

1

0

1

0

0

1

1

1

0

0

1

0

1

1

1

0

1

1

1

336)

Workspace

Q

10

Boolean logic

CONTINUED 2

Complete the truth table for the given logic circuit in Figure 10.13:

z Figure 10.13: Complete the truth table for this logic circuit

p 0 0 0 0 1 1 1 1

R 0

Q

0 0 1 1 0 0 1 1

Workspace

z

1

0 1 0 1 0 1

10.8 Logic expressions

You need to be able to write a logic expression for a logic circuit. The first thing you need to do to be able to write this is to break down the different parts of the logic circuit. Let's look at the logic circuit in Figure 10.14 as an example: A B

y C

Figure 10.14: A simple logic circuit

The first part to the logic circuit is the OR gate. The logic expression for this part is A ORB. The second part of this logic circuit is NOT and the third part of this logic circuit in the AND gate. So, the three parts to this logic circuit are: AORB NOTC AND

337 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

You can now start to join these different parts together to create the complete logic expression. You should always start with the label for the final output followed by an equals symbol(=):

Y= One of the simplest ways to complete the expression is to then add the final gate in the logic circuit as everything else is built around this:

Y=AND Then add the part that creates the first input to this gate. You should put this into brackets to show that it is a different part of the logic expression:

Y =(A ORB) AND Then add the part that creates the second input to this gate to create the complete logic expression: Y = (A OR B) AND (NOT C) Let's look at a larger logic circuit (Figure 10.15) as a second example:

z Figure 10.15: A larger logic circuit

First, break down the logic circuit into its different parts:

PNANDQ NOTQ XOR ANDR Then join together these different parts to create the logic expression. Remember, a simple way to do this is to start with the final logic gate and work from right to left.

Z =ANDR Z =(XOR) ANDR Z = ((PNANDQ) XOR) ANDR Z =((PNANDQ) XOR (NOT Q)) ANDR You now know how to write a logic expression for a logic circuit, that's awesome!

338)

10

Boolean logic

Questions 19 Write the logic expression for the given logic circuit: A

----� Q

Figure 10.16: Find the logic expression for this circuit

20 Write the logic expression for the given logic circuit:

X

Figure 10.17: Find the logic expression for this circuit

10. 9 Representing truth tables You have learnt how to complete a truth table for a logic expression and a logic circuit. You now need to learn how to write a logic expression and draw a logic circuit from a truth table. Let's start with a simple truth table that has two input values A and B: A

B

X

0 0

0

0

1

1

0

0

1

1

1

0

If you look at this truth table, the first thing you should ask yourself if whether you know any single logic gates that would produce this truth table. It doesn't match any of the truth tables that you have learnt previously in this chapter for each of the logic gates, therefore you now know it must be a combination of at least two logic gates. When you are creating a logic expression and a logic circuit from a truth table, you only need to know how to do this using three of the logic gates that you have learnt: the NOT gate, the AND gate and the OR gate. Once you have looked at the truth table to see if it represents a single logic gate that you know, if you find it doesn't, you can move onto the next step which is finding out which gates will create that truth table.

339 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Looking at the truth table again: A

B

X

0 10 1 1

0 1 0 1

0

1I 0 0

It has one output value that is a 1, so this is what you need to concentrate on. You need to use an AND gate to create this output. At present an input value of A =0 and B =1 will not result in an output of 1 using an AND gate. You should remember that for the output to be I for an AND gate, both inputs need to be 1. Therefore, you need to reverse input A, which is 0, to make it 1. You should remember that to reverse the input value to create the opposite value as an output, you should use a NOT gate. That makes the logic expression for this truth table: X =(NOT A AND B) You can then draw a logic circuit for this (Figure I0.18): A-----1 X

B------� Figure 10.18: The logic circuit for logic expression X = (NOT A AND B)

Let's look at another truth table: A

B

X

0 0 1 1

0 1 0 1

0 11 0 11

This time the truth table has two output values that are 1, so you need to focus on both of those. You have the same situation again with the first output of 1, so you already know that this part is NOT A AND B. A

0 0 1 1

B 0 1 0 1

X 0 1 0

NOT AAND B

11

You now need to look at the second output value of 1. You need to think whether an input of 1 for A and an input of 1 for B will create an output of 1 if an AND gate is used. You should recognise that it will. This means that this part is A AND B.

340)

10

A

B

X

0

0

0

0

1

1

1

0

0

1

1

1

Boolean logic

---- NOT AANDB -----AANDB

Now that you have worked out what the part of the logic expression is for each output value of 1, you need to join these together using an OR gate. That makes the logic expression for this truth table: X = (NOT A AND B) OR (A AND B) You can then draw a logic circuit for this (Figure 10.19):

X

Figure 10.19: The logic circuit for logic expression X = (NOT A AND B) OR (A AND B)

Let's now look at a truth table that has three input values A, B and C: A

B

C

X

0

0

0

0

0

0

1

1

0

1

0

0

0

1

1

0

1

0

0

0

1

0

1

1

1

1

0

0

1

1

1

1

This makes the process more complex and there are several methods that you can use to work out the logic expression. Each method may generate a slightly different logic expression, but they all should produce the same truth table. It is the structure of them that will change slightly, but the logic of them will ultimately produce the same result. The first method you can use is a method called sum of products. In this method you need to create a sum of products expression for each row in the table that has an output value of 1. In a sum of products statement, you need to look at each input value. If it is 1, then in the expression it will be, for example, A. If it is 0, then in the expression it will be, for example, NOT A. Each input is then summed, this is done using the AND gate.

341 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Let's look at the first row with an output of 1 in the table: A

B

C

X

0

0

0

0

0

0

1

1I

0

1 1

0

0

1

0

0

0

0

0

1

1

1 1

0

0

1

1

0

1 1 1 1 In this row: •

A is O so that's NOT A.



B is O so that's NOT B.



C is 1 so that's C.

These are then joined using AND gates making: NOT A AND NOT B AND C You need to follow this process for each row in the truth table that has an output of 1. You should see this result when you do: A

B

C

X

0

0

0

0

0

0

1

1

0

1

0

0

0

1

1

0

1 1 1 1

0

0

0

0

1

1

1

0

0

1

1

1

----NOTAANDNOTBANDC

-----AANDNOTBANDC -----AAND BANDC

Each of the sum of product expressions is then joined together with an OR gate creating the final expression: X = (NOT A AND NOT B AND C) OR (A AND NOT B AND C) OR (A AND B AND C) A person would normally look to then simplify this statement, but you do not need to understand how to do this. You could research how to do this though if you wanted to give yourself a challenge. The second method you could use looks for the constant values in each row where the output is 1.

342

>

10

Boolean logic

Let's look at another truth table: A

B

C

X

0 0 0 0

0 0

0

0

1

1

0

0

1

1

0 0

0

0

1

0 1

1

0 1

1

1 1 1

1 1

1

1

Again, you look at the rows that have an output of 1. If you look at the first row with an output of 1, the input values are A = 0, B = 0, C= 1. You need to look to see if any of these values are constant. This means, are there any values that are the same between the inputs. You should notice that the input values for A and B are the same, 0 and 0. You now need to look whether inputs of 0 and 0 for A and B always result in an output of 1 in each row in the table. If they do, this means that the expression for this row is: NOT A AND NOT B If they don't always result in an output of 1, then you use the sum of products expression for the row instead. If you look at row 1 in the table, you should notice that A and B both have an input of 0, but that the output is 0 and not 1. Therefore, you need to use the sum of products expression for row 2 instead, which is: NOT A AND NOT B AND C This is because we need to apply the rule you learnt earlier about reversing the inputs to make sure that the values will give an output of 1 for an AND gate. If you look at the next row that has an output of 1, you should see that the inputs are A = 0, B = 1, C = 1. This time it is B and C that have the constant value as they are both the same. You now need to look at whether all rows in the table where B and C have the value 1, the result is an output of 1. You should be able to notice that the only other place in the table where the inputs are both 1 is row 8, the final row. This does result in an output of 1 as well, so this means that the expression for this row is:

AANDC If you look at the final two rows in the table, they both that have an output of 1. If you have two outputs of 1 together like this, you can treat them as a pair. You apply the same method to see if there are any values that are constant. In row 7 the values are A=1, B =1 and C=0, and in row 8 the values are A= 1, B = 1 and C=1. You should notice that the A and B inputs are constant in both of these rows. You now look to see if there are any other instances of A and B both having an input of one in the table to see if this results in an output of 1 also. There are no other instances, so this means the expression for these two rows is:

AANDB These three expressions are then joined together again with an OR gate, giving a final expression of:

X = ( NOT A AND NOT B AND C) OR (A AND C) OR (AANDB)

343 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

If you work out the statement using the sum of products method, you will get: X = (NOT A AND NOT BAND C) OR (NOT A AND BAND C) OR (A AND B AND NOT C) OR (A AND BAND C) The two statements represent the same truth table, but you can see that the second method creates a shorter statement, which can be helpful if there are lots of outputs of 1 to be considered.

Question 21

Look at the given truth table: A

B

X

0

0

1

0

1

1

1

0

0

1

1

0

a b

Write a logic expression to represent the given truth table. Draw a logic circuit to represent the given truth table.

10.10 Representing logic expressions You need to be able to look at a logic expression and create a logic circuit and a truth table from the expression. Let's look at a simple logic expression: Z =(RANDS) OR (RANDT) You should notice that this logic expression has: •

3 input values: R, S and T



an output value of Z



uses the logic gates AND and OR.

If you look at the brackets you can see that the expression has two main parts that are joined together by an OR gate. You should learn from this that the OR gate will be the final gate in the logic circuit. You can the draw this part of the circuit (Figure 10.20): You the need to look at the parts of the expression that are in the brackets. Each bracketed section is an input into the OR gate that you have drawn. This means that the first input to the OR is the output of RANDS (Figure 10.21): R

Figure 10.21: The logic circuit for the expression Z =(RANDS) OR (something)

344)

D-z Figure 10.20: The logic circuit for the expression Z = (something) OR (something)

10

Boolean logic

The second input to the OR is the output ofRANDT(Figure 10.22): R

z

Figure 10.22: The logic circuit for the expression Z =(RANDS) OR (RANDT)

You now have a logic circuit that represents the logic expression! You can now use what you have previously learnt to represent that as a truth table:

R 0 0 0 0 1 1 1 1

s

0 0

T

z

0

0

1

0

0

0

1

0

0 0

0

0

1

1 1

1

0 1

1

1

1

1

Let's look at another logic expression: X =((AAND B) OR NOT C) XOR (B NOR C) You should notice that this logic expression has: •

3 input values: A, B and C



an output value of X



uses the logic gatesAND, OR, NOT, XOR and NOR.

You can use the same method as before to structure the logic circuit. You should be able to see again that the expression has two main bracketed sections. You will also notice this time that one of those bracketed sections has brackets within it as well. First, you should notice that the final logic gate in the logic circuit will be an XOR gate. You can now begin to draw the circuit (Figure 10.23): If you look at the larger bracketed area to the left of the XOR in the statement you can begin to break this down. This will become the first input for the XOR gate.The bracketed section within this isAAND B.The brackets around this mean that the output ofAAND B needs to become the input of the remaining part of this whole section. The remaining part is OR NOT C. What you should learn from this is that the output onAAND B will become the input to an OR gate and that the second input to the OR gate will be NOT C. You can now continue to draw the circuit (Figure 10.24):

D-x Figure 10.23: The logic

circuit for the expression X = (something) XOR (something)

345 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

A

B

X

C Figure 10.24: The

logic circuit for the expression X = ((A AND B) OR NOT C) XOR (something)

You now need to look at the final bracketed section as this will create the second input for the XOR gate. This is B NOR C, so you can now complete the logic circuit (Figure 10.25): A

B

X

C Figure 10.25:

The logic circuit for the expression X = ((A AND B) OR NOT C) XOR (B NOR C)

Questions

22 Complete the truth table for the logic statement:

X = ((A AND B) OR NOT C) XOR (B NOR C) A

B

C

0

0

0

0

0

1

0

1

0

0

1

1

1

0

0

1

0

1

1

1

0

1

1

1

X

23 Draw a logic circuit to represent the logic expression:

Z = (A OR B) NAND ((C AND B) OR NOT A))

346)

10

Boolean logic

10.11 Representing problem statements The final thing you need to be able to do is to write a logic expression, draw a logic circuit and complete a truth table for a problem statement. A problem statement is when a logic problem is described in natural language and you are given criteria for the logic of the problem within that description. An example of a problem statement is: A factory manufactures soap and has a system that monitors the manufacturing process. The system has three conditions to monitor the acidity (A) the temperature (T)

and the pressure (P).

The conditions for the system are: Input

Binary value

Condition

A

1

T

0 1 0

pH? Temperature< 50 °C Temperature>= 50 °C

p

1

Pressure>= 75% Pressure< 75%

0

The system will sound an alarm (X) when certain conditions are detected. The alarm will sound when: the pressure>= 75% and the temperature>= 50 °C or the temperature< 50 °C and the pH> 7 You can begin to break down this problem and write a logic expression for it . You can take the alarm conditions line by line and break them down to create each part of the expression. Let's look at the first line of the alarm condition: The pressure>= 75% and the temperature>= 50 °C You should notice this involves the inputs P andT. You need to work out what the binary value for the input is for each of these conditions. You can do this by looking at the table you are given. You should work out that P = 1 andT = 0. This line of the problem statement states that if both of those conditions happen, the alarm will sound. This means that the expression would use an ANDgate and that both inputs must be 1 going into that ANDgate in order to create an output of 1 to sound the alarm. AsT = 0, this value will need to be reversed and you should remember that you can use a NOT gate to do this. This means that the expression for this part of the problem statement is: PANDNOTT

347 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

The second line of the alarm condition is simply an OR. You should learn from this that the two sets of conditions will be separated using and OR gate. This means that expression now becomes: (PANDNOTT) OR The third line of the alarm conditions is: The temperature< 50 °C and the pH> 7 You should notice this involves the inputsT andA. You again need to look at the table to work out the binary value for the input for each condition. You should work out thatT = 1 andA = 0. It states that both of the conditions needs to be met for the alarm to sound, so the expression for this part of the problem is: TANDNOTA You can now add this to the other part and create the full logic expression for the problem statement, which is: X = (PANDNOTT) OR (TANDNOTA) Using what you have previously learnt, you can create the logic circuit and the truth table from this to represent the problem statement (Figure 10.26):

X

REFLECTION

Figure 10.26:

The logic circuit for the soap factory problem statement

A

T

p

X

0 0 0 0 1 1 1 1

0 0 1 1 0 0 1 1

0 1

0

0 1

1

0 1 0 1

0

348)

1 1 1 0 0

Which type of Boolean logic task do you prefer to work out? For example, do you prefer to draw a logic circuit for a logic expression, do you prefer to complete a truth table for a logic circuit? Why do you prefer that Boolean logic task?

10

Boolean logic

COMPUTER SCIENCE IN CONTEXT As you can see from studying problem statements, many systems use more than one sensor to monitor processes such as manufacturing. The data from each of these sensors provides an input into a logic circuit to determine what the output will be. Some manufacturing business use as many as ten different sensors in a logic circuit to monitor their manufacturing processes. That would be one huge logic circuit!

SUMMARY A logic gate is a component in a computer that controls the flow of electricity. A single value is output from a logic gate, this can be a 1 or 0. 1 sets it to high, 0 sets it to low. A problem statement is a description of the conditions of an electrical system. A logic circuit is a diagrammatic representation of an electrical system showing the logic gates it uses. The logic gates it can use are NOT, AND, OR, NAND, NOR and XOR. A truth table is a representation of all the different outputs of an electrical system, dependent on the values of each input. A logic expression is a mathematical representation of an electrical system.

EXAM-STYLE QUESTIONS 1

COMMAND WORD

State the purpose of a logic gate in a computer system.

2 Draw the single logic gate that would generate the given truth tables: a

A

B

0 0

0

1 1

b

state: express in clear terms.

X 0

1

0

0

0

1

[1]

1 [1]

A

B

X

0 0

0

1

1

1

1

1

0

0

0 0 [1] [Total: 2)

349)

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

CONTINUED 3 Consider the truth table: A

B

X

0

0

1

0

1

0

1

0

1

1

1

1

a Write a logic expression to represent the given truth table. b Draw a logic circuit to represent the given truth table.

[4] [4] Total: 8] [

4 Consider the truth table:

s

T

p

z

0

0

0

0

0

0

1

1

0

1

0

1

0

1

1

0

1

0

0

1

1

0

1

1

1

1

0

0

1

1

1

0

Write a logic expression to represent the given truth table. 5 Consider the logic circuit:

[5]

y

a Write a logic expression to represent the given logic circuit.

350)

[3]

10

CONTINUED

Bool ean logic

b Complete the truth table to represent the given logic circuit: L

0 0 0 0

1 1 1 1

M 0 0 1 1 0 0 1 1

Workspace

N 0 1 0 1 0 1 0 1

y

[4]

[Total: 7)

6 A greenhouse has a system that monitors the growing conditions for fruits and vegetables. The system has three conditions to monitor the moisture level of the soil (M) the temperature (T) and the humidity (H). The conditions for the system are: Input M

Binary v a lu e

1 0 1 0

T

1 0

H

Condition

Moisture level 80% Moisture level 35 °C Temperature= 65% Humidity< 65%

The system will sound an alarm (X) when certain conditions are detected. The alarm will sound when: The moisture level 35 °C and the humidity is >= 65% a Write a logic expression to represent the problem statement for the alarm system for the greenhouse. b Draw a logic circuit to represent the problem statement for the alarm system for the greenhouse. c Complete the truth table to represent the problem statement for the alarm system for the greenhouse. I

[3]

[5]

Workspace

351 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUT ER SCIENCE: COURSEBOOK

CONTINUED M

T

H

0

1

0

0

1

1

1

0

0

1

0

1

1

1

0

1

1

1

X

Workspace

[4] Total: 12 [ ]

SELF-EVALUATION CHECKLIST After studying this chapter, think about how confident you are with the different topics. This will help you to see any gaps in your knowledge and help you to learn more effectively. You might find it helpful to rate how confident you are for each of these statements when you are revising. You should revisit any topics that you rated 'Needs more work' or 'Getting there'. I can...

See topic

draw logic gates using the standard symbols.

10.1-10.7

describe the logic of each different logic gate.

10.1-10.7

complete a truth table for each logic gate.

10.1-10.7

identify the single logic gate the represents a given truth table.

10.1-10.7

complete a truth table to represent a logic circuit.

10.1-10.7

write a logic expression to represent a logic circuit.

10.8

write a logic expression to represent a truth table.

10.9

draw a logic circuit to represent a truth table.

10.9

draw a logic circuit to represent a logic expression.

10.10

complete a truth table to represent a logic expression.

10.10

write a logic expression to represent a problem statement.

10.11

draw a logic circuit to represent a problem statement.

10.11

complete a truth table to represent a problem statement.

10.11

352)

Needs more work

Getting there

Confident to move on

analyse problems to create programming solutions



• •

understand how to tackle a large problem identify the inputs, processes and outputs of a problem use pseudocode or program code to write solutions for problems .

CAMBRIDGE !GCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

)

GETTING STARTED Work in pairs to discuss how you tackle a programming problem. What do you do first? How do you check that you have met all the requirements? What features do you add to improve the readability of your program?

PLANNING A PROGR AM Programmers have to tackle programming problems every day. They have to analyse the requirements and work out how to write a program to meet those requirements, in the same way that you will need to. The only difference is that programmers have been doing this process for a long time, they have practised and practised. This is the best way to tackle how to write programs; practice, practice and more practice. Most programs follow a pattern, they will have inputs in the system, they will include processes (actions), and then output results. The challenge is working out which order to put these in. Figure 11.1: A person playing a computer game Consider a 3D computer game, where the player moves an online character around a virtual world, interacting with objects and other characters. This system has inputs, processes and outputs. For example: •

Input: an arrow key from the user (up, down, left, right).



Process: change the characters position depending on the key pressed.



Output: the character in the new position.

From this analysis a program can be written to perform these actions. The larger the problem, the more likely a design will need to be created first . This design will identify all of the requirements of the problem, and begin to identify the inputs, processes and outputs. For some programs there could be thousands (or more) inputs, processes and outputs. They all need to be identified to make sure the design covers all the requirements. The only difference between the process with a large problem, and the problem you will be tackling is the size. You are only going to need to identify a small number of inputs, processes and outputs and you are working on your own. A large program could have dozens of programmers, each working on their own part of the problem. Discussion questions 1

What might happen if you did not identify all of the requirements before starting to tackle the problem?

2

How do you tackle a problem? Do you just start creating a solution, or do you need to identify the requirements and components first? Or does this depend on the problem?

11

Programming scenarios practice

11.1 Programming scenario

In the Paper on Algorithms, Programming and Logic, you will be given a scenario that you need to write an algorithm for to solve the problem. It is important that you think about the problem and plan before you start writing a solution. This is especially important to make sure you don't miss anything that is in the question.

There are then two ways that you could tackle this problem. Which you choose depends on you and which you prefer. The first method is identifying the inputs, processes and outputs. The second method is practically doing the programming task and identifying the steps this way. COMPUTER SCIENCE IN CONTEXT Consider your favourite computer game. At some point a programmer had to identify the inputs, processes and outputs in the game.

ACTIVITY 11.1 Write down some of the inputs, processes and outputs for your favourite computer game. Peer Assessment Compare your game with a partner's. Can you think of any more inputs, processes or outputs for their game?

11.2 Method 1: Identifying the inputs, processes and outputs Identify key features First read the problem twice before starting to work out what you need to do. Example - calculator: A program needs writing to act as a calculator. The program needs to: •

Take one integer value from the user.



Take an operator as input; + for addition, - for subtraction,/ for division, * for multiplication or /\ for power of.



Take a second integer value from the user.



Output the result.

Write a program using pseudocode or program code to solve the problem.

355 )

>

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Once you have read it twice, start to identify the key features; the inputs, processes and outputs. You could do this using a table, e.g. Input

Process

Output

Identify the inputs from the scenario: Input

Process

Output

Process

Output

First integer value. Operator. Second integer operator.

Then identify the outputs: Input First integer value.

Result from the calculation.

Operator. Second integer operator.

Then you need to work out how to get from the input to the output. This could be a description, program statements, or anything that helps you to write down what happens. If you get stuck here, try doing what the program needs. In the case of the calculator, write down the first integer value (e.g. 3), write down the operator (e.g. +), write down the second integer value (1). Then what do you do with this values? Because the operator is + you will do 3 + 1. That is your process. Input

Process

Output

First integer value.

If+ is entered add the values.

Result from the calculation.

Operator. Second integer operator.

If - is entered subtract the values. If* is entered multiply the values. If/ is entered divide the values. if A is entered work out the power of .

ACTIVITY 11.2 Open a program you have already written. Identify the inputs, processes and outputs for this program.

356

>

REFLECTION How did you investigate the inputs, processes and outputs for Activity 11.2? Did you work through each line of code at a time, or did you just focus on the elements you were looking for?

11

Programming scenarios practice

11.3 Writing the code Now you know the inputs, processes and outputs, you need to work out the order. Usually the inputs come first, and they are a good place to start. Even if can't identify the processes yet, always do the inputs - they will help to get your started. The question will likely say pseudocode or program code, this is to allow you the freedom of what to use. It does not mean that your code must be syntactically perfect, but it must use code structures, for example: For x ._ 1 TO 10 is code like, but, starting with 1 loop until 10 is not code-like, this is English statements not code statements.

COMPUTER SCIENCE IN CONTEXT

Pseudocode is supposed to be a language neutral way of designing code. This means that any programmer can take the pseudocode you have written, and write it using their programming language of choice.

The _pseudocode conventions used in this chapter appear exactly as you will l see 1n your exams.

Inputs It is always best to include an output before the input, to tell the user what to enter. This can be done in two statements, e.g. OUTPUT "Enter a number" INPUT number or as one statement, e.g. number ._ INPUT "Enter a number" Whichever way you choose, make sure you are inputting a value into a variable. In the examples above the variable is number. If you use this statement: INPUT "Enter a number" then the number will be input and it won't be stored anywhere, so you can't use it. Example - calculator: Write code for the inputs. Numberl ._ INPUT "Enter a number" Operator ._ INPUT "Enter an operator" Number2 ._ INPUT "Enter a number"

Validation Now you have your inputs, consider if there are limits on what should be entered. Look at each input in turn and write down what is, and isn't allowed.

357 )

)

CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK

Example - calculator: •

First integer value - must be a whole number.



Operator - must be+ - / * or A_



Second integer operator - must be a whole number.

There are different ways that you could validate the inputs, e.g. •

Use an if statement and only allow the rest of the program to run if the inputs it valid.



Use a loop to continue asking for the input until it is valid.

Example - calculator: REPEAT Numberl