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 VI How to use this series VIII Introduction 1 1 8 Data representation 1.1 Binary and hexadecimal Binary manipulation and negative 1.2 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 interface Detecting errors in data transmission Encryption 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 numbers How do computers represent text, images and sound? Measuring data storage Data compression > performance of a CPU Input and output devices Data storage Virtual memory Cloud storage Network hardware 10 16 4 Software 78 4.1 80 Types of software 4.2 Operating system 81 Interrupts 84 4.3 4.4 85 Types of programming language 4.5 87 Translators 4.6 Integrated Development Environment (IDE) 90 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 6 Automated and emerging technologies 6.1 Automated systems 6.2 Robotics 6.3 Robots in context 6.4 Artificial intelligence 21 25 27 33 35 36 38 43 44 49 54 56 57 58 58 60 62 66 69 70 72 7 94 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 355 Method 1: Identifying the inputs, processes and outputs 355 Writing the code 357 Method 2: Practically carrying out the program and identifying the stages 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 2 6 1 2 3 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 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 1 I 1 lo lo I 1 I lo lo lo lo 1 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 1 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 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 character set: it contains all the characters that are in that character set and the binary value that is assigned to each character. 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. pixel: a very small dot of colour that is displayed with many others to create an image. 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 <J) � 10 I I I ro > ""O C '' '' 0 I I 2 0 , I ' l 6 5 - II 3 I I I\. I I '\ J 4 5 ' l I \ \ \ \ I 6 7 Time samples , ....'" I I \ \ \ ' 9 10 \ I I '-II '-.J 1 ..... ,,,I 8 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 4 3.5 5 4 6 9 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 <J) � 10 - I ro > ""O C ,, '-', ' 6 5 - II ,I 0 '' ,' I ', __ ,, ''' III ,, \ I I 2 3 .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: • • 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). 26 ) 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 Device A 1-1 -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. [2] Explain why and how packets of data are reordered after packet switching has been used to transmit data across a network. [2] Describe how data is transmitted using serial half-duplex data transmission. [4] Give two benefits of using the USB interface to connect hardware devices to a computer. [2] 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. [6] 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. [4] 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 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 [1] 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. [1] iii Describe what happens at the decode stage of the cycle. [3] 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. [1] ii Explain why the performance of the new CPU would be better. [2] c The computer has both random access memory (RAM) and read only memory (ROM). Identify if these are examples of primary or secondary storage. [1] ii State what each of these components store. [2] [Total: 11] 2 Give the most appropriate sensor for use in each of the given scenarios. A different sensor must be given for each scenario. [3] Scenario 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. [2] ii Describe how data is stored on optical storage. [6] 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. [1] ii Give two disadvantages of storing the customer data in cloud storage, rather than local storage. [2] [Total: 11] 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. [2] 76 ) COMMAND WORDS 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 .?� ;;,��··r;-�� �.,,......-�,; r L ---· _----___------- �Y-�};'?t�<C:,-!'•)i:!/ :-r� explain why a computer system needs a CPU. R 3.1 describe the role of each component in a CPU. 3.1 explain how data is fetched into the CPU, including the components used. 3.2 explain how data is decoded and executed by the CPU, including the components used. 3.3 explain what an embedded system is and identify examples of where one might be used. 3.1 describe the purpose of an input device and provide examples. 3.6 describe the purpose of an output device and provide examples. 3.6 identify the different types of data that is captured by different sensors. 3.6 choose a suitable sensor for a given scenario. 3.6 give characteristics of primary data and explain the role of RAM and ROM. 3.7 give characteristics of secondary storage. 3.7 describe how data is written to and read from magnetic storage. 3.7 describe how data is written to and read from optical storage. 3.7 describe how data is written to and read from solid state storage. 3.7 explain how virtual memory is created and when it is needed in a computer system. 3.8 describe what cloud storage is and how it is used. 3.9 explain the advantages and disadvantages of storing data in the cloud, rather than storing it locally. 3.9 k!� ;,1 to�!!1��!}J 77 > explore the different types of software that run on computers • understand the role and function of an operating system in a computer • explore the different types of programming language • describe and use the software used to write a computer program • learn about the software used to translate program code. 4 Software GETTING STARTED Work in pairs to make a list of all the different pieces of software that you have used. Can you think of a way to categorise these pieces of software? For example, by what they do or how they are used? As a class create a mind-map of the different programming languages that you have used, or come across. Discuss whether any of these have specific uses, or do they allow for any type of program to be written? DEVELOPMENT OF PROGRAMMING LANGUAGES The very first programmable digital computer was developed during World War 2 in the United States of America; the Electronic Numerical Integrator and Computer (ENIAC). Its purpose was to perform calculations faster than a human. It allowed the storage of a 10-digit number and could perform addition and subtraction. This computer could only perform the task it was designed to perform. From this, assembly language was created that allowed a user to write a program that could then be converted into binary code (see binary interpretations in Chapter 1). These languages required the user to state which memory locations were being accessed (for example, store the data in memory location 3, access the data from memory location 4. This takes a lot of expertise to write a long program). Each program had to be written to the assembly language of the computer it was to run on. If you wanted the same program on two computers from different manufacturers, or different versions, then you would have to write the program again in that computer's language. Fortran was the first significant high-level programming language first released in 1957 by IBM. This was different from previous languages because it was the first language that did not require the user to write in assembly language. It used more user-friendly commands that were then converted into code that could be run. Another benefit of this new language was that it was not machine-dependent, you could write a program on one computer, and run it on an entirely different one. Figure 4.1: The ENIAC Figure 4.2: Close-up of an original computer similar to a Turing machine Discussion questions 1 Can you think of any more problems that can arise from only writing programs in assembly language? 2 How has the development of programming languages impacted the use of computers? 79 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) 4.1 Types of software Computers need software to allow the user to do something useful. You will use software each time you use a computer, whether this is a PC, a laptop, tablet or mobile phone. Software is a series of instructions that tell the computer what to do, created using programming languages.. Hardware System software >-- - ---- 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. bookmark: a link that can be created to allow you to quickly find a web page again. tab: a website function that allows you to open multiple web pages in the same window. window: a viewing area that is created in which a software application or file can be opened. 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 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. Table 5.1: 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, ! ,, ,,. •' <. !! l viruses. It is also important to update your anti-virus ilq software. Perpetrators are constantly developing new < i, I .i /) 1 f)() '<; •: ,i,' viruses. The anti-virus software developers are constantly : � ,i: :il 1 ,} _ '._, .1 \ _ l._,, }ii·; t -'. ji, • , ; finding these and update their database used in the scan. You need to make sure that you are updating your ··,:: )l('l1 1 1Pl()('·'.:-:::,,, I'.;:,: j ]1:- �,- _:.,--- �,_ '. ·,i_·�- ,-./� 11,,\•l:•: I anti-virus to make sure that the database is up to date 1 1 - · ,.-.:,- ; Iii I j 1: 1 i 1, 1 i,:: ! !'.:�I:. � and all the viruses are found. J,_ I; 1 i '.I,. d 'I : ; I,; I( 11 I l . .·.__. ,1i ! 1) I!i: f I I 1 ! () r.): ,·,i \ JI I l ! Ii: '.Ii ! . 1 Iii I l I ( ! 11 I I) Anti-malware software can be installed and used to scan llllllil,11 11 l lllllll' (\, your computer and network for other types of malware, I )I , IIHl(illlll !ii "' ,J(l\11 ": ,I] lli]IIIIIIHl{IJ such as worms, spyware, adware and ransomware. This d I I 10 HI I111) Itl ItHHIItlllI I I 1 ll 1 tl operates in a similar way to the anti-virus software by I I lll!tlllHll(lllllll1HlllHlllll<llll scanning, quarantining and deleting any malware found. r10110101 I1111 I IOIOOJn1Ht!lllO The anti-malware that looks specifically for spyware is Figure 5.22: Anti-virus software should be kept up to date to called anti-spyware. 1 ·;,··,: 1 l () ] ◄ find any and all viruses A firewall can be used to help prevent malware being downloaded onto your computer. The data coming into and out of your computer can be examined against the criteria set for the firewall. If the data looks malicious, the firewall will reject it and stop it from being downloaded onto your computer. It is useful that a firewall examines both the data incoming and outgoing data from your computer, especially in the prevention of spyware. As the firewall is examining the data leaving your computer as well, it may recognise a malicious program that is trying to leave your computer that contains all the keypresses that you have made on your keyboard. If the firewall rejects this data, it will not be able to leave your computer, preventing it being sent to the perpetrator to be analysed. Figure 5.23: Malware can be sent to a computer via email 11,1 \ \' 5 .. • • • • • • . . : • • The internet and its uses •• •. .. •• • ,,.• • • • • • • •• • • • • •••• • • •• • • • • •• •• • •• • • • • internet • • • ,, ., ,, ,, Figure 5.24: A firewall protects a user's computer from security threats on internet You can make sure that you are very cautious when clicking any links and downloading any software online. Malware is often hidden in what looks like an innocent piece of software or link, for example, a game that looks enticing to play. There could be malware hidden inside a trojan horse in the game that may not be detected by a firewall. If you download the game, it will download the trojan horse, allowing other malware to be released onto your computer. You should only ever download software from companies and sources that you know can be trusted, no matter how fun or enticing it may look. You can also store a backup of your data that is not attached to your computer or network on a constant basis. This means that if your data is damaged by malware, or encrypted using ransomware, you still have access to a copy of your data. This can prevent you needing to pay a ransom to gain access to your data again, but it will not stop the perpetrator from leaking your data. Therefore, it is advised not to keep any personal data on your computer that could be accessed and leaked by a perpetrator of ransomware. If you do keep personal data stored on your computer, you should encrypt the data yourself, so if the perpetrator did gain access to the data, it would be meaningless to them and they wouldn't be able to leak it. KEYWORD data backup: a copy of data that is stored separate from the computer. To avoid the risk of personal data, such as passwords, being sent to a perpetrator, you could use an onscreen virtual keyboard rather than a physical one to enter passwords. This means that you don't need to make any key presses, so these are not recorded for your password, so any data that was sent to a perpetrator would not contain your passwords. Some companies also add drop down boxes for you to select characters from to input your password. They may also ask you for random characters from your password, and not your whole password. This is to prevent you needing to enter your full password and to stop your full password being sent to the perpetrator. 115 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Figure 5.25: An onscreen virtual keyboard In summary: What happens? What is the aim? What security solutions can be used? Malicious software is downloaded onto your computer or network. Malicious software is used to corrupt your data, gain access to your data or damage your hardware. Anti-malware software, including anti-virus and anti-spyware, a firewall, exercising caution when downloading software and creating a backup of data. Pharming KEYWORDS Pharming is used by perpetrators to try and get your personal data, such as your username and password for your online accounts. They can then log into the account, pretending to be you, and use your account to buy products online with your money. It can also be used to get more personal details from you, such as your address, that can be used by the perpetrator for identity theft and fraud. pharming: a type of cyber threat that involves downloading malicious software onto a user's hard drive, that redirects a request aimed at a genuine website to a fake website instead. The fake website will encourage the user to input their personal data, allowing it to be stolen. The perpetrator will try and entice you into clicking a link or icon to start a download. This could be done in various ways including sending an email, creating a pop up advert or just having a link available on a web page. When you click the link, a download will begin and as part of that download, malicious software will be downloaded onto your hard drive. This malicious software is designed to redirect certain website requests you have to go to a fake website instead (see Figure 5.26). The perpetrator will set up a fake website to look very similar to a genuine website, such as Pay Pal or your social media page. When you next type in the URL to request the web page, the malicious code that has been downloaded on your hard drive will redirect the request to the fake website instead. The perpetrator will hope that you think you have opened the genuine website and when you type in your login details, these will be sent to the perpetrator instead. If you notice that the website is fake after typing in your login detail, it is very important that you change your password for that website immediately. This can help stop the perpetrator being able to log into your account. As pharming uses malicious code that is installed on your hard drive, you can use anti­ malware software to remove it. The anti-malware software will scan the files stored on 116 ) hard drive: a storage device that stores data permanently, until it is deleted by the user. 5 The internet and its uses your computer and will help to find the file that is redirecting you to the fake website. The anti-malware software will quarantine this file and let you delete it. When you type in the URL now the redirection should stop and you should be taken to the genuine website. One thing that you can do to help prevent pharming is to only download software or click links that you know are from a trusted source. You should also thoroughly check any website before you enter your personal details. You can look to see: • If the URL at the top of the screen is the correct one. • If the site is secured using HTTPS. • If the website looks like it normally does. Are all the usual colours, images and text there in the same places? If you are in any doubt at all whether the website is genuine, close the website without entering any of your details and scan your computer immediately with anti­ malware software. ta --� -- -- --- -. ta Perpetrator Any personal data input is obtained Malicious software downloaded /sake website Request gets redirected to fake website/ User types in URL for genuine website Genuine website Figure 5.26: Pharming is a cyber threat where fake websites are used to steal data In summary: What happens? Malicious software is downloaded onto your hard drive that will redirect you to a fake web page when you input the genuine URL. What is the aim? To get your personal data to commit criminal activity such as stealing your money, identity theft or fraud. What security solutions can be used? Anti-malware software, visually checking the web page and only downloading data from trusted sources. Question 11 What can you do to prevent a perpetrator getting your personal data through pharming? Phishing hishing is also used by perpetrators to try and get your personal data, such as your username and password for your online accounts. They can then log into the account, KEYWORD phishing: a type of cyber threat that involves sending a user a fake email that is designed to look genuine. It will encourage the user to provide their personal data either by clicking a link to a fake website , or by responding to the email. 117 ) > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK pretending to be you and use your account to buy products online with your money. It can also be used to get more personal details from you, such as your address, that can be used by the perpetrator for identity theft and fraud. The perpetrator will again try and entice you into clicking a link. In phishing, this is done by sending you an email. The perpetrator will create an email that looks like it is from a genuine company, such as your bank. The email will try and get you to click a link that will take you to a website. The email will try and get you to click the link by telling you things like: • It looks like there has been unusual activity on your account, please click the link and log in to check. • You have won a prize, please click the link and enter your details to claim the prize. • Confirmation is needed that you have made this purchase, please click the link and log into your account to confirm whether or not you have made this purchase. • You are being paid a refund on your taxes, please click the link and enter your credit card details so that you can claim the refund. The link will take you to website that will not be the genuine website, it will be a fake website that has been made to look like the genuine one. If you then input your personal details these will be sent to the perpetrator and they will be able to access your account or try and build a profile to steal your identity. You can help prevent yourself getting fooled by any phishing scams by checking: • The spelling and tone of the text in the email. Is everything spelt correctly? Is the email written in a professional tone? Most genuine companies will spend a lot of time making sure their emails are professionally written. • Whether the email has been personalised or if it is addressed in a generic way, e.g. Dear customer. Many phishing emails are sent out in bulk and this often means they are not individually addressed. • The URL that is attached to the link. If you hover your mouse pointer over the link, you should be able to see the URL that the link is connected to. Check if this is the correct URL for this company. • If the URL at the top of the screen is the correct one. • If the site is secured using HTTPS. • If the website looks like it normally does. Are all the usual colours, images and text there in the same places? Most companies will not ask you to provide your personal details over the internet in this way. If you are in any doubt at all whether the website is genuine, close the website without entering any of your details. If you have entered any of your details and realise after that you think it is a phishing scam, make sure that you change the password to your account and any other accounts that use that password immediately. 11A \ PASSWORD ****** Figure 5.27: In a phishing scam perpetrators will try to get your password 5 The internet and its uses Question 12 What are three things that you can look for to identify if an email is a phishing scam? Social engineering Social engineering relies on manipulating and deceiving people into providing confidential or personal data that can be used in criminal activity such as identity theft and fraud, and hacking into computers systems or networks. Social engineering can take many different forms. Phishing is also one form of social engineering, in that it manipulates you into providing your personal data. Have you ever seen one of those quizzes on social media that ask you to provide lots of fun details about you, like your favourite colour, the name of your pet and your favourite food? These quizzes are often created by perpetrators trying to find out key information about you. Many people base their passwords around this type of information, so a perpetrator can gather lot of information like this about you every time you fill in one of these quizzes on your social media. They can then use this data along with a brute-force password program to try and get into your online accounts. Advice for the future, do not fill out these quizzes! This is another form of social engineering, it manipulates and deceives you into thinking you are filling out a fun quiz to learn more about your friends, but you are actually providing key information that a perpetrator can use against you. One way that you can limit a perpetrator's access to your data on social media is to have your privacy settings set to the highest level of privacy. This will normally mean that only people that you are connected to will be allowed to see your data. KEYWORD social engineering: a cyber threat that involves manipulating or deceiving people into providing confidential or personal data. Social engineering can be used to target companies for their data too. A perpetrator could make contact with the company and try and manipulate and deceive employees into providing key information that can be used to hack the company systems. Here are two examples of how this could be done: Example 1 Large companies often have quite a large IT department that are often not too well known by all the employees. It is a common occurrence that an employee may have an IT issue with their computer in a morning. They will normally report this issue to the IT department in their company and will be told someone will contact them from the department, shortly. Therefore, a perpetrator can try and use this situation. They get hold of a list of all the telephone numbers of the employees in the company and begin to call them. They will say that they are from the IT department in the company and say that they are aware of the IT issue that they have reported. Most employees will probably just say they haven't reported an issue, but if they happen to call an employee that has, that employee will think it is the IT department calling to sort their problem. The perpetrator will then say that they just need the employees login details to access their system to see what is wrong with it. The employee may Figure 5.28: Employees of large companies can be contacted by be tricked into providing their login details and perpetrators claiming to be from the IT department 119 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK now the perpetrator can get into the computer systems of the business and steal any data that they think could be useful to them, or look to introduce malware. ACTIVITY 5.7 Discuss with a partner what you think the employee could do to stop themselves being the target of a social engineering scam like this one. Example 2 Employees often go for dinner together or out for a relaxing coffee after work on a Friday. A perpetrator finds out where employees do this for the company that they want to target. The perpetrator places themselves close to where the employees will normally sit. They will start a conversation with the employees and become friendly with them. They will start to ask lots of questions about the company an employee works for. The employee may mistake this as the person taking an interest in their life. Over a few what seem like accidental meetings with the employee the perpetrator has asked lots of questions that has allowed them to build up a profile about the company, such as information about where they store their data and what kind of security systems they have. The perpetrator can use this information to hack into the company systems and network. KEYWORD access level: the Figure 5.29: Employees can be contacted by perpetrators pretending to be colleagues ACTIVITY 5.8 Discuss with a partner what you think the employee could do to stop themselves being the target of a social engineering scam like this one. One way that companies can help protect against the threat of social engineering is to use access level for their data. This is where employees are given different levels of access to the data in the company. What this normally means is that an employee will only have access to the data that they directly use on a daily basis. It also often means that the only people that have access to more confidential data are the more senior employees in the company. Levels of access are linked to an employee username. 1?n \ amount of direct access a user is given to data and resources. This could be set to be only certain sections of a whole collection of data and resources. REFLECTION How did you come to a decision about what the employees could have done in Activities 5.7 and 5.8? 5 The username will have data connected to it that will show the computer system which data the employee is allowed access to. This means that if an employee is targeted by a social engineering scam and fooled by it, the data that the perpetrator can gain access to may be limited. A company can also train employees to recognise social engineering to make them more aware of when it might be happening to them. In summary: What happens? A perpetrator will try and manipulate and deceive you into providing them with personal or confidential data. What is the aim? To get data to commit criminal activity, such as stealing your money, hacking into a computer network and identity theft or fraud. What security solutions can be used? Access level and awareness of how social engineering is conducted. The internet and its uses KEYWORD username: a text­ based identification that is given to a user that identifies the level of access that they have to stored data and resources. i SUMMARY The internet is the infrastructure that is used to access the world wide web. The world wide web is the collection of all the web pages that are available. A URL is a text based address for a web page that contains the protocol, the domain name and the web page name or file name. The HTTP protocol is used to transmit data between a computer and a web server. This data is not encrypted when sent using this protocol. The HTTPS protocol is the encrypted version of the HTTP protocol. It uses the SSL protocol to encrypt the data. The main purpose of a web browser is to render HTML to allow a user to view web pages. It also has other functions such as recording a user's history and storing bookmarks, favourites and cookies. Cookies are used to save your personal data and track your online preferences. They can be session or persistent based. Web pages are located, retrieved and displayed using a web browser, a DNS and a web server. A digital currency is a currency that only exists electronically. An example can be cryptocurrency and this kind of digital currency is tracked using blockchaining. This is a type of digital ledger that records all payments made using the currency. There are several cyber security threats that exist such as brute-force attacks, data interception, DDoS, hacking, malware, pharming, phishing and social engineering. The aim of most of the cyber security threats is to steal your personal data to commit identity theft and fraud, or as an act of revenge or activism. There are a range of cyber security solutions that can be used to help keep your data safe from security threats such as anti-malware software, firewalls, proxy servers, encryption, authentication (including biometric passwords and two-step verification), privacy settings, automated software updates, access levels and visual checks such as checking the URL that is connected to a link or download. 121 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) EXAM-STYLE QUESTIONS State the name given to the infrastructure that allows a user to access the world wide web. 2 A URL is the name given to the text based address for a web page. The web page name is one part that is used to create the URL. a Identify the name for one other part of a URL. b State the name of the hardware that finds the corresponding IP address for a URL. 1 3 The given paragraph describes how a web page is located and COMMAND WORDS [1] identify: name/ [1] 1?? '> select/ recognise [1] [Total: 2] retrieved to be displayed on a user's device. Complete the missing words in the paragraph. [5] The user types the URL into the address bar in the ......................... This is sent to the ........................................ where the corresponding IP address is found. The IP address is sent to the web browser. The web browser uses the IP address to send a request to the ............................... where the web pages are stored using the ........................................... protocol. The web pages are sent to the web browser. The web browser renders the .............................................. to display the web page. 4 One function of a web browser is to store cookies. a Identify two other functions of a web browser. [2] b State the name of the type of cookie that is stored in a computer until it is deleted by the user or by the web browser when it expires. [1] Total: 3] [ 5 Give one benefit of using blockchain to track a digital currency. [1] 6 A website company is worried about a distributed denial of service (DDoS) attack being carried out on their web server. a State the name of a security solution that can be used to help prevent a DDoS attack taking place. [1] b In a DDoS attack, a perpetrator creates a botnet. Describe how the botnet is created by the perpetrator. [3] 7 Draw a diagram to show how data interception is carried out. state: express in clear terms. [Total: 4] [3] COMMAND WORDS give: produce an answer from a given source or recall/ memory. describe: state the points of a topic/ give characteristics and main features. 5 The internet and its uses CONTINUED 8 Draw a line to connect the security solution to the correct description. [3] Security solution Description Firewall This is a protocol that encrypts data that is sent across the internet. Anti-malware This is software that can be used to scan a computer for malicious files. Access levels This can be hardware or software based and it examines traffic incoming and outgoing from a computer system or network. COMMAND WORD explain: set out purposes or reasons I make the relationships between things evident / provide why and/or how and support with relevant evidence. This is connected to a user's username and provides information about what data the user is allowed to access on a system. SSL 9 A student finds that a perpetrator has managed to hack into their social media account. Explain two ways the perpetrator could have managed to do this. [4] I 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'. - - � - - - - - - -- v· I• t ca�··· l - ··-- , See --4- - - - - - topic explain the difference between the internet and the world wide web. 5.1 explain what is meant by a URL and what the different parts of it are. 5.2 describe how data is sent using both the HTTP and HTTPS protocols. 5.2 describe how web pages are located, retrieved and displayed using a web browser, DNS and a web server. 5.2 explain the main purpose of a web browser and I can identify other functions that they often have. 5.2 explain how cookies are used and what the difference is between a session cookie and a persistent cookie. 5.3 -- Needs more work Getting there Confident to move on 123 ) > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED I can... See topic explain what is meant by a digital currency. 5.4 explain how blockchaining is used to track certain digital currencies. 5.4 describe how a brute-force attack is carried out, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 describe how data can be intercepted, what the aim of it is and how to help prevent it happening. 5.5 describe how a DDoS is carried out, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 describe what is meant by hacking, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 describe what is meant by a virus, what the aim of it is and what security solutions can be used to help prevent it being downloaded. 5.5 describe what is meant by a worm, what the aim of it is and what security solutions can be used to help prevent it being downloaded. 5.5 describe what is meant by a trojan horse, what the aim of it is and what security solutions can be used to help prevent it being downloaded. 5.5 describe what is meant by spy ware, what the aim of it is and what security solutions can be used to help prevent it being downloaded. 5.5 describe what is meant by adware, what the aim of it is and what security solutions can be used to help prevent it being effective. 5.5 describe what is meant by pharming, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 describe what is meant by phishing, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 describe what is meant by social engineering, what the aim of it is and what security solutions can be used to help prevent it happening. 5.5 124 ) Needs more work Getting there Confident to move on learn about the use of automated systems in context • explore how automated systems use sensors, microprocessors and actuators • explore the advantages and disadvantages of automated systems in context • learn about the use of robotics • learn about the characteristics of a robot • explore the use of robots in context • learn about what is meant by artificial intelligence • explore the characteristics of artificial intelligence systems • describe the use of machine learning in artificial intelligence explore the features of, and use of, expert systems. CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) GETTING STARTED Design a robot. Consider a scenario where a robot would be useful in your daily life. Identify the tasks you would like the robot to perform. Describe how the robot will work, for example, the inputs that would be used (and the hardware, e.g. sensors that might do this}, how the robot will decide what to do, and what its output will be. There are many ideas on what it is to be intelligent, with one key area being the ability to learn. How did you develop intelligence? From when you were very young you started to learn. Each time you experienced something new, you learnt from it, for example, if you cried then someone might pick you up. So, next time you wanted to be picked up, you cried. The desire to create intelligent computers has been around since the very first machines. Even looking back to ancient history there are stories about bringing objects to life. Achieving artificial intelligence has made the most steps over the last 20 to 30 years. There are now systems that simulate some human activities, and systems that can learn both with and without a person telling them what to learn. These programs all still run on rules, that are programmed into them to follow, so are they intelligent? Humans learn by developing rules and storing these in memory, so are we intelligent? Figure 6.1: A brain Discussion questions 1 What do you think is meant by intelligence? 2 How would you test whether a computer is intelligent, or not? What would you test it against? 3 Do you think that computers that learn and act independently should be created? 6.1 Automated systems An automated system performs actions without interaction with humans. They are used in small systems such as the heating or air-conditioning in buildings, all the way up to flying aeroplanes and building items such as cars. Features of automated systems An automated system usually has the following features: • Sensors - to measure the environment. • Microprocessor - to process the data from the sensors and determine if an action needs to be taken. • Actuators - to create a movement. ' KEY WORD automated: a device that is operated without human interaction. 6 Automated and emerging technologies There are a lot of different sensors that you need to know about - you can find more information on these where they were covered in Chapter 3, Section 6. You will need to identify which sensor is most appropriate in a given context. For example: a system needs to monitor the pollution in a river. Consider what could be measured. The temperature of the water using a temperature sensor. The amount of light reaching the bottom using a light sensor. The pH of the water using a pH sensor. Sensors just do one job, they read the environment and send the data onwards. They do not process the data. That is done by the microprocessor. There is a problem though, the sensor reads analogue data (real-world data such as 23.5 °C), but the microprocessor only understands binary (01101010). The sensor first sends the data to an analogue-to-digital converter, to turn the reading into binary (digital). Then, the digital data is sent to the microprocessor. Before the system is started, data will be stored in the microprocessor. This could be a single value, for example, the value from an infra-red sensor to state that there is movement. There could be several values, for example, the minimum temperature and maximum temperature for a greenhouse. Or there could be a whole range of data. The microprocessor takes the data from the sensor and compares it to its value, or values. The result of the comparison determines the next step. For example, in a burglar alarm, if the sensor is outside of the stored range then an alarm will need turning on. In a house, if the temperature is below the minimum the heating turns on, and if it's above the maximum it turns the heating off. If the microprocessor decides an action is needed (e.g. turn the heating on), it sends a signal to the actuator, which then performs the action. The whole process is then repeated until the system is turned off. KEYWORDS sensor: a type of input device that is used to capture data from its immediate environment. microprocessor: an integrated circuit that is able to perform many of the functions of a CPU. analogue: continuous data that can be any value within a range. digital: discrete data that is stored as 1 s and Os. actuator: a mechanical part that causes another device or part to move. Example A set of doors in a building automatically open when a person is detected. 1 2 3 4 What type of sensor could be used? An infra-red to detect movement, or a pressure sensor to detect if someone is standing near it. What happens to the analogue data? The analogue data is converted into digital. Where does the data go? The data is sent to the microprocessor. What happens in the microprocessor? It compares the received data with the stored data. If it is out of range, it sends a signal to an actuator to open the doors. If it is not out of range, it does nothing. This process continues until the system is turned off. 127 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) This can also be shown in a diagram in Figure 6.2: START Sensor reads environment Data is converted to digital Data is sent to microprocessor Data compared to stored value/values YES Data is in range? or matches stored value? NO Send signal to actuator to perform action Figure 6.2: The process in which doors open automatically when a person is detected COMPUTER SCIENCE IN CONTEXT Control systems are at work all around you, probably without you noticing. Think about a car. It could have light sensors, so when it is getting dark the headlights will be automatically turned on. It could have rain sensors, so when it starts raining the windscreen wipers start moving. These each have a sensor that is constantly reading the values of the environment, e.g. the light level. The data will be sent to a microprocessor that compares the value with its stored value, and if necessary sends the signal to turn on the lights, or the wipers. This means the car drivers do not have to worry about turning these on when needed. It also improves safety, particularly with the headlights so that the car is always visible. Figure 6.3: Car headlights could operate via sensors 6 Automated and emerging technologies SKILLS FOCUS 6.1 CONTROL AND MONITORING SYSTEMS When considering a control or monitoring system you need to determine the inputs, processes and outputs as you would in a computer program: • The inputs from the sensors. • The processes. • The outputs from the system. n ut �---l _p_ _ _ _ _:---.i• roc u ut o_ _t_p_ __ P_ _ _ _e_ss _ _ _ _ _, Figure 6.4: A control ormonitorings ystem ca n be thought of as a 'story' ofi n put, _ �, _ _ __ • � __ I _ � ___ I process and output Using these you then need to create the 'story' (see Figure 6.4) about how the sensors gather the appropriate data, what this is compared to, and how this influences the outputs. For example: An automatic door will open when a person is detected. The door stays open for 5 seconds if no more people are detected. Take each point in turn: • Inputs: A pressure sensor can be used to detect if a person is standing on a specific point. A motion or infra-red sensor can be used to detect if a person is in a specific place. • Processes: Analogue data from the sensor will be converted to digital. The microprocessor will store the value where a person is detected on the pressure sensor, and/or the result identifying that a person (movement) has been detected. • Output: A signal will go to an actuator to open the door. This will stay for 5 seconds, and is reset each time another person is detected. Questions 1 2 3 Describe how the sensor will monitor its environment. Describe how the processor will work out if the door needs to be opened. When will the door close? 129 > ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Questions 1 2 3 What type of data does a microprocessor process? What tasks does a sensor perform? An automated system makes cakes by positioning a cake tin below a funnel where the cake mix comes through to fill the tin. a Identify a suitable sensor for this system. b The sensor has read the data. Identify the function that happens next. Where is the data sent? c d Describe the actions the microprocessor performs. e How many times does the system run? Automation in context KEYWORD The automation of systems has both benefits and drawbacks, and these are different depending on the system. You need to be able to think about the context and the benefits and drawbacks in that scenario. automation: the use of automated equipment in a process, e.g. a factory. When evaluating the use of automation you can consider: • • • • • • initial cost running cost safety replacing people's jobs continuous work all day every day prec1s10n. Example 1, industry Car manufacturing. • Initial cost: this will be high because the robots need purchasing. The software will also need developing and could be expensive. • Running cost: this could be high because the systems need maintenance, but it could perform actions more efficiently than humans which could save money. However, there may be fewer employees, therefore saving money Jong-term. • Safety: it should be safer because they can monitor their environment and stop if there is any danger, whereas people can be distracted, and more accidents could happen. Figure 6.5: A car manufacturing factory • Replacing people's jobs: jobs that the system now performs will be lost, but more jobs will be made to maintain the system. • Continuous work all day every day: this would mean that more cars can be built. • Precision: human errors will not be made so there are less faulty cars. 6 Automated and emerging technologies Example 2, science Nuclear power plant. • Initial cost: will be high because of the purchase of the devices and development of the system. • Running cost: may be lower because fewer people are needed, however maintenance might be expensive. • Safety: less risk of human error therefore increasing the safety, also people will not need to work in dangerous places. • Replacing people's jobs: some jobs will be replaced for the functions the system does, but new jobs will be made to maintain the system. • Continuous work all day every day: it is important that the power plant is monitored all day every day without getting tired and therefore less errors. • Precision: this is important in a high-risk scenario and an automated system will measure and perform actions with more precision, therefore fewer errors. Example 3, agriculture Growing conditions within a greenhouse. • Initial cost: this may be high for the installation and programmmg. • Running cost: there will be a cost for electricity and maintenance but it is a small system so may not be high. • Safety: this may not be relevant because it is not a dangerous process. • Replacing people's jobs: it might replace jobs of people who monitored the conditions, but this is unlikely to be a large number. • Continuous work all day every day: this will allow the system to adapt as soon as there is a problem, instead of waiting for a person to check and make changes. • Precision: this may not be as important, but it will allow readings to be more accurate and instant changes to be made. Figure 6.6: A greenhouse Questions 4 5 An auto-pilot system will fly an aeroplane without input from a person. Identify two benefits and two drawbacks of using the auto-pilot. A weather station records and stores data about the current weather conditions. Describe the advantages and disadvantages of using the automated system. 131 > ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK 6.2 Robotics KEY WORDS What are robots? robot: a machine that replicates human actions or movement. A robot is a mechanical device that performs an action, usually an action that a human would perform. Robotics is an area that covers the design, construction and operation of robots. A robot can be controlled by a person, or they might be automated, or a mixture of the two. One example is a drone. This is a robot, it can be controlled by a person, and it can be programmed to be perform movements depending on its surroundings. Another example is the machines that build components in industry, for example, manufacturing devices. The robots that put the components together can be automated so that they can build the components without human interaction. Robots have a range of features: • A mechanical structure or framework. This is the body of the robot. • Electrical components such as: • Sensors to record its environment, for example, the position of the component it is building. • Microprocessors, to take the reading from the sensor and decide the action to perform. • actuators, to make the robot move. Robots are also programmable; a program can be written for the robot to follow. 6.3 Robots in context Robots in medicine Developments include the use of robot nurses that can move around a hospital to visit and interact with patients. This can save the doctors and nurses time so that they can spend more time doing other tasks. Robots are also used to perform procedures such as operations. For example, if a surgeon is not present in the hospital, even on the other side of the world, they can control the robot performing the procedure. This means that a patient will not have to wait for their procedure, and specialists are not required in every hospital because they can share resources. The use of robots in medicine also has drawbacks. If there are any errors in the programming, or someone gains access to the programs and changes them, then the result could cause harm. If a surgeon is controlling a robot from a different location and the network connection is lost, then the procedure will stop. This means there needs to be backup systems ready to work if there are any problems. robotics: an area of computer science that looks at the creation and use of robots. programmable: a computer that will run the commands stored in it. 6 Automated and emerging technologies Figure 6.7: Robots preparing for surgery Robots in agriculture Developments include automated tractors and other machines, they can make use of satellites and satellite navigation to guide their movements and then perform the required actions. This means that a farmer can be performing other actions, whilst the machines perform the repetitive tasks that would take up their time otherwise. Robots can also be used to plant seeds, remove weeds, check and adjust the environment where the plants are growing. All of these can be carried out 24 hours a day, 7 days a week, whereas a person may only be working 8 hours a day. Robots in agriculture are often used for the repetitive tasks that people would otherwise spend a lot of time performing. The upfront cost might be high, and there will be maintenance required. However, it might also replace a worker who would otherwise be performing these actions. Figure 6.8: A lawnmower working without a driver 133 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Transport A self-driving car is a robot. It reads its environment and moves accordingly. This is still being developed, but eventually people may not need to drive cars, this could improve safety because the robot can react faster than a person. It is an expensive up-front cost, and there is the threat of what happens if someone accesses the program of a car and changes it. Robots are commonly used in factories to transport items. For example, in a factory, robots can move boxes of product to the lorries. These can be completely automated, keeping people away from the movement of products that could be dangerous. They do replace people's jobs, but also provide new jobs to run and maintain the system. Figure 6. 9: A self-driving car Industry Industry is the manufacture of goods from raw materials. This could be from the building of a pencil, to the building of an aeroplane and everything in-between. Some factories are completely automated with robots. A car production line can involve many different robots, each performing a specific role. The car being built moves from one robot to the next without the need for human interaction. This means that the factory can run all day, every day. The robots do not need to rest and can be more precise because they are not prone to human error. However, their roles were previously carried out by people who may now be without a job. Instead a smaller number of people are required to monitor and maintain the robots, with a different skill set than those who have been replaced. The initial cost is also very large as the equipment needs to be purchased, and the program produced. Robots don't always manage all parts of a process. Some robots can: • Manage the packing of items, for example, putting packets of biscuits into boxes of 24 packets. • Test products, for example, checking the temperature of products when they come out of an oven. • Perform tasks that are minute in size and require exact precision, for example, the building of circuits. Entertainment There are many robots that can be bought as toys, such as robot dogs for people to interact with. There are also those that are educational, for example, where a child can build a robot and then program it to perform specific functions. These allow people to engage with technology, and in some cases learn about how robots work and be introduced to programming. 11LI. \ 6 Automated and emerging technologies COMPUTER SCIENCE IN CONTEXT Drones are another example of where robots are used in entertainment. People can use their drones to record videos of themselves performing tasks. These allow people to get a birds-eye view of an area, but a loss of contact between the drone and the remote could cause the drone to crash and potentially cause injury to people nearby. Figure 6.10: A drone Domestic Domestic robots are those that perform tasks around a home. The most common one is the robot vacuum cleaner. It will make its way around a room, turning when it detects obstacles and changing direction. This can save people time as they will not need to perform the task themselves, however they still need monitoring and cannot go up and down steps. A robot lawnmower works in the same way, monitoring the area it is mowing to make sure it does not miss any spaces. COMPUTER SCIENCE IN CONTEXT A security robot can be used to protect a house. It could record what is happening as videos, and detect motion or sound. These can be set to patrol an area and alert someone if an abnormality (something unusual) is detected. ACTIVITY 6.1 Find more examples of robots that are used in each of the sections; medicine, agriculture, transport, industry, entertainment and domestic. List the benefits and drawbacks of each of the robots. Share your findings with the class and see how many different robots you have all found. 135 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) REFLECTION After completing Activity 6.1, it can be helpful to think about how you approached it and ways you could improve your research skills for future activities. 1 Discuss the sources you used to find examples of robots. How did you make sure these sources were reliable, up-to-date and accurate? What would you do differently if you had to find further examples? 2 Discuss whether finding your own examples might help you answer exam questions. Is it helpful to find your own contexts instead of relying on those given in class? Questions 6 7 8 9 Define the term robot. Identify two ways robots can be used in industry. Give one benefit and one drawback of the use of domestic robots. Discuss the use of driverless cars. 6.4 Artificial intelligence Can computers think? This is a question that has been asked and sought after for many years. Alan Turing developed a test in 1950, called the Turing Test, to assess whether a computer can display intelligence. The test involves a person holding a conversation with a computer program, and another person. If they cannot work out which is the computer and which is the person they are talking to, then it is has passed the Turing Test. Some people do not think that this would demonstrate intelligence, the computer is still following a set of rules that are pre-written. What is artificial intelligence? KEYWORD Artificial intelligence (Al) is the development of programs to simulate human behaviour. There is a broad range of areas within AI: artificial intelligence • Image recognition; to identify objects or people in an image. • Speech recognition; to identify words spoken and store them. • Natural language; to receive a command or instruction that is not in a set format and perform the required response. • Computer games; to move elements or characters independently based upon the environment. • Diagnosis systems; for example, medical diagnosis. You have probably used natural language systems, for example, on a smartphone or a web browser. You can enter your request in dozens of different ways. Let's say you want to find out what time the sun sets today. You could enter "sunset today time", or "what 136 ) (Al): a part of computer science that looks at creating machines that can think and perform tasks a person would usually perform. 6 Automated and emerging technologies time does the sun set today?" or "today when does the sun set?" or many other ways. The software needs to understand what you have asked to decide how it will answer. Some simple questions could be hard-coded. That means every possible way of asking a question is written in the program, so it just has to select the correct one. The problem is, how many ways are there? Is it possible to hard-code every possible question or statement that anyone in the world could ever give? This would be impossible. So instead, the artificial intelligence program has to be able to adapt to whatever is entered. This could be done by comparing it with similar phrases, or picking out key words and grammar, or it could use neural networks which attempt to simulate the human brain to process the words entered. ACTIVITY 6.2 Identify any programs you have used that might make use of artificial intelligence. This could be computer games where you play against the computer, or natural language interfaces. Discuss how you think these may have been programmed and how the problems can be simplified into smaller parts to make the task easier to tackle. Components of Al Artificial intelligence programs can be simplified to the four key features: 1 2 3 4 Collection of data: A program will need data input, this might come from a user (e.g. speech recognition) or from its sensors (e.g. a robot that uses infra-red sensors to work out its position and where it can and can't move). A set of programmed rules: These are stored for the program to use to make decisions. For example, a calculation to determine which decision to make. A rule that if an object is in front of the sensor, turn to the right. The ability to reason: Reasoning is an area of logic, where you have rules, and from these you can develop facts. For example, all dogs eat meat. Fred is a dog. Therefore, Fred must eat meat. The ability to learn and adapt: Not all AI systems will do this, this is a specialist area known as machine learning. Systems can be programmed to learn, and change their own rules and logic. This often involves training. If you want a program to differentiate between an image of a dog and a horse, you can train the system by showing it images of dogs and horses and telling it what the images are showing. The program will then learn the characteristics of a horse and a dog, so when it is tested with a new image it will hopefully identify the animal. Machine learning Some AI systems do not learn, for example, in a computer game the characters can move and interact with your character and adapt to what you do, but they are not learning what you do, they are following their pre-programmed rules. '1achine learning can be supervised, or unsupervised. Supervised means that user is telling the program what its data means, for example, in the image recognition example the user says this image shows a horse. KEYWORD machine learning: a computer program that can adapt its stored rules or processes. 137 ) > 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 <- X + l. Figure 7.2: A structure diagram for a calculator The subprograms can then be split further. The calculator needs two numbers and a symbol to be entered (e.g. 2 + 3). Add these boxes below input (Figure 7.4). The process is dependent on the symbol entered. In this calculator, there is +, - , * and/. Each of these could be given a separate box (Figure 7.5). Figure 7 .3: Input, process and output are added to the calculator structure diagram 146 ) Figure 7.4: Expanding the input subprograms 7 Algorithm design and problem solving Figure 7.5: Expanding the process subprograms Or the variable names from the input can be used (Figure 7.6): Input number1 Input symbol Input number2 Figure 7.6: An alternative way of representing the algorithm shown in Figure 7.4 KEYWORD Both of these are valid. There are lots of ways you can decompose a problem, and everyone could do it slightly differently but the solution is still valid. decompose: the Finally, the output needs identifying (Figure 7.7): action of performing decomposition; splitting a system into smaller sub-systems, which can in turn be split into smaller sub­ systems. Figure 7.7: A finished structure diagram for the calculator This program was fairly small, so it has been split into very precise instructions that can then be programmed. The next example is a larger problem. A computerised version of chess is being developed. Two players can enter their names and then a new board will be displayed. The players take it in turns to select pieces to move and the positions to move them to. The program will check that the moves are valid and then move the pieces. It will remove any pieces that have been taken in each move, and check if anyone has reached checkmate. 147 > ) 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. Algorithm design and problem solving Examples number = number + 1 message= "hello" & "world" Figure 7 .18: Process Decision A question with two outcomes, yes or no (or true or false). The question is a comparison from: = equal to > greater than < less than >= greater than is 1 > 2? YES NO <= less than. You can have more than one condition by including AND or OR. See Chapter 8, Section 6 for the use of these operators. One arrow goes into the box. Two arrows come out, one labelled yes (or true) and the other no (or false). is X = y? NO YES Figure 7 .19: Decision Table 7 .1: Flowchart symbol examples It is important that all arrows are complete, i.e. all boxes lead somewhere else so that you cannot get stuck in the flowchart with nowhere to go. 151 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Example 1 Figure 7 .20 shows a flowchart for a calculator. Start input num1 input symbol input num2 is symbol +? YES >-----answer= num1 + num2 >------ ---� is symbol -? YES >-----.ianswer = num1 -num2 f-----------------1 YES >----.., answer = num1 / num2 >-------------< NO *? YES >-----.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 = numl input = num2 if numl is greater than num2 then output numl if 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 <= LENGTH(DataArray) - 1 DO 162 ) 7 Algorithm design and problem solving //reset changes each time a new pass starts Changes r FALSE //loop through each element in the array //check if the data is in the correct order FOR Index r Oto LENGTH(DataArray) - 1 IF DataArray[Index] > 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 <- 0. • in a program that add together a set of data to produce the total. Add the value to the current contents of the total, e.g. Total <- Total + Value. Example 1 Totalling the 10 values input by the user: Total <- 0 //Initialise the total variable to 0 FOR X <- 0 TO 9 Total <- Total + INPUT("Enter a value") //Add the input to the total NEXT X OUTPUT Total Example 2 Totalling the values in an array named dataArray: TotalValue <- 0 //Initialise the total variable to 0 FOR Count <- 0 TO LENGTH(DataArray) - 1 TotalValue <- TotalValue + DataArray[Count] //Add the input to the total NEXT Count OUTPUT Total PROGRAMMING TASK 7.3 A program is needed to ask the user to input the price of products they have bought. Calculate and output the total cost they spent. Getting started 1 What are the steps required to find the total? For example, initialising the total to O will be the first step. 167 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED 2 You will need to work out how to continue asking for the price of products until they do not have any more. Have a look at some of the previous algorithms in this chapter that perform similar actions to this. What did they use? How did they limit the number that could be entered? Practice 1 Create a structure diagram for the problem. 2 Write an algorithm to ask users to repeatedly input the price of products they have bought until there are no more to enter. 3 Amend the algorithm to total the cost of all the products and output this at the end of the algorithm. Challenge 1 Amend the algorithm to also count how many items they entered. You can look ahead to the next section or work out how to count them yourself. 2 Now you have the total and the quantity, amend your program to work out the average cost. Counting KEYWORD Counting is working out how many of something there are. For example, counting how many fingers you have or counting how many items you bought when you went shopping. counting: statements in a program that record how many of something there are. To do this in a program you need to: • Initialise a variable to start the count, e.g. Countitems� 0. • Add 1 to the count variable each time, e.g. Count� Count + 1. Example 1 Count the number of items the user enters: Count� 0 //initialise the count variable Number� 0 WHILE Number <> -1 DO// loop until the user enters -2 Number� INPUT("Enter a number. Enter -1 to stop") Count� Count + 1 //add 1 to count each time a number is input ENDWHILE Example 2 Count how many numbers in an array are below 10, and how many are more than 20: CountBelowl0� 0 //initialise both counters to 0 CountAbove20� 0 FOR X� 0 to LENGTH(NumberArray) //loop through each array element 168 ) 7 Algorithm design and problem solving //if the number is less than 10 IF NumberArray[x] < 10 THEN CountBelowl0 � CountBelowl0 + 1 //increment the counter //if the number is greater than 20 ELSEIF NumberArray[x] > 20 THEN CountAbove20 � CountAbove20 + 1 //increment the counter ENDIF NEXT X PROGRAMMING TASK 7.4 A program needs to ask the user to input the weight of parcels being posted. It needs to count how many parcels are less than 1 kg, how many are between 1 kg and 2 kg, and how many are above 2 kg. Getting started 1 Recap how to count in an algorithm. What are the different pieces of code you need? For example, initialise the count to start at 0. 2 You will need to use selection to compare the inputs with the weights. Recap the use of selection and the format, including the differences between the operators>,>=,< and<=. Practice 1 Draw a structure diagram for the problem. 2 Write an algorithm to read in the weights of the parcels until the user has finished. 3 Amend the algorithm to count and output how many parcels are below 1 kg. 4 Amend the algorithm to also count and output how many parcels are between 1 and 2 kg. 5 Amend the algorithm to also count and output how many parcels are more than 2 kg. Challenge The user would like to enter the limits that they are counting themselves when the program starts. For example, counting how many parcels are less than 1.5 kg instead of 1 kg. Amend the program to make this change. Finding the minimum KEYWORD The minimum value is the smallest value within a set. For example, the marks for a class are entered and the lowest mark is the minimum. minimum: the smallest item in a set of data. To do this in a program you need to: • initialise a minimum variable to be a large value, beyond those that will be entered, e.g. Minimum � 9999. • Compare each value to the minimum variable, e.g. IF Number < Minimum. 169 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK • If it is, it replaces the minimum value, e.g. minimum .- number. This means the new value is the minimum, so the next time a value is compared, it is checking it with the new minimum value. Example 1 Find the smallest number input by a user: Minimum r 9999 //initialise minimum to large value Number r 1 WHILE Number >= 1 DO //loop until the user enters 0 Number r INPUT("Enter a number or Oto stop") IF Number < Minimum THEN // check if the number entered is smaller than //the current minimum Minimum r Number //if true then make minimum because the number ENDIF ENDWHILE Example 2 Find the smallest number in an array of data: Minimum r 999999 FOR X <- 0 TO LENGTH(NumberArray) IF NumberArray[X] < minimum THEN Minimum r NumberArray[X] ENDIF NEXT X Finding the maximum KEYWORD The maximum value is the largest value within a set. For example, the marks for a class are entered and the highest mark is the maximum. maximum: the To do this in a program you need to: • • • largest item in a set of data. Initialise a maximum variable to be a small value, beyond those that will be entered, e.g. Maximum r -9999. Compare each value to the maximum variable, e.g. IF Number > Maximum. If it is, it replaces the maximum value, e.g. Maximum r Number. This means the new value is the maximum, so the next time a value is compared, it is checking it with the new maximum value. Example 1 Find the largest number input by a user: Maximum r -9999 //initialise maximum to small value Number r 1 WHILE Number >= 1 DO //loop until the user enters 0 Number = INPUT( "Enter a number or 0 to stop") IF Number > Maximum THEN // check if the number entered is larger than //the current maximum Maximum r Number //if true then make maximum because the number ENDIF ENDWHILE 170 ) 7 Algorithm design and problem solving Example 2 Find the largest number in an array of data: Maximum� -1 // initialise the maximum value to a small number FOR X� 0 TO LENGTH(NumberArray) //check if the number entered is larger than the current maximum IF NumberArray[X] > Maximum THEN Maximum� NumberArray[X] //if true store the value in maximum ENDIF NEXT X Finding the average KEYWORD The average here is referring to the mean. This is the total of all the values added together, then divided by how many numbers there are. average: the mean For example, if the data is 1, 3, 5, 8, 4, 2, 6, 9 , the average = ( 1 + 3 + 5 + 8 + 4 + 4 + 6 + 9) I 8 = 40 / 8 = 5 of a set of values, the total divided by the quantity. To do this in a program you need to use the count and total from earlier in this section. T he average is then calculated with the formulae Total / Count. Example 1 Find the average of the numbers input by a user: Count� 0 //initialise the count to 0 Total� 0 //initialise the total to 0 Number� 1 WHILE Number >= 1 DO //loop until the user enters 0 Number� INPUT( "Enter a number or O to stop") Total� Total + Number //add the number entered to the total Count� Count + 1 //add 1 to the count ENDWHILE Example 2 Find the average of the numbers in an array of data: Count� 0 //initialise the count to 0 Total� 0 //initialise the total to 0 FOR X� 0 TO LENGTH(NumberArray) Total� Total + NumberArray[X] //add value to total Count� Count + 1 //add 1 to count NEXT X PROGRAMMING TASK 7.5 A teacher needs a system to calculate the lowest, highest and average mark their 30 students got in a test out of 100. Getting started 1 Identify the code required to work out the minimum and maximum values in a set of data. 171 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > 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 <-- INPUT("Enter a number between 1 and 10") IF Number < 1 OR 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 <-- INPUT("Enter a number between 1 and 10") WHILE Number < 1 OR Number > 10 DO OUTPUT("Invalid please try again") Number <-- INPUT() ENDWHILE Length check A length check will check the number of characters that are present. This could in a string, for example, the length of "hello world" is 11, the space is also a character. It could be in a variable, for example, in this example, 8 will be output: TheData <-- "123 ABC!" OUTPUT(LENGTH(TheData)) KEYWORD length check: a type of validation that checks the number of characters is within a set limit. The length of a piece of data can be found using a variety of commands depending on the language you are using. The following are all valid and there are many more: theData.length() LENGTH(theData) LEN(theData) theData.len A length check can be programmed using selection or iteration. Example 1 Using selection: This algorithm will check if the data input has 10 or less characters to be invalid, otherwise (10 or more) it is valid. 173 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Data � INPUT() IF LENGTH(Data) < 10 THEN OUTPUT("Invalid") ELSE OUTPUT("Valid") ENDIF Example 2 Using iteration: This algorithm will also check the length but will continually ask for this to be input until it is 10 or more characters long. Data � Input() WHILE LENGTH(Data) < 10 DO OUTPUT("Invalid, please try again") Data � INPUT() ENDWHILE Type check Data can be in different forms, including an integer (whole number), real (decimal number), string (any characters), Boolean (true or false). There are two ways of writing a type check: 1 2 Use a function such as . GetDataType() to return the data type, that you can then compare to the one you want. Use a function such as . IsInteger() to return True if it is an integer and False otherwise. KEYWORD type check: a type of validation that checks data is the correct data type. Example 1 Using selection: This algorithm will check if the data entered is an integer value to be valid. INPUT Data //check if the data entered is an Integer IF Data.GetDataType() <> Integer THEN //if it is not an integer OUTPUT ("Invalid") ENDIF Example 2 Using iteration: This algorithm will continually ask for the data to be input until it is a string value. INPUT Data //loop while the data entered is not a string WHILE Data.IsString = FALSE DO OUTPUT("Invalid please try again") INPUT Data ENDWHILE 174) 7 Algorithm design and problem solving Presence check KEYWORD Example 1 presence check: a type of validation that makes sure data has been entered. A presence check makes sure that some data has been entered. Programming languages can make use of the value null, or for a string value an empty string represented by "". Using selection: This algorithm outputs Invalid if there is no data entered. INPUT Data IF Data = NULL THEN //check if the data entered is null OUTPUT("Invalid") ENDIF Example 2 Using iteration: This algorithm continually takes an input while there is no data entered. INPUT Data WHILE Data = "" DO //loop while there is nothing in data OUTPUT("Invalid please try again") INPUT Data ENDWHILE Format check Some data may need to be entered in a specific way, for example, a date must be: __ I __ I ____, where each space is a number - a format check makes sure the data is entered this way. An ID number may need to be 1 number followed by 3 characters. Example 1 Using selection: KEYWORD format check: a type of validation that makes sure the data meets a specific order, e.g. 1 number, then 3 letters. An ID number entered needs to be 1 number followed by 2 characters. This algorithm checks the characters and outputs whether it meets the required format. INPUT IdNumber //check if the first character is a number, and characters 2 //and 3 are strings IF(SUBSTRING(IdNumber, 0, 1) .IsNumeric = TRUE AND SUBSTRING(IsNumber, 1, 2) = TRUE) THEN OUTPUT("Valid") ELSE OUTPUT ( "Invalid") ENDIF Note that SUBSTRING(String, X, Y) starts at character x in the string, and returns y number of characters. 175 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Example 2 Using a loop: This algorithm checks whether an input is in the format two numbers,/, two numbers, /, four numbers. INPUT Date //loop while the data is not in the correct format WHILE (SUBSTRING(Date, 0, 2) .IsNumeric = FALSE OR //2 numbers OR II 1st slash SUBSTRING(Date, 2, 1) <> = FALSE OR //2 numbers 2) .IsNumeric SUBSTRING(Date, 3' <> / /2nd slash OR SUBSTRING(Date, 5, 1) = FALSE) DO II 4 numbers, year 4) .IsNumeric SUBSTRING(Date, 6, OUTPUT("Invalid") INPUT Date ENDWHILE OUTPUT("Valid") 11 / 11 11 / 11 Check digit A check digit is calculated from a set of numbers, and is input with the numbers. When the data has been input, the calculation is performed on the data again and the result is compared with the final number (the check digit). Example This algorithm calculates the check digit using the method 5 digit number input. 9999, 4 digits used to calculate 5th check digit, and compares it to the input value. 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. INPUT Code //extract 1st digit Digitl r Code DIV 1000 Code r Code - (1000 * Digitl) //extract 2nd digit digit2 r Code DIV 100 Code r Code - (100 * Digitl) //extract 3rd digit Digit3 r Code DIV 10 Code r Code - (10 * Digitl) //extract 4th digit Digit4 r DIV(Code, 1) CheckDigit r Code //calculate check digit from data entered //multiply by position and add together Total r (Digitl * 4) + (Digit2 * 3) + (Digit2 * 2) + Digit3 NewCheckDigit r MOD(Total, 11) //find Mod 11 of total NewCheckDigit r 11 - NewCheckDigit //subtract result from newCheckDigit //check if the calculated check digit is the same as the last digit in the //code IF NewCheckDigit = CheckDigit THEN OUTPUT("Correct data entry") ELSE OUTPUT("Incorrect data entry") ENDIF You can find out more about check digits in Chapter 2. 176 ) 7 Algorithm design and problem solving Verification of data When entering data from another source, for example, a paper copy, it is important to make sure you have entered exactly what was written originally. This is called verification, a check that you have copied the data accurately. There is a difference between entering data accurately, and entering the correct data. Verification only checks you have copied it accurately, the actual data may still be incorrect if the original was incorrect. Two forms of verification are a visual check and double entry. A visual check is where you compare the data entered to the original. For example, reading each line from a paper copy and checking it is identical on the computer. A double entry check is where the same data is entered twice, usually by different people. The computer will then check whether there are any differences in what they each entered. COMPUTER SCIENCE IN CONTEXT Have you ever had to enter data into a program twice? You have most likely done this when entering your email address, or a password. Think about why it was important that your email and password were entered accurately. What could have happened if they were not? KEYWORDS verification: checking that data is entered accurately, that it is the same as the original. visual check: comparing the data entered with the original side-by-side. double entry check: two different people enter the same data which are then compared. PROGRAMMING TASK 7.6 A user needs to enter a series of data that each require validation. The table shows the data and the requirements: Data Validation requirements Username Minimum length of 5 characters. Date of birth In the format NN/NN/NNNN, e.g. 01/01/2020. Type of character Limited to: "Elf", "Fairy", "Gnome", "Magician". Starting strength A number between 1 and 5 inclusive. Starting health 10 minus the starting strength input. Getting started For each of the validation requirements, decide on which type of validation you are going to use. Try and choose a different one for each value. Recap the algorithms for each type, write an example beside each of the ones you have chosen. 177 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED Practice 1 Write an algorithm to take as input the five values. 2 Amend the program to include the validation for each item of data. 3 Amend your program to output, for each data item, whether their data is valid or invalid. Challenge Extend the program to repeatedly ask for each item of data until they enter one that is valid. Then the next piece of data should be input. Could any of the items of data have more than one validation rule used? Find at least one piece of data that can have two types of validation and implement it in your program. ACTIVITY 7 .8 Work in pairs to identify how many times you have come across validation or verification in a program or website. Compare your answers with another pair. How common are validation and verification? Are there any methods not identified here, for example, what is two-step verification? Questions 25 What is validation? 26 Give three examples of validation checks. 27 What is the purpose of verification? 28 Identify which validation rule this algorithm uses: INPUT Num IF Num > 0 AND Num < 100 THEN OUTPUT "Valid" ELSE OUTPUT "Invalid" ENDIF 29 Identify which validation rule this algorithm uses: REPEAT INPUT Value UNTIL Value <> NULL AND Value <> "" 30 Write a validation routine to input a word and check that it is more than 10 characters long. 31 Write a validation routine to input a number and check that it is an integer value. 178 ) 7 Algorithm design and problem solving 7 .8 Trace tables KEY WORD A trace table is a structure to help you follow an algorithm, for example, to find an error, or to work out what the algorithm does. Each statement in an algorithm is run manually, and the values that are written to variables are written in the table in the order the changes are made. Each column in the table is designated to one variable. There can also be a column for any outputs to be written in. User prompts are also entered in the trace table, these can be entered in a separate column or as an output (because they will be output). For example, x = input("Enter a number"), the text "Enter a number" is a user prompt and will need to be added to the trace table. trace table: a structure to complete when walking through an algorithm manually, where the values that change are written in each row. Specific inputs can be given to test different parts of the algorithm. SKILLS FOCUS 7.3 TRACE TABLE WITH SELECTION To create a trace table you need to identify all of the variables in an algorithm. Each variable should have its own column in the trace table. There should also be an output column if the program will output any data or strings. For example, trace the following algorithm with the input values 1 and 3. I INPUT Numberl INPUT Number2 IF Numberl > Number2 THEN OUTPUT(Numberl) ELSE OUTPUT(Number2) ENDIF I I There are two variables and there is an output (each variable has a column, and the output has a column). numbe,1 numbe,2 OUTPUT You then complete this table by reading through the algorithm one line at a time. It is important not to jump ahead and guess what the algorithm will do. Read one line and perform that action. Run line 1 of the code (input values 1, 3): INPUT Nwnberl INPUT Number2 IF Numberl > Number2 THEN OUTPUT(Numberl) ELSE OUTPUT(Number2) ENDIF 179 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED number1 number2 OUTPUT The first line inputs the first value given, 1. Run line 2 of the code (input values 1, 3): INPUT Numberl INPUT Number2 IF Numberl > Number2 THEN OUTPUT(Numberl) ELSE OUTPUT(Number2) ENDIF number1 number2 1 3 OUTPUT Run the IF statement: INPUT Numberl INPUT Number2 IF Numberl > Number2 THEN I OUTPUT(Numberl) ELSE OUTPUT(Number2) ENDIF � umbe,1 ACTIVITY 7. 9 I ..' 7...........____ ;umbe,2 Run the algorithm in Skills Focus 7.3 with the following input data: a 10, 2 b 9, 9 C 20, 30 Peer Assessment Compare your answers from running the algorithm with the different values with a partner. Did you get the same result? If not, work out which is correct by running the algorithms again. 180 ) The second line inputs the second value given, 3. Use the values in the table. numberl is 1, number2 is 3. IF 1 > 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 InputValue <---- 1 Total <---- 0 WHILE InputValue > 0 DO INPUT InputValue Total<---- Total + InputValue Count<---- Count + 1 ENDWHILE OUTPUT "The total is " Total OUTPUT "There were " , Count, " Numbers" I Start by creating the trace table with each of the variables and the output. There are 3 variables in this algorithm: 1 2 I lnputValue OUTPUT Run the first 3 lines of code. T hese are the initialisations, lines 0 1, 02 and 03. 01 Count <---- 0 02 InputValue<---- 1 03 Total <---- 0 Count lnputValue Total 0 1 0 OUTPUT Run line 04. 04 WHILE InputValue > 0 DO LOOP is 1 so this is TRUE meaning that the code inside the loop is run Run line 05 with the first input value of 4. INPUT InputValue 05 Count lnputValue Total 0 1 0 4 OUTPUT When a variable has a new value, it is written below the previous one. 181 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED 3 Run lines 06 and 07. Total r Total + InputValue 06 07 Count r Count + 1 count inputYalue total 0 1 0 4 1 4 Total r O + 4 Count r O + 1 OUTPUT 4 Line 08: 08 ENDWHILE sends you back to line 04. 04 WHILE InputValue > 0 DO InputValue is 4, so while 4>0 is TRUE to run line 05 with the second input value of 3. INPUT InputValue 05 count inputValue total 0 1 0 1 4 4 OUTPUT 3 5 Lines 06 and 07 run. Total r Total + InputValue 06 Count r Count + 1 07 Total r 4 + 3 Count r 1 + 1 OUTPUT count inputValue total 0 1 0 4 1 3 2 6 7 ENDWHILE returns to line 04. Line 08 WHILE 3 > 0 is TRUE. Run lines 05, 06 and 07. 04 WHILE InputValue > 0 DO INPUT InputValue InputValue r 2 05 Total r 7 + 2 Total r Total + InputValue 06 Count r 2 + 1 Count r Count + 1 07 count inputValue 0 1 1 2 3 7 4 4 3 2 total 0 OUTPUT 4 7 9 Line 08 again returns to line 04. WHILE 2>0 is TRUE. Run lines 05, 06 and 07. InputValue r 1 INPUT InputValue 05 Total r Total + InputValue 06 Total r 9 + 1 Count r 3 + 1 07 Count r Count + 1 182 ) 7 Algorithm design and problem solving CONTINUED count 0 1 2 inputValue 1 4 3 2 1 3 4 8 OUTPUT Line 08 returns to line 04 again. WHILE 1 >0 is TRUE. Run lines 05, 06 and 07. INPUT InputValue InputValue <--- 0 05 06 Total <--- Total + InputValue Total <--- 10 + 1 07 Count <---Count + 1 Count<--- 4 + 1 count inputValue total 0 1 2 1 4 3 2 1 0 4 7 9 10 10 3 4 5 9 total 0 4 7 9 10 0 OUTPUT Line 08 returns to line 04 again. WHILE 0 >0 is FALSE this time, so the loop does not run. Jump to line 09 run line 09 and 10. 09 OUTPUT "The total is ", Total 10 OUTPUT "There were ", Count, " numbers" count inputValue total 0 1 2 3 4 1 4 3 2 1 0 0 4 5 OUTPUT 7 9 10 10 The total is 10 There were 5 numbers � Be careful with your outputs. They must match the output in the code. For example, 'The total is 10' is correct, but 'total= 10' is incorrect. Questions 1 2 What do you record in a trace table? When do you change the value in a column? 183 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) ACTIVITY 7 .10 Trace the algorithm in Skills Focus 7.4 with the following inputs: a 1, 6, 8, 2, 0 b 1,-1,2 C 10,20, 30, -5 Self Assessment Trace the algorithms a second time and see whether you got the same result. If not, where did you go wrong? 7.9 Finding the purpose of an algorithm A trace table can help you work out the purpose of an algorithm. By following an algorithm step-by-step you can see what happens to the values, what changes are made, and when these are made. From this you can determine the purpose of the algorithm. SKILLS FOCUS 7.5 FINDING THE PURPOSE WITH A TRACE TABLE Describe the processes in this algorithm and state its purpose. INPUT Valuel INPUT Value2 INPUT Value3 IF Valuel > Value2 AND Valuel > Value3 THEN OUTPUT(Valuel) ELSEIF Value2 > Valuel AND Value2 > 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 <= 100 THEN Quantity� Quantity + 1 Total� Total + Value IF Value < Small THEN Small� Value ENDIF ENDIF ENDWHILE OUTPUT("small Small) OUTPUT(Total / Quantity) quantity Total value small Copy the trace table and test the algorithm in 03 with some sample data, e.g. 1, 100, 50, 10, 33, 3, 42. OUTPUT 185 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK SKILLS FOCUS 7.6 DESCRIBING AN ALGORITHM When you are describing an algorithm you need to do more than repeat the line of code using English statements. For example, in the following code, for line 02 don't just say, 'it is a for loop from y is O to x.' This is stating what each part of the code is, but it does not describe the algorithm. 01 INPUT X 02 FOR Y <-- 0 TO X OUTPUT Y 03 04 NEXT Y You can do a trace table to help you work out the purpose of the algorithm before describing it if that helps you. This algorithm has three parts: line 01, line 02 and line 03. These are summarised below: • Takes a number as input. (line 01) • Loops from O to the number that has been input. (line 02) • Outputs the values from O to the number. (line 03) From this you can develop a description of the algorithm, for example: The algorithm takes a number from the use,� and then outputs all of the numbers from 0 to the number input. Questions 1 2 3 What methods can you use to work out the purpose of an algorithm? Why should your description explain more than what each part of the code does? Describe the purpose of this algorithm: 01 X <-- -1 02 Count <-- 0 03 WHILE Count < 10 DO 04 INPUT Y 05 IF Y > X THEN X = y 06 ENDIF 07 08 Count <-- Count + 1 09 ENDWHILE 10 OUTPUT(X) 186 ) 7 Algorithm design and problem solving 7 .10 Finding errors in a program and correcting the errors To find an error in an algorithm you need to know the purpose of the algorithm. You can then test the algorithm with different data, completing trace tables if needed, to find out what the algorithm actually does. Once you know the difference between what it does and should do, you can start to identify the errors and the changes you need to make. COMPUTER SCIENCE IN CONTEXT Computer programmers will come across errors all the time. These could be ones that they have made, or that they are testing or fixing for other people. There are lots of ways that they can find the errors, but many of them will use the two methods used here; using a trace table, and d ry running by reading the code. There are other options often available to them as well, for example, features within the Integrated Development Environment (!DE) that they use to write the program. These features allow the programmer to see the values of variables and the outputs at each stage, without having to trace them manually. SKILLS FOCUS 7.7 USING A TRACE TABLE TO FIND ERRORS IN A PROGRAM Using a trace table will allow you to follow each step in the algorithm and by comparing this to the intended outcome you can find where it goes wrong, and then work out how to correct it. For example, this program should take 5 numbers as input and output the total of all the numbers. 01 02 03 04 05 06 07 08 Total<- 1 Quantity<- 1 WHILE Quantity < 5 DO INPUT Number Total<- Number Quantity<- Quantity + 1 ENDWHILE OUTPUT (Total) First dry run the algorithm. If not provided, you will need to identify some test data to use. This algorithm should take 5 numbers as input, so you could use 1, 2, 3, 4, 5. Then work out what the result of the algorithm should be. It outputs the total, so it should output: 1 +2+ 3+4+5= 15 187 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED Now draw a trace table for the algorithm (revisit the section on trace tables if needed) and then run each step of the algorithm, writing the values in the table. Total Quantity 1 1 1 2 3 4 5 2 3 4 Number OUTPUT 1 2 3 4 Now look at the results and where it has gone wrong: 1 2 3 The total is overwritten each time, it should be added to. Total starts with 1 but this will add another 1 to the total, so it should be 0. Only four numbers can be input, it should be five. Let's take each of the problems one at a time to solve them. 1 2 3 The total should not be overwritten. Line 05 overwrites the total. This should be Total<--- Total + Number. The total should not start at I, it should be 0. Line 01 writes I to total. This line should be Total<--- 0. Only 4 numbers are input, it should be 5. There are two ways this can be changed, both are valid. Either Line 02 can be Quantity <--- 0 or line 03 can be WHILE Quantity < 6. SKILLS FOCUS 7.8 FINDING ERRORS BY READING THE CODE You may not always need to use a trace table, or you may not want to. There are many different ways of finding the errors. In this example you will look for each of the requirements in the algorithm to determine whether it has been met. The following algorithm should take 3 numbers as input, and output the largest value and the average value. 01 02 03 04 05 06 07 08 09 10 11 12 188 ) Total<--- 0 Largest <--- 999 FOR X <--- 0 TO 2 INPUT Data IF Data < 999 THEN Large <--- Data ENDIF Total<--- Total + Data NEXT X OUTPUT Largest Average <--- Total I 3 OUTPUT Average 7 Algorithm design and problem solving CONTINUED Re-read the description: take 3 numbers as input, and output the largest value and the average value. This can be split into three sections: 1 2 3 Take 3 numbers as input. Output the largest value. Output the average value. The two outputs need to be calculated before being output, so they can be added to the requirements: 1 2 3 4 5 Take 3 numbers as input. Calculate the largest value. Output the largest value. Calculate the average value. Output the average value. Now check the first requirement: Does it take 3 numbers as input? The for loop goes from 0 to 2, so it will nm 0, 1, 2 = 3 times. Inside the loop it inputs a value each time. This is correct. The second requirement: Calculate the largest value. To find the largest it needs to: a Initialise a largest variable with a low number. This is not met. Line 02 largest is set to 999 but this should be a very small value, e.g. Largest <--- -1 b It should check if the data input is larger than the data in largest. This is not met. Line 05 checks if data is less than 999. It should be larger. IF Data > Largest THEN c Line 06 replaces the value in Large with data, but the identifier is incorrect, the variable is named largest. Largest <--- Data The third requirement: Output the largest value. Line IO outputs the largest value, this is correct. 189) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED The fourth requirement: Calculate the average value. The average is calculated by totalling the inputs and then dividing by the number of inputs. Line 08 totals the data entered, but it uses the wrong identifier, it should be data not DATA. Total r Total + Data Line 11 works out the average correctly. The fifth requirement: Output the average value. Line 12 outputs the average correctly. In this case the errors and corrections have been identified along the way. You can also combine this with using test data to check both the original algorithm and to check that your corrections are accurate. Questions 1 Complete the trace table for the following algorithm with the input data: 20 50 60 25 35. Total r 0 Average r 0 Counter r 0 WHILE Counter <= 5 DO INPUT Mark Total r Total + Mark Counter r Counter + 1 ENDWHILE Average r Total/ Counter OUTPUT "The total is ", Total OUTPUT "The average is ", Average Total 190 ) Average Counter Mark OUTPUT 7 Algorithm design and problem solving CONTINUED 2 a Complete the trace table for the following algorithm using the input data: 7. INPUT Number WHILE Number >= 0 DO OUTPUT Number Number � Number - 1 ENDWHILE Number b 3 OUTPUT State the purpose of the algorithm. Explain the purpose of the following algorithm: Valid� 0 Invalid� 0 Continue � "Y" WHILE Continue = "Y" DO INPUT Value IF Value >= 10 AND Value <= 20 THEN Valid� Valid + 1 ELSE Invalid� Invalid + 1 ENDIF OUTPUT "Continue?" INPUT continue ENDWHILE OUTPUT "valid = " Valid OUTPUT "invalid = ", Invalid 191 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK SUMMARY Programs are developed by following a program development life cycle. The program development life cycle is made up of; analysis, design, coding and testing. In the analysis stage the problem is identified and decomposed. In the design stage the algorithms are planned. In the coding stage the program is written. In the testing stage the program is tested. Decomposition is the splitting of a system into sub-systems. Decomposition can be shown using a structure diagram. Algorithms can be planned using flowcharts and pseudocode. A linear search checks each item of data in turn. A bubble sort compares the items in pairs repeatedly. Totalling is adding together the values. Counting is adding 1 to the count for each item. To find the minimum value, a variable needs to be initialised with a large value. To find the maximum value, a variable needs to be initialised with a small value. Validation is checking data entered is reasonable and within bounds. Validation checks include; range check, length check, type check, presence check, format check and check digit. Verification checks that data has been input accurately. Verification checks include visual check and double entry check. Four types of test data are normal, abnormal, extreme and boundary. A trace table is used to dry run an algorithm. It can be used to find the purpose of an algorithm and to find errors in the algorithm. - EXAM-STYLE QUESTIONS COMMAND WORDS 1 Define the term algorithm. [1 l 2 One stage of the program development life cycle is the analysis. Identify and describe two other stages. [4] 3 Describe the purpose of decomposition. [2] 4 A computer game allows a user to load a saved game or to start a new game. The game then loads the puzzle for that level. The user controls a character by using the arrow keys on the keyboard. The left arrow moves the character left, the up makes the character jump, right moves the character right, down makes the character lie down. a Draw a structure diagram for the game. [4] define: give precise 192 ) meaning. identify: name/ select/ recognise describe: state the points of a topic I give characteristics and main features. 7 Algorithm design and problem solving CONTINUED b Write an algorithm using a flowchart to represent the input of a key from a user, and then move the character. c When the user starts a new game, they have to input a name that is made of at least 8 letters. This is validated using a length check. Identify one other appropriate validation routine that could be used to validate the name. ii Write, using pseudocode, the length check validation for the name. [6] [1] [4] [Total: 15] 5 Complete the trace table for the following algorithm, with the input data: I blue I I I 5 Y blue Y yellow 3 Y white 5 x I Blue +- 10 White +- 5 Yellow+- 2 Continue +- "Y" WHILE Continue = "Y" DO INPUT Colour INPUT Quantity IF Colour = "Blue" AND Quantity <= Blue THEN Blue +- Blue - Quantity OUTPUT "Blue left = ", Blue ELSEIF Colour = "White" AND Quantity <= White White +- White - Quantity OUTPUT "White left = ", White ELSEIF Colour = "Yellow" AND Quantity <= Yellow OUTPUT "Yellow left = ", Yellow ELSE OUTPUT "Try again" ENDIF OUTPUT "Continue?" INPUT Continue ENDWHILE Blue White Yellow Continue Colour Quantity OUTPUT [5] 193) > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED COMMAND WORD 6 Show the stages of a linear search, when looking for the number 100 in show (that): provide the following data: 10 20 8 6 5 3 7 Show the stages of a bubble sort to put the following data into ascending alphabetical order: I apple I pear I banana I pineapple I orange I peach 8 The following algorithm should: [3] [5] • Ask the user to input a number 20 times. • Count and output how many numbers are less than 10, equal to 10, and more than 10. • Calculate and output the average number entered. 01 TotalLess<---- 0 02 Equal <---- 0 03 TotalMore <---- 0 04 Total <---- 0 05 FOR X<---- 0 TO 20 06 07 INPUT Number IF Number <= 10 THEN TotalLess<---- TotalLess + 1 08 09 ELSEIF Number <> 10 THEN 10 Equal<---- Equal + 1 11 ELSE 12 TotalMore <---- TotalMore + 1 13 ENDIF 14 Total<---- Total + Number 15 NEXT X 16 OUTPUT "Total less = " 18 OUTPUT "Total more = " 17 OUTPUT "Total equal = 19 OUTPUT "Average = " ' TotalLess " ' Equal ' TotalMore ' Total I 20 The algorithm has four errors in it. Identify the line number of each error and write the corrected line for each. [4] 194 > 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 &lt �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<U ("Wu:t"l .Su.bt :�!::�.!;!�!; . , �e1!:��:�t:;!::�1!:!::'c • !�!::�i.!�!!��s!:!:��> :�b ra1ae, r..iaa, ral••• Tal••• f'alae, f'al••• falae. ral.••• Tal.ae, On r;rror GoTo Tehler L------�l'J x Loh1l = w.. Figure 8.1: Image of a man reading program code 197 ) CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED In VB.NET: In Java: FOR count = 1 to 10 Console.writeline(count) NEXT count for(count = 1; count < 11; count++) { System.out.println(count); These all do the same functions, and they all follow the same principles. They start with the word 'for'. They have a variable (count). They set the starting value and they say when to stop. So once you can do a for loop in VB.NET, you should just be able to search for how to do it in Python and just change a couple of the words. Discussion questions 1 Why do you think all these languages have similar constructs? 2 Find some constructs that are in one language, e.g. VB.NET, and not in another, e.g. Python. 8.1 Programming concepts This chapter will introduce different code examples. It will show how to do each of the procedures in three different languages (Java, VB.NET and Python) and pseudocode. The pseudocode (red font) will always appear as the first code in each example. Variables and constants What are variables and constants? When you are writing a program, you will need to store data; whether this is data that has been input, the result of calculations or any for any other reason. You can store data in variables and constants. A computer has memory, e.g. RAM. This is made of lots of spaces where you can put data. Imagine this table is memory. Each of the boxes can store a piece of data. 0 10 1 Red 3 True 2 22.5 4 5 6 7 In memory location 0 is the data 10. In memory location 1 is the data red. Each variable and constant is one of these spaces in memory that is given an identifier (it has a name). In this table the memory numbers have been replaced with their identifiers. The memory space with the name numberl is storing the piece of data 10. 198 ) KEYWORDS variable: a named memory location that can store data. The data can change whilst a program is running. constant: a named memory location that can store data. The data cannot change whilst a program is running. identifier: a name given to a variable, constant, data structure (e.g. array) or subroutine. 8 numberl Programming 10 colour red price 22.5 finished True 4 5 6 7 Variables and constants have one difference. In a variable, you can change the data while the program is running. For example, putting the number 3 0 into memory location numberl, the memory would then look like this: numberl 30 price red 22.5 finished True colour 4 5 6 7 A constant cannot have its value changed while the program is running. When you declare a constant you put a value into it and this cannot be changed. Using variables Putting data into a variable is done using an assignment statement. The left hand side of the equals sign is the identifier. The right hand side of the equals sign is the value (see Figure 8.2). KEY WORD assignment: a type of programming statement that stores data in a variable or constant. number = 10 Figure 8.2: Components of an assignment Number <-- 10 Colour <-- "red" Price <-- 22.2 199 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) VB.NET Dim number As Integer Dim colour As String Dim price As Single number = 10 colour = "red" price = 22.2 Python number = 10 colour = "red" price = 22.2 Java public static void main(String args[]) { Integer number = 10; String colour = "red"; Double price = 22.2; To get data out of a variable you just use its identifier (see Figure 8.3). print (number) Figure 8.3: Printing the contents of a variable Number r 10 Colour r "red" OUTPUT(Number) OUTPUT("The colour is Price r Number * 2 Colour) VB.NET Dim number As Integer Dim colour As String = "red" Dim price As Single Console.WriteLine(number) Console.WriteLine("The colour is " & colour) price = number * 2 200) 8 Programming Python colour = "red" number = input() print("The colour is", colour) price = number * 2 Java public static void main(String args[]) { Integer number = 10; String colour = "red"; System.out.println("The colour is " + colour); Integer price = number * 2; Using constants Before you use a constant in your program you need to give it a value. This is an assignment statement the same as a variable. (No examples are given for Python as it does not have in-built constants.) CONSTANT Colour <-- "yellow" VB.NET Const colour As String "yellow" Java public static void main(String args[]) { final String colour = "yellow"; Using the key word constant makes it clear that this value cannot then be changed. You get data out of a constant the same way as a variable, by using its identifier. OUTPUT(Colour) VB.NET Const colour As String = "yellow" Console.Writeline(colour) Java public static void main(String args[]) { final String colour = "yellow"; System.out.println(colour); 201 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK 8.2 Data types Data in programs can be of different types. For example, it could be numeric or text. You will need to tell your program what type of data you want it to store. Some programming languages need you to declare what type of data your variable will store when you first use it. In some programming languages you need to swap data between types, for example, Python will only output string (text) data, so if you try and output a number without turning it into a string it will produce an error. Table 8.1 shows common data types: Data type Description String Text- characters numbers and symbols. "hello" The data will always need to be inside speech marks, either ' ' or " " "help!" Integer Whole numbers. Example data "123" 1 23 -300 Real, single, double Decimal numbers. Char Either true or false. One character or number of symbol. The data will always need to be inside speech marks, either " or "". data type: the characteristics of a piece of data. Common data types are string, integer, real and Boolean. integer: a data type. Whole numbers. real: a data type. 23.0 single: a data type. 3949.3834 TRUE FALSE "h" II 9 II ti? .. Table 8.1: Common data types ACTIVITY 8.1 Take each data type in turn and think of at least 10 different examples of data that can be stored (apart from Boolean where there can be only two). From these, identify whether any of these could be more than one data type, discuss in pairs what options would be valid and which would be most appropriate. Peer Assessment Compare your work with another pair. Identify if all of the data is appropriate for the data type chosen. Discuss the choices, e.g. if one was more appropriate than the other? 202) string: a data type. Any characters including letters, numbers and/or symbols. 45656 1. 2 -20.49 Boolean KEYWORDS Decimal numbers. Decimal numbers. double: a data type. Decimal numbers. Boolean: a data type. True or False. char: A single character, e.g. 'A', 8 Programming Storing different data types Storing a string in a variable: Colour<- "red" Storing an integer in a constant: CONSTANT Value <- 10 Storing a real number in a variable: Price<- 22.4 Storing a Boolean in a variable: Flag<- TRUE VB.NET Dim colour As String = "red" Const value As Integer = 10 Dim price As Single 22.4 Dim flag As Boolean = True Python colour = "red" value = 10 price = 22.4 flag = True Java public static void main(String args[)) { String colour = "red"; final Integer value = 10; 22.4; Double price Boolean flag = true; Converting between data types You might need to turn one data type into another data type. This is not required as part of the specification, but when you are programming in your chosen language you might have to do it for your program to work. This is called casting. You can do this by using the name of the data type you want the data to become. Example 1 KEYWORD casting: converting data from one data type to another data type. Convert a string to an integer: Number<- int("123") 203 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > VB.NET Dim number As Integer number = Convert.Toint16("123") Python int("123") number Java public static void main(String args[]) { Integer number = Integer.parseint("123"); Example 2 Convert a number to a string: Value � string(22.4) VB.NET Dim value As String value = Convert.ToString(22.4) Python value str(22.4) Java public static void main(String args[]) { String value = Double.toString(22.4); Questions 1 Tick one or more boxes in each row to identify whether each statement refers to variables and/or constants. Statement You cannot change the value when the program is running. It has an identifier. It is a memory location. You can change its value when the program is running. It stores a piece of data. ?04) Variable Constant 8 2 3 Programming Write a pseudocode statement to assign the word "house" to a variable named MyWord. Write a pseudocode statement to declare a constant named MultiplyValue with the value 10. 8.3 Input and output Output A program at some point will probably need to give information to the user. It does this using output. When outputting strings (characters, letters, etc.). Example 1 KEYWORD output: data that is displayed to the user usually on-screen. Output the words, Hello World: OUTPUT("Hello world") VB.NET Console.WriteLine("Hello World") Python print("Hello World!") Java public static void main(String args[]) { System.out.println("Hello World"); Example 2 Output the number 20: OUTPUT(20) VB.NET Console.WriteLine(20) Python print(20) 205 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Java public static void main(String args[]) { System.out.println(20); If you want to output more than one piece of data then you can join them using a concatenation symbol. Concatenation means join together, so it joins multiple pieces of data together. This could be a comma (, ), an ampersand (&) or a plus (+) depending on your language. All are acceptable in pseudocode. Example 1 Output the word Hello, then the contents of variable name: OUTPUT("Hello ", Name) VB.NET Dim name As String = "Alex" Console.WriteLine("Hello " & Name) Python name = "Alex" print("Hello", name) Java public static void main(String args[]) { String name = "Alex"; System.out.println("Hello " + name); Example 2 Output the cost of an item stored in the variable cost: OUTPUT("The cost is " , Cost) VB.NET Dim cost As Single = 22.54 Console.WriteLine("The cost is " & cost) Python cost = 22.54 print("The cost is", cost) 206) KEY WORD concatenation: joining two or more strings together. 8 Programming Java public static void main(String args[]) { Double cost= 22.54; System.out.println("The cost is " +cost); Example 3 Output the number of balloons stored in the variable balloon: OUTPUT("There are " , Balloon , " balloons") VB.NET Dim balloon As Integer= 100 Console.WriteLine("There are " & balloon & "balloons") Python balloon= 100 print("There are", balloon, "balloons") Java public static void main(String args[]) { Integer balloon= 100; System.out.println("There are "+balloon+" balloons"); In these examples you will see there are spaces within the speech marks. This is because OUTPUT ("Hello", Name) would join these together, e.g. HelloJane. When writing in pseudocode it is not important that these are included, but you might need to do it when outputting in your chosen programming language. Input KEYWORD A program might need the user to enter (input) some data. To do this, the command word INPUT is used. This cannot appear on its own, otherwise the data entered will disappear into space. So you need to do something with it, for example, store it in a variable. input: the user entering data into the program, usually from a keyboard. Example 1 Input a number and store it in a variable: INPUT Number VB.NET Dim number As Integer number= Console.ReadLine 207 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python number = int(input()) Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); Integer number = Integer.parseint(scanner.nextLine()); Example 2 Tell the user to enter a word and store it in a variable: OUTPUT("Enter a word") INPUT Word VB.NET Dim word As String Console.WriteLine("Enter a word") word = Console.ReadLine Python number input("Enter a word") Java public static void main(String args[]) { System.out;println("Enter a word") Scanner scanner = new Scanner(System.in); String word = scanner.nextLine(); PROGRAMMING TASK 8.1 A program asks the user to register for a new account. The user needs to enter key information, e.g. name, date of birth, select a username, etc. Getting started 1 Work in pairs to list the different items that the program will collect. 2 Identify the most appropriate data type for each of the items you have identified. 208) 8 Programming CONTINUED Practice 1 Select appropriate variables for the items you have identified that you are going to store. 2 Write a program to ask the user to enter each of the items in turn. Read in each value and store it in an appropriate variable. 3 Output a message confirming the details that the user has entered. Challenge 1 The username needs to be at least 8 characters long. Find out how to work out the length of a string input and output how many characters the user has entered. 2 Find out how to use selection statements to check the length of the string and if it is not long enough, ask the user to enter a different username. KEYWORD 8.4 Arithmetic operators Arithmetic operators instruct a program to perform calculations. Table 8.2 describes the most common operators, many of which you will know from mathematics. Operator Description + Adds two values together. - * I DIV MOD A Subtracts the second value from the first. Multiplies two values together. Divides the first number by the second. Gives the whole number after the first number is divided by the second, i.e. it ignores any decimals. Example 10 + 2 gives 12 11. 3 10 - + arithmetic operator: a symbol that performs a mathematical function, e.g. '+' adds two values together. 9 gives 20.3 2 gives 8 11. 3 - 9 gives 2.3 10 * 2 gives 20 11. 3 * 9 gives 101.7 10 I 2 gives 5 11. 3 I 9 gives 1.256 DIV(10, 2) gives 5 DIV(ll, 9) gives 1 Gives the remainder after the first number is divided by the second, i.e. how many are left. MOD(10, 2) gives 0 Power of. 2 MOD(ll, 9) gives 2 3 A A 3 = 8 2 = 9 Table 8.2: Common operators 209) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) MOD has one special use in programming.It can be used to work out if a number is odd or even.If you perform MOD 2 to a number and it returns 0 then it is even, if it returns 1 then it is odd. Example: MOD(l 0, 2) = 0 therefore 10 is even. MOD(l 1, 2)=1 therefore 11 is odd. SKILLS FOCUS 8.1 MOD VS DIV It is important that you know the difference between MOD and DIV. They are similar in their function, but are often confused with division(/). You need to be able to use both of these, both to identify the result of the operation, and to be able to write programs using them.In this Skills Focus you will be calculating the result from a MOD and DIV operation. DIV gives the whole number after the division and ignores any remainder. a 10/2=v5 There is no remainder, so DIV(l 0, 2)=5. b 20/7= 2.857 There is a remainder, so DIV(20, 7)= 2(ignore the numbers after the decimal point). c 100/21=4.762 There is a remainder, so DIV(l00, 21)=4(ignore the numbers after the decimal point). MOD gives the remainder after division. This is not the decimal point, but how many values are left. a 10/2=5 There is no remainder, so MOD(l0, 2)=0. b 20/7= 2.857 There is a remainder. Take the DIV result(2) and multiply it by the divisor number. 7 * 2= 14. The remainder is how many more numbers are between 14 and the 20(20- 6). The answer is 6. c 100/21=4. 76 2 There is a remainder. Take the DIV result(4) and multiply it by the divisor 21 * 4= 84. The remainder is 100- 84 which is 16. d 30/9=3.3333 There is a remainder. 9 * 3= 2 7. 30- 2 7=3. Questions 1 2 Calculate the result for each of these equations: a DIV(9, 2) b DIV(! 7, 3) Calculate the result for each of these equations: a MOD(9, 2) b MOD(1 7, 3) COMPUTER SCIENCE IN CONTEXT Many of these arithmetic operators should be familiar to you from mathematics, where you should be used to working out expressions. In programming the same principles are used, you write the formulae but not the answer - the computer works that out because the input data can be changed. 210 ) I I KEYWORDS MOD: remainder division. The remainder after the division is performed, e.g. MOD(5, 2) = 2. DIV: integer division. The remainder from the division is ignored, e.g. DIV ( 5, 2) = 2. 8 Programming T he operators for DIV and MOD will differ depending on the programming language you are usmg. Example 1 Taking two numbers as input and adding them together: OUTPUT("Enter the first number") INPUT Numl OUTPUT("Enter the second number") INPUT Num2 Total� Numl + Num2 VB.NET Dim numl As Integer Dim num2 As Integer Dim total As Integer Console.WriteLine("Enter the first number") numl = Console.ReadLine Console.WriteLine("Enter the second number") num2 = Console.ReadLine total = numl + num2 Python numl = int(input("Enter the first number")) num2 = int(input("Enter the second number")) total = numl + num2 Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the first number"); Integer numl = Integer.parseint(scanner.nextLine()); System.out.println("Enter the second number"); Integer num2 = Integer.parseint(scanner.nextLine()); Integer total = numl + num2; Example 2 Subtracting IO from 20: Numberl � 10 Number2� 20 Result� Number2 - Numberl VB.NET Dim numberl As Integer = 10 Dim number2 As Integer = 20 Dim result As Integer result = number2 - numberl 211 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python numberl = 10 number2 = 20 result = number2 - numberl Java public static void main(String args[]) { Integer numberl = 10; Integer number2 = 20; Integer result = number2 - numberl; Example 3 Multiplying two values together: Numberl +-- 5 OUTPUT("Enter a number") INPUT Number2 Result +-- Numberl * Number2 VB.NET Dim numberl As Integer = 5 Dim number2 As Integer Console.WriteLine("Enter a number") number2 = Console.ReadLine Dim result As Integer result = number2 * numberl Python numberl = 5 number2 = int(input("Enter a number")) result = numberl * number2 Java public static void main(String args[]) { Integer numberl = 5; System.out.println("Enter a number"); Scanner scanner = new Scanner(System.in); Integer number2 = Integer.parseint(scanner.nextLine()); Integer result = numberl * number2; 212 ) 8 Programming Example 4 Dividing 100 by 5: Numberl <--- 100 Number2 <--- 5 Result<--- Numberl / Number2 VB.NET Dim numberl As Integer 100 5 Dim number2 As Integer Dim result As Single result = number2 / numberl Python numberl = 100 number2 = 5 result = number2 / numberl Java public static void main(String args[]) { Double numberl = 100.0; Double number2 = 5.0; Double result = number2 / numberl; Example 5 Finding the whole number after dividing 33 by 7: Result<--- DIV(33, 7) VB.NET Dim result As Single result = 33 \ 7 Python result = int(33 / 7) Java public static void main(String args[]) { Integer result = 33 / 7; 213 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Example 6 Finding the remainder after dividing 33 by 7: Result� MOD(33, 7) VB.NET Dim result As Single result = 33 Mod 7 Python result 33 % 7 Java public static void main(String args[]) { Integer result = 33 % 7; Calculations can use parentheses (brackets) to change the order the calculations are performed in. The calculations within the brackets are done first. Example 7 Total� 1 + (2 * 3) Total� (1 + 2) * 3 The first line will result in 7 (3 * 2 = 6 + 1 = 7). KEYWORD parentheses: brackets in a mathematical statement. They determine which calculations are performed first. The second line will result in 9 (1 + 2 = 3 * 3 = 9). 8.5 Sequence Sequence is the first of three constructs within programs. A sequence is a series of statements that are executed (run) once, in the order they are written. Example 1 OUTPUT("Enter a colour") INPUT Colour OUTPUT("Enter your name") INPUT Name OUTPUT(Name , " your favourite colour is " , Colour) VB.NET Dim colour As String Console.WriteLine("Enter a colour") colour = Console.ReadLine() Dim name As String Console.WriteLine("Enter your name") 214 ) KEYWORD sequence: a programming construct. Instructions are run once and in the order they are written. 8 Programming name = Console.ReadLine() Console.WriteLine(name & " your favourite colour is " & colour) Python colour = input("Enter a colour") name = input("Enter your name") print(name, "your favourite colour is", colour) Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a colour"); String colour = scanner.nextLine(); System.out.println("Enter your name"); String name = scanner.nextLine(); System.out.println(name + " your favourite colour is " + colour); This is a sequence. It has 3 lines are executed once, and in the order they are written (line 1, then 2 then 3). Example 2 X<- 1 y<- 2 Z <- 3 Total<- X + Y + Z OUTPUT("Enter the first value") INPUT Valuel VB.NET Dim X As Integer = 1 2 Dim y As Integer 3 Dim z As Integer Dim total As Integer = X + y + z Dim valuel As String Console.WriteLine("Enter the first value") valuel = Console.ReadLine Python 1 X y = 2 z = 3 total = x + y + z valuel = int(input("Enter the first value")) 215 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Java public static void main(String args[]) { Integer X = l; Integer Y = 2; Integer Z = 3; Integer total = X + Y + Z; String valuel; System.out.println("Enter the first value"); Scanner scanner = new Scanner(System.in); valuel = scanner.nextLine(); Questions 4 Give the result from the following calculations: a b C d 5 6 7 10 + 20 20 / 2 100 * 4 50 - 15 e f g h 20 DIV 2 39 DIV 6 20 MOD 2 40 MOD 6 Write a program to take a number as input, multiply it by 2 and output the result. Write a program to store the numbers 10 and 12 in constants, add them together and then output the result. Write a program to ask a user to enter their age and name, then output a message that uses both values, e.g. Hello Suzie you are 15 year old. 8.6 Selection Selection is the second of the three constructs. In selection a condition is checked and this determines which, if any, code is run. There are two forms of selection, IF statements and CASE statements. Conditions need logical operators. These allow for comparisons to be made. Table 8.3 describes these different operators. Each statement using a logical operator results in TRUE or FALSE. KEYWORDS selection: a programming construct. A condition is checked and this determines which code is run, or not run. IF statement: a type of selection construct where the result of the condition is either true or false. CASE statement: a type of selection construct where there is a list of different values to compare a single value against. logical operator: a 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. Example Logical operator Description =or== Equals to 10 = 10? would give TRUE. 10 is equal to 10. Not equal to 10 = 2? would give FALSE. 10 is not equal to 2. 10 <> 10? would give FALSE. 10 is not, not equal to 10. Less than 10 <> 2? would give TRUE. 10 is not equal to 2. 10 < 11? would give TRUE. 10 is less than 11. <> or!= < 10 < 10? would give FALSE. 10 is not less than 10. 11 < 10? would give FALSE. 11 is not less than 10. 216 ) (continued) 8 Programming Logical operator Description Example <= Less than or equal to 10 <= 11? would give TRUE. 10 is less than or equal to 10. > Greater than 10 <= 10? would give TRUE. 10 is less than or equal to 10. 11 <= 10? would give FALSE. 11 is not less than or equal to 10. 10 > 11? would give FALSE. 10 is not greater than 11. 10 > 10? would give FALSE. 10 is not greater than 10. >= Greater than or equal to 11 > 10? would give TRUE. 11 is greater than 10. 10 >= 11? would give FALSE. 10 is not greater than or equal to 11. 10 >= 10? would give TRUE. 10 is greater than or equal to 10. 11 >= 10? wou Id give TRUE. 11 is greater than or equal to 10. Table 8.3: Logical operators SKILLS FOCUS 8.2 COMPARISON OPERATORS Comparison operators are used in comparison statements; both selection and iteration. The operators are very similar and you need to know the difference to make sure you know, a, how to read the statements to make sure you follow an algorithm correctly, and b, which to select when you are writing your own comparison statements. A common error is when less than and greater than are confused. The shape of them can help you to work out which is correct. IF ( 10 < 2) The smaller part of the< is nearest the left, the 10. This is the less than part. So the statement reads if 10 is less than 2. This would result in False because 10 is not less than 2. IF ( 150 > 2 5) The larger part of the > is nearest the left, the 150. This is the greater than part. So the statement reads if 150 is greater than 25. This would result in True because 150 is greater than 25. IF ( 3 3 <= 3 4) The smaller part of the<= is nearest the left, the 33. This is the less than part. There is also an equals after the less than sign. So the statement reads if 33 is less than or equal to 34. This would result in True, 33 is less than 34. IF ( 50 > = 7 0 ) The larger part of the > = is nearest the left, the 50. This is the greater than part. There is also an equals after the less than sign. So the statement reads if 50 is greater than or equal to 70. This would result in False, 50 is not greater than or equal to 70. 217 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED Questions 1 2 Put each statement into words: a IF( 1 < 2) Look at the left of the symbol. Is it small or large? Write the first number, followed by the symbol name, then the second number. b IF(6 > 3) IF(999 >= 998) C d IF(34 <= 77) Work out if each statement is True or False. a IF(66 < 40) b IF(l00 > 101) C IF(90 <= 45) d IF(30 >= 30) IF statements The command IF is followed by a condition that is created using the logical operators. T here are three stages of IF statements; IF, ELSE and ELSEIF. IF has one comparison and the code inside the IF will only run if that condition is True. If it is not true, the code in the IF statement will not run. It follows the structure: IF comparison THEN Statements that run if the comparison is true ENDIF Example 1 This program will check the value in the variable numl is equal to 10. If it is, it will output the word True. Numl <-- 10 IF Numl = 10 THEN OUTPUT( "True") ENDIF VB.NET Dim numl As Integer = 10 If numl = 10 Then Console.WriteLine("True") End If Python numl = 10 if numl == 10: print ("True") 218 ) 8 Programming Java public static void main(String args[]) { Integer numl = 10; if(numl == 10) { System.out.println("True"); Example 2 This program will check if the value input is greater than the one stored in the variable. OUTPUT("Enter a number") INPUT Valueinput StoredValue � 100 IF Valueinput > StoredValue THEN OUTPUT("It is more than 100") ENDIF VB.NET Dim valueinput As Integer Console.WriteLine("Enter a number") valueinput = Console.ReadLine Dim storedValue As Integer = 100 If valueinput > storedValue Then Console.WriteLine("It is more than 100") End If Python valueinput = int(input("Enter a number")) storedValue = 100 if valueinput > storedValue: print("It is more than 100") Java public static void main(String args[]) { Integer storedValue = 100; Scanner scanner = new Scanner(System.in); System.out.println("Enter a number"); Integer valueinput = Integer.parseint(scanner. nextLine()); if(valueinput > storedValue) { System.out.println("It is more than 100"); 219 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) ELSE This is added within an IF statement. If the IF statement's condition is false then the ELSE will run. You can only ever have one ELSE in an IF statement. ELSE follows the structure: IF comparison THEN Statements that run if the comparison is true ELSE Statements that run if the comparison is false ENDIF Example 1 In this example if the two values are the same it outputs "That's correct". If they are not the same then the ELSE runs, it will output "Incorrect". Num r 10 OUTPUT("Enter a number") INPUT Guess IF Num = Guess THEN OUTPUT("That's correct") ELSE OUTPUT("Incorrect") ENDIF VB.NET Dim num As Integer = 10 Dim guess As Integer Console.WriteLine("Enter a number") guess = Console.ReadLine If num = guess Then Console.WriteLine("That's correct") Else Console.WriteLine("Incorrect") End If Python num = 10 guess = int(input("Enter a number")) if num == guess: print("That's correct") else: print("Incorrect") Java public static void main(String args[]) { Integer num = 10; Integer guess; Scanner scanner = new Scanner(System.in); 220) 8 Programming System.out.println("Enter a number"); guess = Integer.parseint(scanner.nextLine()); if(num == guess){ System.out.println("That's correct"); }else{ System.out.println("Incorrect"); Example 2 In this example, it will output the smallest number, or one of the numbers if they are both the same. Valuel <- 10 Value2 <- 20 IF Valuel < Value2 THEN OUTPUT(Valuel) ELSE OUTPUT(Value2) ENDIF VB.NET Dim valuel As Integer = 10 Dim value2 As Integer = 20 If valuel < value2 Then Console.WriteLine(valuel) Else Console.WriteLine(value2) End If Python valuel = 10 value2 = 20 if valuel < value2: print(valuel) else: print(value2) Java public static void main(String args[]){ Integer valuel = 10; Integer value2 = 20; if(valuel < value2){ System.out.println(valuel); }else{ System.out.println(value2); 221 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) ELSEIF This allows for a second condition to be used within the same IF statement. If the first condition is False, then a second condition can be checked. ELSEIF follows the structure: IF comparisonl THEN Statements that run if the comparison is true ELSEIF comparison2 THEN Statements that run if comparisonl is false, and comparison2 is true ENDIF Example 1 This will output which number is greater, or nothing will output if they are the same. Numl <- 10 Num2 <- 20 IF Numl < Num2 THEN OUTPUT(Num2) ELSEIF Num2 < Numl THEN OUTPUT(Numl) ENDIF VB.NET Dim numl As Integer = 10 Dim num2 As Integer 20 If numl < num2 Then Console.WriteLine(num2) Elseif num2 < numl Then Console.WriteLine(numl) End If Python numl = 10 num2 = 20 if numl < num2: print(num2) elif num2 < numl: print(numl) Java public static void main(String args[]) { Integer numl = 10; Integer num2 = 20; if(numl < num2) { System.out.println(num2); }else if(num2 < numl) { System.out.println(num2); 222 ) 8 Programming You can use multiple ELSEIF statements, and combine them with a single ELSE statement at the end. This will follow the structure: IF comparison] THEN Statements that run if the comparison is true ELSEIF comparison2 THEN Statements that run if comparisonl is false, and comparison2 is true ... . as many ELSEIFs as you need ELSE Statements that run if none of the comparisons are true ENDIF Example 2 This uses ELSEIF and an ELSE to output the largest number. IF Numl > Num2 THEN OUTPUT(Numl) ELSEIF Num2 > Numl THEN OUTPUT(Num2) ELSE OUTPUT("They are the same") ENDIF VB.NET Dim numl As Integer = 10 20 Dim num2 As Integer If numl > num2 Then Console.WriteLine(numl) Elseif num2 > numl Then Console.WriteLine(num2) Else Console.WriteLine("They are the same") End If Python numl = 10 num2 = 20 if numl > num2: print(numl) elif num2 > numl: print(num2) else: print( "They are the same") Java public static void main(String args[]) { Integer numl 10; Integer num2 = 20; 223 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK if(numl < num2){ System.out.println(num2); }else if(num2 < numl){ System.out.println(num2); }else{ System.out.println("They are the same"); Example 3 This uses multiple ELSEIFs. IF Age < 14 THEN OUTPUT("You are not old enough") ELSEIF Age < 16 THEN OUTPUT("You need an adult present") ELSEIF VB.NET Dim age As Integer Console.WriteLine("Enter your age") age = Console.ReadLine If age < 14 Then Console.WriteLine("You are not old enough") Elseif age < 16 Then Console.WriteLine("You need an adult present") End If Python age = int(input("Enter your age")) if age < 14: print("You are not old enough") elif age < 16: print("You need an adult present") SELECT CASE A SELECT CASE statement allows the program to take one variable or value, and then have lots of different options depending what it is equal to. CASE follows the structure: CASE OF variable valuel: Statements that run if CASE valuel is true value2: Statements that run if CASE valuel is false, and value2 is true OTHERWISE Statements that run if none of the comparisons are true. ENDCASE 224) 8 Programming A case can have as many CASE statements as needed, but can only ever have a maximum of one default (this runs if none of the comparisons are true). Example 1 Using a SELECT CASE to output a grade for an in-lesson test. (No example is given for Python as it does not have a CASE construct and no example is given for Java as it does not support switch statements with comparisons, e.g. < or>.) Score � INPUT("Enter score") CASE OF score: >=80: OUTPUT ("A") >=70: OUTPUT("B") >=60: OUTPUT("C") >=50: OUTPUT("D") OTHERWISE OUTPUT("U") ENDCASE VB.NET Dim score As Integer Console.WriteLine("Enter score") score = Console.ReadLine Select Case score Case >= 80 Console.WriteLine("A") Case >= 70 Console.WriteLine("B") Case >= 60 Console.WriteLine("C") Case >= 50 Console.WriteLine("D") Case Else Console.WriteLine("U") End Select Example 2 Output a message depending on which number is entered. (No example is given for Python as it does not have a CASE construct.) OUTPUT("Enter a number, 1 to 5"} INPUT Choice CASE OF Choice: 1: OUTPUT("Menu option l") 2: OUTPUT("Menu option 2") 3: OUTPUT("Menu option 3") 4: OUTPUT("Menu option 4") 5: OUTPUT("Menu option 5") OTHERWISE OUTPUT("Invalid choice") ENDCASE 225 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) VB.NET Dim choice As Integer Console.WriteLine("Enter a number, 1 to 5") choice = Console.ReadLine Select Case choice Case 1 Console.WriteLine("Menu option 1") Case 2 Console.WriteLine("Menu option 2") Case 3 Console.WriteLine("Menu option 3") Case 4 Console.WriteLine("Menu option 4") Case 5 Console.WriteLine("Menu option 5") Case Else Console.WriteLine("Invalid choice") End Select Java public static void main(String args[)){ Scanner scanner = new Scanner(System.in); System.out.println("Enter a number, 1 to 5"); Integer choice= Integer.parseint(scanner.nextLine()); switch(choice) { case 1: System.out.println("Menu option 1"); break; case 2: System.out.println("Menu option 2"); break; case 3: System.out.println("Menu option 3"); break; case 4: System.out.println("Menu option 4"); break; case 5: System.out.println("Menu option 5"); default: System.out.println("Invalid choice"); ACTIVITY 8.2 What is the difference between IF and CASE statements? Is there a scenario when one is more appropriate than another? Write one example of each where that is the most appropriate type to use. 226) 8 Programming CONTINUED Peer Assessment Explain your choices in Activity 8.2 to a partner. Did they come to the same conclusions as you did? Is there always a correct answer or are the different points of view all valid? Boolean Operators KEYWORDS There are three Boolean operators that you can use to join conditions: the AND operator, the NOT operator and the OR operator. These are described in Table 8.4. Boolean operator Description Example AND If both conditions are true, the result is true. IF 1 = 1 AND 2 = 2 If one or both conditions are false, the result is false. This will return TRUE. The left of the AND is true, and the right of the AND is true. IF 1 = 1 AND 1 > 2 This will return FALSE. The left of AND is true, but the right of AND is false. IF 1 < -2 AND O < -1 OR This will return FALSE. Both comparisons are false, so the result is false. IF 1 = 1 OR 2 = 2 If one, or both, conditions are true, the This will return TRUE. The left of the OR is result is true. true, and the right of the OR is true. If both conditions are IF 1 = 1 OR 1 > 2 false, the result is false. This will return TRUE. The left of OR is true, but the right of OR is false. Boolean operator: a symbol that joins multiple logical comparisons, can be AND' OR or NOT. AND operator: returns True when both inputs are True. NOT operator: returns True if the input is False, and False if it is True. OR operator: returns True when one, or both, inputs are True. IF 1 < -2 OR O < -1 NOT Reverse the condition. If the condition is True it becomes False. This will return FALSE. Both comparisons are false, so the result is false. IF NOT (1 = 1) The brackets equal to TRUE, 1 equals 1. The NOT makes it FALSE, so it becomes 1 does not equal 1. IF NOT (End of File) This is used with file handing. End of File will return TRUE if there is no data left in the file. The NOT turns this to false. So while not at the end of the file. Table 8.4: Boolean operators 227 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ACTIVITY 8.3 Make a list of the use of AND, OR and NOT in real-life situations. For example, if one of two light switches is pressed then a light turns on. If the door is locked and you have the key then you can unlock the door. Peer Assessment Share your list in groups of 3. Discuss each of the statements and whether they have been correctly identified as AND, OR or NOT. Select one of each Boolean operator and share it with the rest of the class. Example 1 This will output the first message if both test marks are greater than or equal to 90. If only one mark is greater than or equal to 90 then the second message will output. OUTPUT("Enter the mark for test 1") INPUT Markl OUTPUT("Enter the mark for test 2") INPUT Mark2 IF Markl >= 90 AND Mark2 >= 90 THEN OUTPUT("Well done you got top marks on both tests") ELSEIF Markl >= 90 OR Mark2 >= 90 THEN OUTPUT("Well done you got top marks on one of the tests") ELSE OUTPUT("You didn't quite get top marks on the tests, try again next time") ENDIF VB.NET Dim markl As Integer Console.WriteLine("Enter the mark for test l") markl = Console.ReadLine Dim mark2 As Integer Console.WriteLine("Enter the mark for test 2") mark2 = Console.ReadLine If markl >= 90 And mark2 >= 90 Then Console.WriteLine("Well done you got top marks on both tests") Elseif markl >= 90 Or mark2 >= 90 Then Console.WriteLine("Well done you got top marks on one test") Else Console.WriteLine("You didn't quite get top marks ont he tests, try again next time") End If Python markl = input("Enter the mark for test l") mark2 = input("Enter the mark for test 2") if markl >= 90 and mark2 >= 90: print("Well done you got top marks on both tests") elif markl >= 90 or mark2 >= 90: print("Well done you got top marks on one of the tests") 228 ) 8 Programming else: print("You didn't quite get top marks on the tests, try again next time") Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the mark for test l"); Integer markl = Integer.parseint(scanner.nextLine()); System.out.println("Enter the mark for test 2"); Integer mark2 = Integer.parseint(scanner.nextLine()); if(markl >= 90 && mark2 >= 90) { System.out.println("Well done you got top marks on both tests"); }else if(markl >= 90 11 mark2 >= 90) { System.out.println("Well done you got top marks on one of the tests"); }else{ System.out.println("You didn't quite get top marks on the tests, try again next time"); Example 2 Output the highest number out of three that are input: OUTPUT("Enter 3 numbers") INPUT Numberl INPUT Number2 INPUT Number3 IF Numberl > Number2 AND Numberl > Number3 THEN OUTPUT(Numberl) ELSEIF Number2 > Number3 THEN OUTPUT(Number2) ELSE OUTPUT(Number3) ENDIF VB.NET Dim numberl As Integer Console.WriteLine("enter a number") numberl = Console.ReadLine() Dim number2 As Integer Console.WriteLine("enter a number") number2 = Console.ReadLine Dim number3 As Integer Console.WriteLine("enter a number") number3 = Console.ReadLine If numberl > number2 And numberl > number3 Then Console.WriteLine(numberl) Elseif number2 > number3 Then Console.WriteLine(number2) Else Console.WriteLine(number3) End If 229) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python numberl = input("Enter a number") number2 = input("Enter a number") number3 = input("Enter a number") if numberl > number2 and numberl > number3: print(numberl) elif number2 > number3: print(number2) else: print(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 iteration: 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). 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 <= 10; x++) { System.out.println(x); Example 2 Output the 12 times table from 1 to 12: FOR Count� 1 TO 12 OUTPUT(Count * 12) NEXT Count VB.NET For count = 1 To 12 Console.WriteLine(count * 12) Next Python for count in range (1, 13): print(count * 12) Java public static void main(String args[]) { for(Integer count = l; count < 13; count++) { System.out.println(count * 12); 232 > 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 <= 10; number++) { total = total + number; You can change the amount that you increase the variable by each time you loop. This is by using STEP. STEP 1 will increase the counter by 1 each time. STEP -1 will decrease the counter by 1 each time. STEP O. 5 will increase the counter by 0.5 each time. Example 1 Output the numbers 10 to 1: FOR Number 10 TO 1 STEP -1 OUTPUT(Number) NEXT Number f- VB.NET For number = 10 To 1 Step -1 Console.WriteLine(number) Next 233 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python for number in range (10, 0, -1): print(str(number)) Java public static void main(String args[]) { for(Integer number = 10; 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 <= 20.0; value += 0.5) { System.out.println(value); Pre-condition A pre-condition loop tests the condition before starting the loop. This means that if the condition is false, the code inside the loop will not run. It loops while the condition is true. It stops looping when the condition is false. A WHILE loop is a pre-condition loop. It has the structure: WHILE condition DO Code that will run when the condition is true ENDWHILE 234) 8 Programming Example 1 Looping while the user enters "Yes". InputValue +- "Yes" WHILE InputValue = "Yes" DO InputValue +- INPUT("Do you want to continue?") ENDWHILE VB.NET Dim inputValue As String = "Yes" While inputValue = "Yes" Console.WriteLine("Do you want to continue?") inputValue = Console.ReadLine End While Python inputValue = "Yes" while inputValue == "Yes": inputValue = input("Do you want to continue?") Java public static void main(String args[]) { String inputValue = "Yes"; Scanner scanner = new Scanner(System.in); while(inputValue.equals("Yes")) { System.out.println("Do you want to continue?"); inputValue = scanner.nextLine(); Example 2 Outputting the numbers 1 to 10: Number +- 1 WHILE Number < 11 DO OUTPUT(Number) Number +- Number + 1 ENDWHILE VB.NET Dim number As Integer = 1 While number < 11 Console.WriteLine(number) number = number + 1 End While 235 ) > 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<- 5 Guessed<- FALSE WHILE Guessed = FALSE DO OUTPUT("Guess the number") INPUT Guess IF Guess = Number THEN Guessed<- TRUE ENDIF ENDWHILE VB.NET Dim number As Integer = 5 Dim guessed As Boolean = False While guessed = False Console.WriteLine("Guess the number") number = Console.ReadLine If guessed = number Then guessed = True End If End While Python number = 5 guessed = False while guessed == False: guess = int(input("Guess the number")) if guess == number: guessed = True 236 > 8 Programming Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); Integer number = 5; Boolean guessed = false; while(guessed == false) { System.out.println("Guess the number"); Integer guess = Integer.parseint(scanner.nextLine()); if(guess == number) { guessed = true; Post-condition loop A post-condition loop runs the code inside the loop once, and then checks the condition at the end of the loop. This means that the code will always run once. A REPEAT UNTIL loop is a post-condition loop. It has the structure: REPEAT Code that runs inside the loop UNTIL Condi tion In this case it continues until the Condition becomes True. It loops while the condition is False. Example 1 Looping until the user enters Yes. (No example is given for Python as it does not have an in-built post-condition loop.) REPEAT OUTPUT("Do you want to stop?") INPUT Answer UNTIL Answer = "Yes" VB.NET Dim answer As String Do Console.WriteLine("Do you want to stop?") answer = Console.ReadLine Loop Until answer = "Yes" Java Java has a do while loop, so it loops while the condition is true, not until it is true. public static void main(String args[]) { Scanner scanner = new Scanner(System.in); String answer = "Yes"; 237 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) do{ System.out.println("Do you want to stop?"); answer = scanner.nextLine(); }while(!answer.equals("Yes")); Example 2 Outputting the numbers 1 to 10. (No example is given for Python as it does not have an in-built post-condition loop.) Number � 1 REPEAT OUTPUT(Number) Number � Number + 1 UNTIL Number > 10 VB.NET Dim number As Integer = 1 Do Console.WriteLine(number) number = number + 1 Loop Until number > 10 Java public static void main(String args[]){ Integer number = l; do{ System.out.println(number); number++; }while(number <= 10); Example 3 Asking the user to enter a number until they guess the correct number. (No example is given for Python as it does not have an in-built post-condition loop.) NumberToGuess � 15 REPEAT OUTPUT("Guess the number") INPUT Guess UNTIL Guess = NumberToGuess VB.NET Dim numberToGuess As Integer = 15 Dim guess As Integer 238) 8 Programming Do Console.WriteLine("Guess the number") guess = Console.ReadLine Loop Until guess = numberToGuess Java public static void main(String args[]){ Scanner scanner = new Scanner(System.in); Integer numberToGuess = 15; Integer guess; do{ System.out.println("Guess the number"); guess = Integer.parseint(scanner.nextLine()); }while(numberToGuess != guess); PROGRAMMING TASK 8.3 A program needs to ask the user to guess what number the game is 'thinking of'. The game should store the number for the user to guess. The user should continually guess until they get the correct answer. Getting started 1 Work in pairs to identify the inputs, processes and outputs required for this system. 2 Discuss which construct(s) will be needed: sequence, selection and/or iteration. 3 In pairs plan the algorithm to perform the required tasks. Practice 1 Write a program for the algorithm you have designed. 2 Change the program so that the program outputs "lower" if their guess is too high, and "higher" if their guess is too low. Challenge 1 Change the program to count how many times the user guesses the number before they get it correct. Output the total when they guess correctly. 2 Change the program to allow a user to enter the number for the player to guess at the start of the program. 239) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK SKILLS FOCUS 8.3 CONVERTING A FOR LOOP TO A WHILE LOOP The three different types of loop (count-controlled, pre-condition and post­ condition) can often be written as a different type of loop. For example, a count­ controlled loop can be written using a pre-condition loop, or a post-condition loop. Pre-condition and post-condition loops can be rewritten as each other. Some pre- and post-condition loops can be written as a count-controlled - but only if their comparisons are for a count, e.g. looping IO times. A computational thinking skill is the ability to take a loop and convert it to other loops. This demonstrates your understanding of how the different loops work and the characteristics of each type of loop. Therefore it is good practice to experiment by converting one loop into a different type. For example, converting a for loop to a while loop. Consider the for loop: FOR X <-- 1 TO 10 OUTPUT(X) NEXT Step 1: Declare the variable used as the counter. In this example the variable is x, the value is 1. Step 2: Take the last value and put it in the while loop condition. In this example loop until it is 10, so the condition is while x < 11. Step 3: Increment the counter in the loop. The counter is x so x needs to have 1 added to it. X = 1 (Step 1) WHILE X < 11 DO (Step 2) OUTPUT(X) X <-- X + 1 (Step 3) ENDWHILE Questions 1 Convert the following FOR loop to a WHILE loop. FOR Count <-- 0 TO 100 OUTPUT(Count + Count) NEXT Step 1: Declare your variable with its starting value. Step 2: Take the last value and put it in the while condition. Step 3: Increment the counter in the loop. 2 Convert the following FOR loop to a WHILE loop. FOR New <-- 100 TO 111 OUTPUT(New New) NEXT A 240) 8 Programming Questions 13 Describe the difference between a pre-condition and post-condition loop. 14 A program needs a loop that will run 50 times. Which type of loop would be most 15 16 17 18 19 appropriate? Write a program to output the numbers 100 to 200. Write a program to output the 5 times table (from 5 times I, to 5 times 12). Write a program to ask the user to enter a number continually, until they enter the number 10, using a post-condition loop. Write a program to output the word "Hello" until the user enters the word "stop", using a pre-condition loop. Convert the following count-controlled loop to a pre-condition loop. FOR Counter <- 1 to 10 OUTPUT(Counter * Counter) NEXT Counter 8.8 Totalling KEYWORD Totalling is adding together a set of values. To write a program to total you need to: totalling: a type of • Initialise the total to 0. • Add the values together (either individually or within a loop). program, it adds up multiple values to find the total. Example 1 Asking the user to enter 10 numbers and totalling them: Total<- 0 FOR Counter<- 0 TO 10 OUTPUT("Enter a number") Total<- Total + INPUT NEXT Counter OUTPUT("The total is " & Total) VB.NET Dim total As Integer = 0 For counter = 0 To 10 Console.WriteLine("Enter a number") total = total + Console.ReadLine Next Console.WriteLine("The total is " & total) Python total = 0 for counter in range(0, 11): total = total + int(input("Enter a number")) print("The total is", total) 241 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); Integer total = 0; for(Integer counter = 0; counter < 11; counter++) { System.out.println("Enter a number"); total = total + Integer.parseint(scanner.nextLine()); } System.out.println("The total is " + total); Example 2 Total the data in an array of 100 elements: Total .- 0 FOR Count<- 0 TO 99 Total .- Total + ArrayData[Count] NEXT Count OUTPUT(Total) VB.NET Dim total As Integer = 0 Dim arrayData(99) As Integer 'insert code to populate array For count = 0 To 99 total = total + arrayData(count) Next Console.WriteLine(total) Python total = 0 arrayData= [] #insert code to populate array for count in range(0, 100): total = total + arrayData[count] print(str(total)) Java public static void main(String args[]) { Integer total = 0; Integer[] arrayData = new Integer[l00]; //insert code to populate array for(Integer count = 0; count < 100; count++) { total = total + arrayData[count]; System.out.println(total); 242 ) 8 8.9 Counting KEYWORD Counting is working out how many of something there are. For example how many numbers were entered that were over 10. To write a program to count you need to: • • Programming Initialise a counter variable to 0. Increment (add one to) the counter each time an item is entered, or found . counting: a type of program, it adds one for every item to find out how many there are. Example 1 Count how many numbers the user enters until they say to stop: Count <---- 0 Continue <---- "Yes" WHILE Continue = "Yes" DO OUTPUT("Do you want to continue?") INPUT Continue Count <---- Count + 1 ENDWHILE OUTPUT("You continued " & Count - 1 & " times") VB.NET Dim count As Integer = 0 Yes 11 Dim continueLoop As String While continueLoop = "Yes" Console.WriteLine("Do you want to continue?") continueLoop = Console.ReadLine count = count + 1 End While Console.WriteLine("You continued " & count-1 & " times") 11 Python count = 0 continueinput = "Yes" while continueinput == "Yes": continueinput = input("Do you want to continue?") count = count + 1 print("You continued", str(count-1), "times") Java public static void main(String args[)) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the first number"); Integer count = O; String continueinput = "Yes"; while(continueinput.equals("Yes")) { System.out.println("Do you want to continue?"); continueinput = scanner.nextLine(); 243) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) count = count + l; count = count - 1; System.out.println("You continued " + count + " times"); Example 2 Count how many numbers in an array of 100 elements are more than 50: Count <-- 0 FOR X <-- 0 TO 99 IF ArrayData[X] > 50 THEN Count<-- Count + 1 ENDIF NEXT X VB.NET Dim arrayData(99) As Integer 'insert code to populate array Dim count As Integer = 0 For X = 0 To 99 If arrayData(X) > 50 Then count = count + 1 End If Next Python count = 0 arrayData= [] #insert code to populate array for x in range(0, 100): if arrayData[x] > 50: count = count + 1 Java public static void main(String args[]) { Integer[] arrayData = new Integer[l00]; //insert code to populate array Integer count = 0; for(Integer x = 0; x < 100; x++) { if(arrayData[x] > 50) { count = count + 1; 244) 8 Programming Questions 20 What are the two required elements for a totalling program. 21 What are the two required elements for a counting program. 22 Write a program to ask the user to input 100 numbers, total the values and output the total. 23 Write a program to ask the user to input numbers. Count how many numbers are less than 100, and how many are more than or equal to 100. Stop when the user enters the number 0. 8.10 String manipulation A string is a piece of text. This could be made up of characters, numbers and/or symbols. There are lots of different string manipulators that you can use; these let you alter strings, find values in strings, etc. The two you need to know are length and substring. Length This command will return the number of characters in a string. It has the structure: LENGTH(string) Example 1 LENGTH( "hi ") would return 2. VB.NET Dim stringLength As Integer stringLength = Len("hi") Python stringLength len("Hi") Java public static void main(String args[]) { Integer stringLength = ("hi") .length(); Example 2 LENGTH( "0123") would return 4. VB.NET Dim stringLength As Integer stringLength = Len("0123") 245 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python stringLength len("0123") Java public static void main(String args[J) { Integer stringLength = ("0123") .length(); Substring This command will return some of the characters in the string. It has the structure: SUBSTRING(string, start character, number of characters). Depending on your language, the first character could be in position O or position 1. Example 1 Using substring: SUBSTRING("Hello", 0, 1) This will start at character 0 and take 1 character. It will return "H". VB.NET (Uses 1 for the first character.) Dim substring As String substring = Mid("Hello", 1, 1) Python (Uses O for the first character.) substring = "Hello" (0:1) print(substring) Java public static void main(String args[)) { String substring = ("Hello") .substring(0,1); System.out.println(substring); Example 2 Using substring: SUBSTRING("Goodbye" , 4 , 3) . This will start at character 4 and take 3 characters. It will return "bye ". 246) 8 Programming VB.NET Dim substring As String substring = Mid("Goodbye", 5, 3) Python substring = "Goodbye" [ 4: 7] Java public static void main(String args[]) { String substring = ("Goodbye").substring(S, 3); Example 3 Output the length of a string that the user inputs: InputString <-- INPUT("Enter a string") StringLength <-- LENGTH(InputString) OUTPUT(InputString & " is " & StringLength & " characters long") VB.NET Dim inputString As String Console.WriteLine("Enter a string") inputString = Console.ReadLine Dim stringlength As Integer stringlength = Len(inputString) Console.WriteLine(inputString & " is " & stringlength & " characters long") Python inputString = input("Enter a string") stringLength = len(inputString) print(inputString, " is ", str(stringLength), " characters long") Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a string"); String inputString = scanner.nextLine(); Integer stringLength = inputString.length(); System.out.println(inputString + " is " + stringLength + " characters long"); 247 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Example 4 Output the first 4 characters in a string: StringData ..... "Goodbye" NewMessage f--- SUBSTRING(StringData, 0, 4) OUTPUT(NewMessage) VB.NET Dim stringData As String = "Goodbye" Dim newMessage As String newMessage = Mid(stringData, 1, 4) Console.WriteLine(newMessage) Python stringData = "Goodbye" newMessage = stringData[0:4) print(newMessage) Java public static void main(String args[)) { String stringData = "Goodbye"; String newMessage = stringData.substring(0,4); System.out.println(newMessage); Example 5 Output each letter of a string one character at a time. Depending on your language, the stopping condition might be the length, or the length -1 depending on whether the first character is O or 1. OUTPUT("Enter a message") INPUT Stringinput FOR Count f--- 0 to LENGTH(Stringinput) - 1 Character ..... SUBSTRING(Stringinput, Count, 1) OUTPUT(Character) NEXT Count VB.NET Dim stringinput As String Console.WriteLine("Enter a message") stringinput = Console.ReadLine Dim character As String For count = 1 To Len(stringinput) character = Mid(stringinput, count, 1) Console.WriteLine(character) Next 248 ) 8 Programming Python stringinput = input("Enter a message") for count in range(0, len(stringinput)): character = stringinput[count:count+l] print(character) Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a message"); String stringinput = scanner.nextLine(); String character; for(Integer count = 0; count < stringinput.length(); count++) { character = stringinput.substring(count, count+l); System.out.println(character); Example 6 Output the last 3 characters in a string: OUTPUT("Enter a message") INPUT Stringinput NewString r SUBSTRING(Stringinput, LENGTH(Stringinput) - 3, 3) OUTPUT(NewString) VB.NET Dim stringinput As String Console.WriteLine("Enter a message") stringinput = Console.ReadLine Dim newString As String newString = Mid(stringinput, Len(stringinput) - 2, 3) Console.WriteLine(newString) Python stringinput = input("Enter a message") newString = stringinput[len(stringinput)-3:] print(newString) Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a message"); String stringinput = scanner.nextLine(); String newString = stringinput.substring(stringinput.length()-3, stringinput. length()); System.out.println(newString); 249 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Upper and lower The characters a z- can be converted into uppercase and the characters A-Z can be converted into lowercase. This can be done to an individual character, or to an entire string at the same time. If a character is already in upper case, trying to convert it to upper case will not change it. UPPER( string) LOWER( string) Example 1 Using UPPER with a string: UPPER("Hello") will return "HELLO" VB.NET Word "Hello".toUpper() Python Word "Hello".upper() Java Word = "Hello".toUpperCase(); Example 2 Using LOWER with a string stored in a variable: Word+- "HELLO" Word+- LOWER(Word) VB.NET word = "HELLO" word = word.toLower() Python word = "HELLO" word = word. lower() Java word = "HELLO"; word = word.toLowerCase(); 250) 8 Programming COMPUTER SCIENCE IN CONTEXT When you need to create a password for a website or computer there are usually rules you have to follow; e.g. more than 8 characters, at least one lowercase letter, at least one uppercase letter, one special character, etc. The length function you have just learnt can be used to work out if the password is long enough. You can also use the substring function by checking each character one at a time to work out if it is a special character (e.g./!?, etc.). You don't need to know about cases for the specification, but you can research how to find out about a character in upper case , or lowercase as well. Put them all together and you can write a program to check if a password is valid. 8.11 Nested statements A nested statement is one or more selection and/or iteration statements inside another selection/iteration statement. This could be an IF statement inside an IF statement or a loop inside an IF statement or an IF statement in a loop or a loop within a loop. You might have already used these without realising they were called nested statements. The position of the start and end of these constructs are important. If, for example, a loop starts inside an IF statement, the loop must also finish inside the same IF statement. KEY WORD nested statement: a construct (selection or iteration) that is inside another construct. Example 1 Count how many numbers entered are more than 10, and how many are equal to 10: MoreThanl0 <---- 0 EqualTol0 <---- 0 FOR X <---- 0 TO 99 OUTPUT ( "Enter a number" ) INPUT Number IF Number > 10 THEN MoreThanl0 <---- MoreThanl0 + 1 ELSEIF Number = 10 THEN EqualTol0 <---- EqualTol0 + 1 ENDIF NEXT X This code has an IF statement nested inside a count-controlled loop. VB.NET Dim moreThanl0 As Integer = 0 Dim equalTol0 As Integer = 0 Dim number As Integer For x = 0 To 99 Console.WriteLine("Enter a number") number = Console.ReadLine If number > 10 Then moreThanl0 = moreThanl0 + 1 Elseif number = 10 Then 251 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) equalTol0 = equalTol0 + 1 End If Next Python moreThanl0 = 0 equalTol0 = 0 for x in range(0, 100): number = int(input("Enter a number")) if number > 10: moreThanl0 = moreThanl0 + 1 elif number = 10: equalTol0 = equalTol0 + 1 Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); Integer moreThanl0 = 0; Integer equalTol0 = 0; for(Integer x = 0; x < 100; x++) { System.out.println("Enter a number"); Integer number = Integer.parseint(scanner.nextLine()); if(number > 10) { moreThanl0 +=1; }else if(number == 10) { equalTol0 +=l; Example 2 Loop counting how many values in an array are more than or equal to 100, and then stop counting: Number � 0 Count� 0 WHILE Number < 10 DO DatainArray� ArrayData[Count] Count� Count + 1 IF DatainArray >= 100 THEN Number� Number + 1 ENDIF ENDWHILE This has an IF statement inside a pre-condition loop. 252) 8 Programming VB.NET Dim number As Integer = 0 Dim count As Integer = 0 Dim dataArray(999) As Integer 'insert code to populate array Dim datainArray As Integer While number < 10 datainArray = dataArray(count) count = count + 1 If datainArray >= 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 <--- 1 OUTPUT(DataParameter) OutputData(Data) 261 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) VB.NET Module Program Sub outputData(dataParameter) Console.WriteLine(dataParameter) End Sub Sub Main(args As String()) Dim data As Integer data = 1 Console.WriteLine(data) outputData(data) End Sub End Module Python def outputData(dataParameter): print(str(dataParameter)) #main data = 1 print(str(data)) outputData(data) Java class outputting{ public static void outputData(Integer dataParameter){ System.out.println(dataParameter); public static void main(String args[]){ Integer data = l; System.out.println(data); outputData(data); Best practice restricts the use of global variables, because their memory is taken for the whole of the program and nothing else can use that memory space. If you declare them locally then when that part of the program finishes the memory location is freed. Local variables are more tricky to program because you need to send them as parameters between functions and make sure you return them back if they have changed. Parameters A parameter is a value that is sent from the main program to the subroutine (procedure or function). Parameters are declared inside the brackets after the subroutines name, e.g. PROCEDURE identifier(parameterl, parameter2 ...) ENDPROCEDURE or 262 ) 8 Programming FUNCTION identifier(parameterl, parameter2 ...) ENDFUNCTION If a subroutine is declared with parameters, then it must be called with the same number of parameters. For example: PROCEDURE Total(Numl, Num2) END PROCEDURE This has two parameters. When the procedure is called it must have 2 numbers sent to it. This could be numbers, e.g. Total(l,2) or variables. e.g. Total(Numberl, Number2) Example 1 A function takes two numbers, divides them and returns the result: FUNCTION Division(First, Second) RETURN First/ Second ENDFUNCTION The main program sends 10 and 2, then outputs the return value. OUTPUT(Division(l0, 2)) VB.NET Sub Main() Console.WriteLine(division(l0, 2)) End Sub Function division(first, second) Return first/ second End Function Python def division(first, second): return first/ second print(str(division(l0,2))) Java public static Double division(Double first, Double second) { return (first/ second); } public static void main(String args[J) { System.out.println(division(l0.0,2.0)); 263 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Example 2 A procedure takes 2 values and outputs all the numbers between the first number to the second: PROCEDURE OutputNumbers(Numl, Num2) FOR Count� Numl TO Num2 OUTPUT Count NEXT Count ENDPROCEDURE The main program taking two values from the user. OUTPUT("Enter the smallest number") INPUT FirstNumber OUTPUT("Enter the largest number") INPUT Second.Number OutputNumbers(FirstNumber, Second.Number) VB.NET Sub Main() Console.WriteLine("Enter the smallest number") Dim firstNumber As Integer = Console.ReadLine Console.WriteLine("Enter the largest number") Dim second.Number As Integer = Console.ReadLine outputNumbers(firstNumber, second.Number) End Sub Sub outputNumbers(numl, num2) For count = numl To num2 Console.WriteLine(count) Next End Sub Python def outputNumbers(numl, num2): for count in range(numl, num2+1): print(str(count)) firstNumber = int(input("Enter the smallest number")) second.Number = int(input("Enter the largest number")) outputNumbers(firstNumber, second.Number) Java public static void outputNumbers(Integer numl, Integer num2) { for(Integer count = numl; count <= num2; count++) { System.out.println(count); 264) 8 Programming public static void main(String args[]) { Scanner scanner= new Scanner(System.in); System.out.println("Enter the smallest number"); Integer firstNumber= Integer.parseint(scanner.nextLine()); System.out.println("Enter the largest number"); Integer secondNumber=Integer.parseint(scanner.nextLine()); outputNumbers(firstNumber, secondNumber); Questions 29 What is the difference between a function and a procedure? 30 Consider the following function: FUNCTION Calculate(Numl, Num2) Numl <--- Numl * 2 Num2 <--- Num2 + Numl RETURN(Numl + Num2) ENDFUNCTION What will the following statement output? OUTPUT(Calculate(l,2)) 31 Write a program statement to call the following function with the parameter 100 and output the return value. FUNCTION FindValue(Number) Number<--- Number+ INPUT RETURN Number ENDFUNCTION 32 Write a procedure to take three numbers as parameters and output the largest. 33 Write a function that takes two strings as parameters. It takes the first 3 characters of each string and combines them, returning the resulting string. 8.13 Library routines A program library is a set of subroutines that are pre-written and that can be called within a program. In some programming languages the operators for MOD and DIV are library functions. In other programming languages they are just operators. For example, 2 MOD 4 is the same as MOD(2, 4). Two other library routines that you need to know are ROUND and RANDOM. ROUND This will take a real number (decimal) and limit how many numbers there are after the decimal point. KEYWORD library routine: a pre-written subroutine that can be called from within a program. 265 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK For example ROUND(10.123, 1) will take the number 10.123 and only leave 1 number after the decimal point, returning 10.1. ROUND( 4. 8 293, 2) will return 4. 8 2. As with functions, the values it returns need to be used. This could be done by outputting the return value, or saving it in a variable, e.g. RoundedValue � ROUND(77.293, 1) VB.NET Dim roundedValue As Single roundedValue = Math.Round(77.293, 1) Python roundedValue round(77.293,1) Java public static void main(String args[]) { double value = Math.round(77.23 * 10.0) / 10.0; RANDOM This will generate a random number between two values that it takes as parameters. For example, RANDOM(1 O, 2 O) will return a number between 10 and 20. ACTIVITY 8.4 Is there such a thing as a random number? Research how computers generate random numbers and work out if there is such a thing as a truly random number. Find out why randomness is important in programming and what the potential consequences are of having a system that does not generate random numbers. RANDOM(1, 4) will return a number between 1 and 4. As with functions, the values it returns and therefore need to be used. This could be by outputting the return value, or saving it in a variable, e.g. randomNumber = RANDOM(l, 100) VB.NET Dim randomNumber As Integer Dim rand As Random = New Random randomNumber = rand.Next(l, 101) 266) 8 Programming Python import random randomNumber = random.randint(l, 100) Java public static void main(String args[]) { Random rand = new Random(); Integer randomNumber = rand.nextint(l000) + l; 8.14 Maintainable programs When you write a program there are several things to take into consideration to make it a maintainable program. This is so that when you come back to it in a week, or a year, you can still understand what all of the code does. It might be you are writing a program that someone else needs to understand, so you need to make it understandable to someone who does not know what the program does. Meaningful identifiers KEYWORD maintainable program: a program that has key features to help it be understood at a later date. Variables, constants, subroutines and arrays all have identifiers (names). If you call a variable X, then there is no indication of what it is storing or what its purpose is. If instead, it is called Total, then you know that it is storing a total. The identifiers for subroutines are usually descriptions of their function. For example, a procedure to output the numbers 1 to 10 could be called Functionl, but then there is no indication of what it does. Instead, it could be called Outpu tl Tol0. Comments A comment is a description of a line of code, or section of code. To write a comment you use a special character or characters, for example, //. This tells the program not to execute the text after this symbol. You do not need to comment every line of code, for example, the statement Count = 0 does not need commenting, it is clear that it is storing O in the variable count. KEYWORD comment: text within a program to describe its function, it is not executed when the program 1s run. Example 1 The function of the FOR loop is written as a comment: FOR Count� 0 TO 9 //Output the first 10 elements in the array OUTPUT(Array[Count]) NEXT Count 267 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) VB.NET For count = 0 To 9 'output the first 10 elements in the array Console.WriteLine(arrayData(count)) Next Python for count in range(0, 10): output the first 10 elements in the array print(arrayData[count]) Java public static void main(String args[]) { Integer[] arrayData = new Integer[l0]; //insert code to populate the array //output the first 10 elements in the array for(Integer count = 0; count < 11; count++) { System.out.println(arrayData[count]) Example 2 OUTPUT("Enter a number") INPUT Numl OUTPUT("Enter a number") INPUT Num2 //find and output the largest number IF Numl > Num2 THEN OUTPUT(Numl) ELSE OUTPUT(Num2) ENDIF VB.NET Dim numl As Integer Dim num2 As Integer Console.WriteLine("Enter a number") numl = Console.ReadLine Console.WriteLine("Enter a number") num2 = Console.ReadLine 'find and output the largest number If numl > num2 Then Console.WriteLine(numl) Else Console.WriteLine(num2) End If 268 ) 8 Programming Python numl = int( input("Enter a number")) num2 = int(input("Enter a number")) # find and output the largest number if numl > num2: print(str(numl)) else: print(str(num2)) Java public static void main(String args[]){ 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()); if(numl > 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] VB.NET value = 10 + numbers(2) 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 1 2 3 4 0 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] <--- 10 VB.NET data(4,3) 10 Python numbers = [[OJ * 5 for i in range(S)] numbers[4] [3] = 10 Java public static void main(String args[]) { Integer[][] data = new Integer[l0J [10]; data[4J [3 J = 10; Getting data out of an array You need to know both indices to access the data. Example 1 Output the data in the array ArrayData, element 5 across and 1 down: OUTPUT(ArrayData[4, 1]) VB.NET Console.WriteLine(arrayData(4,1)) Python arrayData = [[OJ * 5 for i in range(S)J print(str(arrayData[4][1])) Java public static void main(String args[]) { Integer[][] arrayData = new Integer[S][5]; //insert data to populate array System.out.println(arrayData[4] [1]); 278 ) 8 Programming Example 2 Access the data in the array colours, in the first element across and the third down: ColourAccessed� Colours[0, 2] VB.NET colourAccessed colours(0,2) Python colours = [ [ ' ' ] * 5 for i in range(5)] colourAccessed = colours[0][2] Java public static void main(String args[]) { String[][] colours = new String[l0][5]; String colourAccessed = colours[0][2]; Using variables as indices Each index can be stored in a variable in the same way as they can be in a 1 D array. Example 1 Output the data in element 4, 3: First� 4 Second� 3 OUTPUT(ArrayData[First, Second]) VB.NET Dim arrayData(9, 9) As String 'insert code to populate array Dim first As Integer = 4 Dim second As Integer = 3 Console.WriteLine(arrayData(first, second)) Python arrayData [ [ ' ' ] * 5 for i in range(5)] first = 4 second = 3 print(arrayData[first] [second]) 279) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > Java public static void main(String args[]) { String[][] arrayData = new String[l0] [10]; //insert code to populate array Integer first = 4; Integer second = 3; System.out.println(arrayData[first][second]); Example 2 Ask the user which element to store in data: OUTPUT("Enter dimension 1") INPUT Indexl OUTPUT("Enter dimension 2") INPUT Index2 Data� Array[Indexl, Index2] VB.NET Dim arrayData(9, 9) As String 'insert code to populate array Dim first As Integer Console.WriteLine("Enter dimension 1") first = Console.ReadLine Dim second As Integer Console.WriteLine("Enter dimension 2") second = Console.ReadLine Dim data As Integer data = arrayData(indexl, index2) Python arrayData = [[''] * 10 for i in range(l0)] #insert code to populate array indexl = int(input("Enter dimension 1")) index2 = int(input("Enter dimension 2")) data = arrayData[indexl] [index2] Java public static void main(String args[]) { Scanner scanner = new Scanner(System.in); String[][] arrayData = new String[l0][10]; //insert code to populate array Integer indexl = Integer.parseint(scanner.nextLine()); Integer index2 = Integer.parseint(scanner.nextLine()); String data = arrayData[indexl][index2]; 280) 8 Programming Using iteration to read and write Due to the two dimensions, you need two nested loops to read through all the data elements. If you think about the table again, one loop goes through the columns and one loop goes through the rows. The first loop will check row 1. The column will change from 0, 1, 2, 3, 4. The row will stay the same at 0. 0 0 10 2 7 Index 3 1 1 5 15 10 2 90 74 85 3 4 26 62 4 87 5 24 The first loop will check row 2. The column will change from 0, 1, 2, 3, 4. The row will stay the same at 1. Index 0 1 2 0 10 3 7 1 5 15 10 2 90 74 85 3 26 62 4 4 87 5 24 It is best to use count controlled loops to go through the array. It has the structure: FOR row� first index to last index FOR column� first index to last index Code to run NEXT row NEXT count Example 1 DataArray has 10 elements by 3 elements. Output all of the elements in the array: FOR Row� 0 TO 2 FOR Column� 0 TO 9 OUTPUT(DataArray[Column, Row]) NEXT Row NEXT Count VB.NET Dim dataArray(2, 9) As Integer 'insert code to populate array For row = 0 To 2 For column = 0 To 9 Console.WriteLine(dataArray(row, column)) Next Next 281 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python arrayData = [[''] * 2 for i in range(l0)] #insert code to populate array for row in range(0, 3): for column in range(0, 10): print(arrayData[row] [column] Java public static void main(String args[]) { Integer[][] dataArray = new Integer[3][10]; //insert code to populate array for(Integer row = 0; row < 3; row++) { for(Integer column = 0; column < 10; column++) { System.out.println(dataArray[row][column]); Example 2 Search a 2-dimensional array, with 50 elements by 100 elements, for the value input by the user: OUTPUT("Enter a number to search for") INPUT SearchValue FOR Row� 0 TO 49 FOR Column� 0 TO 99 IF DataArray[Row, Column] = SearchValue THEN OUTPUT("Found it at " & Column & " " & Row) ENDIF NEXT Column NEXT Row VB.NET Dim dataArray(S0, 100) As Integer 'insert code to populate array Dim searchValue as Integer Console.WriteLine("Enter a number to search for") searchValue = Console.ReadLine() for (row = 0 to 50) for(column = 0 to 100) if(dataArray(row, column) =searchValue) then Console.WriteLine("Found it at " & column & " " & row) endif next next 282) 8 Programming Python arrayData = [[OJ * 50 for i in range(l00)) #insert code to populate array searchValue = int(input("Enter a number to search for")) for row in range(0, 50): for column in range(0, 100): if arrayData[column)[row) = searchValue: str(row)) print("Found it at", str(column), Java public static void main(String args[)) { Integer[)[) dataArray = new Integer[50) (100); Scanner scanner = new Scanner(System.in); Integer searchValue = Integer.parseint(scanner.nextLine()); for(Integer row = 0; row < 50; row++) { for(Integer column = 0; column < 100; column++) { if(dataArray[row) [column) == searchValue) { System.out.println("Found it at " + column + " " + row); Example 3 Find and output the total of all elements in the each of the first dimensions, in an array of 10 elements by 15 elements: FOR Row <- 0 TO 9 Total <- 0 FOR Column <- 0 TO 14 Total <- Total + TheArray[Row, Column) NEXT Column OUTPUT("Index " & Row & " has the total " & Total) NEXT Row VB.NET Dim theArray(9, 14) As Integer 'insert code to populate array Dim total As Integer = 0 For row = 0 To 9 total = 0 For column = 0 To 14 total = total + theArray(row, column) Next Console.WriteLine("Index " & row & " has the total " & total) Next 283 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Python theArray = [[OJ * 10 for i in range(15)] #insert code to populate array total = O for row in range(O, 10): for column in range(O, 15): total = total + theArray[row] [column] print("Index",row,"has the total",total) Java public static void main(String args[]) { Integer[][] theArray = new Integer[lO] [15]; //insert code to populate array Integer total = O; for(Integer row = O; row < 10; row++) { for(Integer column = O; column < 15; column++) { total = total + theArray[row][column]; System.out.println("Index " + row + " has the total " + total); PROGRAMMING TASK 8.4 The 2-player game of noughts and crosses has a grid of 3 squares by 3 squares (Figure 8.4). Figure 8.4: A noughts and crosses grid One player is noughts, the other is crosses. Each player takes it in turn to select a box to place their nought or cross. They cannot select a box that has already been chosen. The first player to get three of their symbols in a row (horizontally, vertically or diagonally) wins. If the board is full and no-one has won then it is a draw. 284) 8 Programming CONTINUED Getting started 1 Decompose the problem into its inputs, processes and outputs. 2 Work in pairs to discuss how you will alternate between the players. 3 Work in pairs to discuss how you will check if a player has won. Practice 1 Write the program to ask each player to make one move. Check that they have not selected the same box, if they have, ask them to select another box. 2 Write an algorithm to check if a player has won and either output who has won, or continue playing. Challenge 1 Write a function for your algorithm to check if a player has won or not. This should check all possible ways of winning and return either: X (crosses has won), 0 (noughts has won) or C (continue play as no-one has won). Your main program will need to decide whether to end, or continue based on the value returned. 2 Edit your program to allow the user to play multiple games. The player should alternate allowing noughts to go first, and then crosses to go first. 3 Edit your program to allow the user to select how many games they should play. Keep track of how many games each player has won and output who won overall. Questions 38 Explain the difference between a variable and an array. 39 Explain why the following code will result in an error. MyData[O] MyData[l] MyData[2] MyData[3] � 1 � 4 � "7" � "9" 40 Write a program to read 10 numbers from the user into a 1-dimensional array named MyNumbers. 41 Write a program to add together all 100 elements in a 1-dimensional array named MyNumbers. 42 A 2-dimensional array, MyData, has 20 elements by 5 elements. Write a function that takes a parameter search value. The function should search MyData and return either TRUE if the parameters is in MyData, or FALSE if the parameters is not in MyData. 285 ) > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK 8.16 File handling If you have data in a program, when you stop or close a program all of that data is lost. If you need to save data to use again later then you need to save it externally into a text file. The storage and access of data in a file is called file handling. COMPUTER SCIENCE IN CONTEXT When playing computer games, for example, on an X-Box or PlayStation, you are able to save the game and then continue from the same point next time. It does this by saving data about your current progress in a file. When your program saves, this data is updated; it might store your current position, health, points, money, etc. When you restart the program, it goes to this file and loads the data. This lets you start playing at the exact point you left it. Reading from a file You need to be able to read a single item of data, or a single line of text. This means all of the data will be on the first line in the text file, so you do not need to check how many lines of text are in the file. Once you have read in the data you can then manipulate it, for example, if it is a line of text you can split it into individual words, or use it as one item of data. To read a value from a file you need to: • Open the file using its filename (the filename will be a string value). • Read the data value, and do something with it (e.g. output it, store it in a variable). • Close the file. You can use the pseudocode commands: OPEN filename variable identifier� READ(filename) CLOSE filename Example 1 Reading and outputting a word stored in the text file data.txt: OPEN "data.txt" OUTPUT(READ("data.txt")) CLOSE "data.txt" VB.NET Dim theFile As New System.IO.StreamReader("data.txt") Console.WriteLine(theFile.ReadLine()) theFile.Close() 286) KEYWORD file handling: programming statements that allow text files to be opened, read from, written to and closed. 8 Programming Python theFile = open("data.txt", print(theFile.read()) theFile.close() 'r') Java public static void main(String args[]){ try{ FileReader f = new FileReader("data.txt"); BufferedReader reader = new BufferedReader(f); System.out.println(reader.readLine()); reader.close(); }catch(Exception e) { System.err.println("No file"); Example 2 Read and output the number stored in the file myNumber.txt by storing the filename in a variable: Filename <- "myNumber.txt" OPEN Filename TheFileData <- READ(Filename) CLOSE(Filename) OUTPUT(TheFileData) VB.NET Dim filename As String = "myNumber.txt" Dim theFileData As String Dim theFile As New System.IO.StreamReader(filename) theFileData = theFile.ReadLine() theFile.Close() Console.WriteLine(theFileData) Python filename = "myNumber.txt" theFile = open(filename, 'r') theFileData = theFile.read() theFile.close() print(theFileData) 287 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Java public static void main(String args[]){ String filename = "myNumber.txt"; String theFileData; try{ FileReader f = new FileReader(filename); BufferedReader reader = new BufferedReader(f); theFileData = reader.readLine(); reader.close(); }catch(Exception e){ System.err.println("No file"); Writing to a file The specification states that you will only need to write a single item of data or a line of text. This means you will be overwriting any data that is already in the file, you do not need to worry about appending (to add onto the end) to data that already exists, or writing multiple values to the same file. To write a value to a file you need to: • • • Open the file using its filename (the filename will be a string value). Write the data to the file. Close the file. You can use the pseudocode commands: OPEN filename WRITE data CLOSE filename Example 1 Write the word "red" to the file colour.txt: OPEN "colour.txt" WRITE "red" CLOSE "colour.txt" VB.NET Dim fileWrite As New System.IO.StreamWriter("colour.txt") fileWrite.WriteLine("red") fileWrite.Close() Python fileData = open("colour.txt", 'w') fileData.writelines("red") fileData.close() 288) 8 Programming Java public static void main(String args[]){ try{ FileWriter f = new FileWriter("colour.txt"); BufferedWriter out = new BufferedWriter(f); out.write("red"); out.close(); }catch(Exception e){ System.err.println("No file"); Example 2 Write the number 100 to the file myData.txt storing the filename in a variable: Filename <- "myData.txt" OPEN Filename WRITE 100 CLOSE Filename VB.NET Dim filename As String = "myData.txt" Dim fileWrite As New System.IO.StreamWriter(filename) fileWrite.WriteLine(l00) fileWrite.Close() Python filename = "myData.txt" fileData = open(filename, 'w') fileData.writelines(l00) fileData.close() Java public static void main(String args[J){ try{ String filename = "myData.txt"; FileWriter f = new FileWriter(filename); BufferedWriter out = new BufferedWriter(f); out.write(l00); out.close(); }catch(Exception e){ System.err.println("No file"); 289) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) PROGRAMMING TASK 8.5 A maths quiz game needs to keep a record of the highest number of points players has gained. The maths quiz is made of randomly generated questions; the mathematical operation and the numbers are all randomly generated. The user keeps on being given new questions until they get one wrong. The points equate to the number of questions they got correct. Getting started 1 2 3 In pairs discuss how the program can randomly generate the numbers within reasonable bounds, e.g. between 1 and 20. In pairs discuss how the program can randomly generate the symbol limited to+ - /*A_ In pairs discuss how the highest score can be stored in a file. Discuss when the file will be read from, and when it will be written to. Practice 1 2 3 Write the program to randomly generate one maths question (random numbers and symbol). Output the question and ask the user for the answer. Check if it is correct and output an appropriate response. Amend your program to repeatedly ask the user questions until they get one incorrect. Keep track of how many questions they get correct. Amend your program so when the user gets a question incorrect, the current high score is loaded from a text file. Replace the high score if the user has more points. Challenge 1 Text files can be read one line at a time. Find out how to store more than one high score (e.g. a top-ten) in a file, and rearrange the high-score table when a user gains a score worthy of including. REFLECTION Consider the program you made for Programming Task 8.5. How did you decide which stage(s) to complete and when to stop? How did you find example code that you needed? Was this an efficient method of finding the required statements? How did you test your program during development? Did you test the program after each line of code, or did you write a section? Did this method work for the program? Would you do it the same way in the future? How did you test your program once it was complete? Did you set out a structured test plan with different types of data? Did you ask other people to help you test it? Was your chosen method appropriate for the program, or did you have to change it during the testing process? 290) There are five options so a number could represent each I symbol. _J 8 Programming Questions 43 44 45 46 Why do some programs need to store data in files? What are the three stages that need to be followed to write data to a file? Write a program to read in a value from the file dataStore. txt and output it. Write a program to ask the user to input a filename, then store the word "house" in the file. SUMMARY A variable is a space in memory, with an identifier, that can store a data item that can change while the program is running. A constant is a space in memory, with an identifier, that can store a data item that cannot change while the program is running. Integer data type stores whole numbers. Real data type stores decimal numbers. Char data type stores a single character. String data type stores a series of characters. Boolean data type stores True or False. Input allows the user to enter data into a system. Output allows the program to display data to the user. There are three constructs in programming; sequence, selection and iteration. There are two types of selection; IF and CASE. IF statements can include ELSEIF and ELSE. There are three types of iteration; count-controlled loops (a set number of iterations), pre-condition loops (condition is tested before starting the loop) and post-condition loops (condition is tested after completing the code in the loop). Totalling requires initialising the total to 0, then adding the values to it. Counting requires initialising the count to 0, then adding 1 to it. Nested statements are when selection/iteration are within a selection/iteration construct. Subroutines are self-contained code, with an identifier that can be called from elsewhere in the program. Subroutines reduce repeated code. Subroutines can be procedures (that do not return a value) or functions (that return a value). A parameter is a value sent to a subroutine. Library routines contain pre-written and pre-tested subroutines that can be used in a program. A maintainable program includes meaningful identifiers, addition of comments and subroutines. An array allows a set of data, of the same data type, to be stored under one identified. Each element in an array has an index. This might start at O or 1 depending on your language. 291 ) ) CAMBRIDGE IGCSE ™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED An array can be I-dimensional (one index) or 2-dimensional (two indices). Iteration can be used to read data to, or from an array, by visiting each index in turn. Files can be used to store data once a program has finished running. EXAM-STYLE QUESTIONS COMMAND WORD 1 Programs can use variables and constants. a State two similarities between a variable and a constant. [2] [1l Total: 3] [ b State the difference between a variable and a constant. state: express in clear terms. 2 Write a program to take two values as input and output first the result when they are added together, and then the result when they are multiplied together. 3 The following is a pseudocode algorithm. [4] INPUT Quantity Smallest<-- 999 Largest<-- 0 Counter <-- 0 WHILE Counter < Quantity DO INPUT Value Total<-- Total + Value IF (Value > Largest) THEN Largest<-- Value ENDIF IF (Value < Smallest) THEN Smallest<-- Value ENDIF Counter<-- Counter + 1 ENDWHILE OUTPUT("The average is " & Total/ Quantity) OUTPUT("The smallest is " & Smallest & " and the largest is " & Largest) a b c d Identify the type of iteration used in the algorithm. State the purpose of the variable counter . Give the name of three other variables in the program. Re-write the loop using a FOR loop. 4 Write a program to ask the user to enter 20 numbers. Store each number in an array. 292) COMMAND WORDS [1] [1l [3] [5] [Total: 10] [3] identify: name / select I recognise. give: produce an answer from a given source or recall / memory. 8 Programming CONTINUED 5 Tick one box in each row to identify whether each if statement would result in True, False or is an invalid condition. Statement if(l0 < 20) if(l00 > < 2) if(S >= 5) if(9 <= 8) X <- 1 y <- 3 if(x = y) numl <- 100 num2 <- 200 if(numl and num2) valuel <- 70 value2 <- 190 if(valuel <> value2) True False Invalid [7] 6 The 2-dimensional integer array, numbers , has 10 elements by 20 elements. Write an algorithm to initialise all of the elements to a random integer value between I and 100. [4] 7 A program stores the x and y coordinates of a character in a game. The function move () takes an x coordinate as a parameter. It asks the user to enter a movement (left or right) and changes the coordinate: • Right increases the coordinate by 1. • Left decreases the coordinate by 1. The function then returns the result. a State why move () is a function and not a procedure. b The function move loops until the user enters either right or left. Write the function move () . 8 Complete the table by stating how each of the features helps the (1] [7] Total: 8] [ maintainability of a program. Feature How it aids maintainability Comments Meaningful identifiers 9 A procedure twelve () reads an integer number from the text file number. txt (e.g. 5). It then outputs the 12 times table for that number (e.g. 5 x 1, 5 x 2 etc.). Write the procedure twelve () . [2] [6] 293 ) ) 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 use variables and constants. 8.1 learn about the appropriate use of basic data types. 8.2 write programs that use input and output. 8.3 8.4 write programs that use sequence, selection and iteration including nested statements. 8.5 8.6 8.7 write programs that use arithmetic, logical and Boolean operators. 8.4 8.4 write programs that use totalling and counting. 8.8 8.9 write programs that perform the string handling methods. 8.10 write programs that use purpose of procedures and functions, including parameters and variable scope. 8.11 write programs using library routines. 8.13 create maintainable programs. 8.14 understand the use of arrays (I-dimensional and 2-dimensional) as data structures. 8.15 write programs to read data from and write data to a file. 8.16 8.12 Needs more work Getting there Confident to move on learn about the structure and components of a single-table database • identify the fields necessary for a single-table database • understand the type of data each of the basic data types represent • identify appropriate data types for specific data and fields • describe the purpose and/or need for a primary key in a table • identify an appropriate primary key for a table • understand the purpose of SOL scripts • read and complete SOL scripts that use SELECT FROM • read and complete SOL scripts that use SELECT FROM WHERE • read and complete SOL scripts that use ORDER BY • read and complete SOL scripts that use SUM • read and complete SOL scripts that use COUNT. CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > GETTING STARTED Your school will have a database of information about you. Find out some of the information the school stores, this could be by talking to your teacher, or other members of staff at the school. Make sure you consider privacy of data. You can find out the type of information collected, e.g. date of birth, but you cannot collect actual data about specific people or items. Work in pairs to identify why each item of data is stored by the school. Take it in turns to share your reasons with the rest of the class. A WORLD OF DATABASES Almost all organisations, companies, businesses, etc. have to store data. This could be data about the people who work for them, the items they sell, their customers. Almost everything that they need to store is in databases. Consider a software development company. They have employees who write the program, and then they sell the programs to the public. What will they need to store in a database? • Information about their employees, e.g. their name and address, the amount they get paid, their bank account details. • Information about the programs they are developing, e.g. the names, people working on them, the type of program they are, the release data. • Information about their customers and their orders, e.g. which customer has ordered which program, how much they paid. The company can then use this database to find information out. They could find out the contact details of all their customers to send them details about new programs. They could find out which employees need to be paid overtime. Websites also usually have databases, especially if you c_an log into them, or buy products from them. The website is the front-end, the user interface. When you enter information into the web page, your web browser sends this across the internet to a web server. This web server has a database. It searches the database for the information it needs, then sends it back to your web browser with the HTML code to create the website. Data is valuable. Companies buy data from other companies so that they can use it for themselves. If you have the names and email addresses of all the people who have bought an item from a clothing company, then you can send them information about your clothing company, possibly even a voucher for 20% off. Then you might gain new customers. 296 > Figure 9.1: A filing cabinet can hold paper databases 9 Databases CONTINUED Data can also be stolen. This is an additional threat if the data is stored online, e.g. on a web server. This is because external people can access the web server and access the data on it. This could include personal information such as your bank details. This is why it is important that the web servers have security such as firewalls to attempt to stop this unauthorised access. You can learn more about online security in Chapter 5. Discussion questions 1 Consider a social media website. What information will they store about their users? What could happen if someone gains unauthorised access to this data? 2 How important is it that a company keeps their data secure? What are the potential consequences of someone gaining unauthorised access to personal data? 9 .1 Database structure Introduction to databases KEYWORDS A database is a collection of data that is set up in a structured way. This is usually on a computer, but you could have a paper-based database as long as it is suitably structured. database: an example of application software to store and manipulate data. A database holds data about objects, for example, a person, an item in a shop, an order someone has made, etc. Each of these objects is stored in a table. Each table is then made up of fields, a field is an individual piece of data being stored about an object. For a person you could have a field for first name, a field for email address, for phone number, etc. table: a set of data A collection of these fields about one object is called a record. For example, all the information about the person Aarna Singh will be one record. field: an individual Most databases have many tables and these are all joined together so that the data is linked. This is outside the scope of the specification. You only need to look at single table databases. Here's an example database about books in a library. The table is called books. Book name Author Publisher Genre Fiction Picking 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 about one type of object, e.g. students. piece of data, e.g. date of birth. record: all of the records in a table about one object, e.g. all the personal details about one student. This database has five fields; Book name, Author, Publisher, Genre and Fiction. This database as four records: One for Picking daisies, one for Night starts, one for Dreaming of the sun and one for Cooking for Fun. 297 > 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 (,). - a new line, Picking Each record is on 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 < Less than. WHERE Cost< 3.99 <= Less than or equal to. WHERE Cost< = 10 > Greater than. WHERE Quantity> 0 >= Greater than and equal to. WHERE Quantity> = 100 <> Not equal to. WHERE Cost<>4.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 <= 6.00 This query returns: 3.99 2 6.00 Greater than SELECT FirstName, LastName FROM Orders WHERE Numberitems > 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 .......................................... <= .......................................... More than one condition Combining conditions requires a Boolean operator between the conditions. These are similar to those that you used in programming (Table 9.3). KEYWORD Boolean operator: a symbol that joins multiple logical comparisons, can be AND OR or NOT. 307 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) Operator Description AND Example WHERE WHERE Fiction = TRUE AND Cost< 3.99. Only data that meets both conditions will be returned. Only records where Fiction is TRUE and Cost is less than 3.99 will be displayed. Data that meets WHERE Fiction = TRUE OR Cost< 3.99. one condition, or both Any records where Fiction is TRUE will be returned. conditions will Any records where Cost< 3.99 will be returned. be returned. OR If a record meets both then this will be returned only once. Table 9.3: Boolean operators Multiple conditions have the format: SELECT field FROM table WHERE conditionl logical operator condition2 The following queries will use the following table, Orders: Order ID FirstName LastName Numberltems TotalCost 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 AND SELECT Order ID, Numberitems, Posted FROM Orders WHERE Numberitems > 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 Silver 29 59.65 No 1D Jenny 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 Numberltems TotalCost 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 21 James Smith 20 156.90 22 Ajay Gupta 1 10.00 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 [2] 320 > meaning. describe: state the [4] 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. define: give precise [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 6 Customer ID Quantity bought Total Cost 3/3/2020 1GHF2 1 6.99 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 P0OO1 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 34FDD 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 <= 15 [2] 322 ) COMMAND WORD 9 Databases CONTINUED e Complete the following SQL script to calculate the total number of books sold on 4/4/2020. SELECT ........................... (Quantity bought) ........................... SALES WHERE .......................... . [4] f Complete the following SQL script to calculate the total cost of all the orders. SELECT ........................... (Total Cost) [3] [Total: 20] 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 learn about the structure and components of a single-table database. 9.1 identify the fields necessary for a single-table database. 9.1 identify appropriate data types for specific data and fields. 9.1 identify an appropriate primary key for a table. 9.1 understand the purpose of SQL scripts. 9.2 read and complete SQL scripts that use SELECT FROM 9.3 read and complete SQL scripts that use SELECT FROM WHERE. 9.4 read and complete SQL scripts that use ORDER BY. 9.5 read and complete SQL scripts that use SUM. 9.6 read and complete SQL scripts that use COUNT. 9.7 Needs more work Getting there Confident to move on 323 > • 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<=? 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<= 80% Temperature> 35 °C Temperature<= 35 °C Humidity>= 65% Humidity< 65% The system will sound an alarm (X) when certain conditions are detected. The alarm will sound when: The moisture level<= 80% and the humidity< 65% or The temperature> 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 <--- INPUT "Enter a number" UNTIL Numberl.isinteger() REPEAT Operator<--- INPUT "Enter an operator" UNTIL Operator "+" OR Operator = " " OR Operator OR Operator "*" OR Operator 11 A 11 REPEAT Number2 <--- INPUT "Enter a number" UNTIL Number2.isinteger() NB the statement . is Integer is not language specific, but as a pseudocode statement it shows that you are looking to check if the value is an integer and only allow the input if it is. You might have one for the language you choose, but it is better to use this than a statement such as: until the number is an integer. Processes Revisit your design table and take the processes one at a time and work out whether they need sequence, selection and/or iteration. Example - calculator: Process Construct 1 If+ is entered add the values. selection 2 If - is entered subtract the values. selection 3 If* is entered multiply the values. selection 4 If/ is entered divide the values. 5 selection If A is entered work out the power of. selection Process 1. If + is entered add the values. IF Operator = "+" THEN Result<--- Numberl + Number2 358) II / 11 Programming scenarios practic 11 e ELSEIF Operator = "-" THEN Result� Numberl - Number2 ELSEIF Operator = "*" THEN Result� Numberl * Number2 ELSEIF Operator = "/" THEN Result� Numberl / Number2 ELSE Result� Numberl Number2 ENDIF A Outputs Once you have written your processes, work out where your outputs should be. Make sure you output using an appropriate message, for example, what the value is showing. Example - calculator: Input Process Output First integer value. If+ is entered add the values. Result from the calculation. Operator. If - is entered subtract the values. Second integer operator. If* is entered multiply the values. If/ is entered divide the values. if A is entered work out the power of. The output is: OUTPUT "The result is: " , Result or OUTPUT Numberl , Operator , Number2 , " " , Result Example - calculator, full code: REPEAT Numberl � INPUT "Enter a number" UNTIL Numberl.isinteger() REPEAT Operator� INPUT "Enter an operator" UNTIL Operator "+" OR Operator " " OR Operator OR Operator = "/" OR Operator = nAn REPEAT Numberl� INPUT "Enter a number" UNTIL Numberl.isinteger() IF Operator = "+" THEN Result� Numberl + Number2 rr * 11 When outputting data, it is good practice to include a message to say what the output is. This is the same in a small pseudocode problem as in a large program being created by many people. If you run a program and it outputs a number without a message how do you know what that number means? 359) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ELSEIF Operator = "-" THEN Result� Numberl - Number2 ELSEIF Operator = "*" THEN Result� Numberl * Number2 ELSEIF Operator = "/" THEN Result� Numberl / Number2 ELSE Result� Numberl A Number2 ENDIF OUTPUT "The result is: " Result Adding comments You should always add comments to your code to explain what you have done. Comments are statements in your program that will not be run. A comment will always start with a specific symbol to state that this is where the comment starts, for example, */,#or// . Comments are used to explain sections of code, not every single statement. Example - calculator: // input 2 numbers and operator REPEAT Numberl� INPUT "Enter a number" UNTIL Numberl.Isinteger() REPEAT Operator� INPUT "Enter an operator" UNTIL Operator = "+" OR Operator = " " OR Operator OR Operator = nAn REPEAT Numberl� INPUT "Enter a number" UNTIL Numberl.Isinteger() //check operator and perform calculation IF Operator = "+" THEN Result� Numberl + Number2 ELSEIF Operator = "-" THEN Result� Numberl - Number2 ELSEIF Operator = "*" THEN Result� Numberl * Number2 ELSEIF Operator = "/" THEN Result� Numberl / Number2 ELSE Result� Numberl A Number2 360) "*" OR Operator .. I II 11 ENDIF //output the result OUTPUT "The result is: Programming scenarios practice Result Final checks Once you have finished your algorithm perform the following checks: 1 2 3 4 5 6 7 8 Have you stored all of your inputs in variables? Have you validated inputs where possible? Have you performed all of the processes? Have you outputted the required values? Have you included appropriate messages in your outputs? Have you added comments? Do all your variables have appropriate identifiers? Return to the scenario and tick every statement that your program performs. If you don't tick a statement then you need to add that to your program. ACTIVITY 11.3 Read the calculator pseudocode solution above and complete the final checks on the algorithm. Tick each on in turn to make sure it has been covered in the solution. SKILLS FOCUS 11.1 TACKLING A PROBLEM When you are given a problem to write a computer program for, you need to know how to approach it to create a solution. In this Skills Focus you will be walked through the production of a solution by analysing the problem, identifying the components and writing a solution that covers all of the requirements. You can then apply the same methodology to other problems to write a computer program to solve the problem. A computer game asks the user to enter a 5-letter word and then stores each letter in a different index in the array, for example: I I 'house' is input: Index 0 Letter• h A second user then has 10 guesses to try and work out what the word is. They have to enter one letter at a time, and the program either outputs the position that letter is in (e.g. 'h' is in 0), or that the letter is not in the word. After guessing a letter the user gets a free guess at the word. If they get it correct they win and the program ends. If the player has entered 10 letters and not guessed correctly then they lose. Write a program using pseudocode or program code for the computer game. 361 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED Identify key features Write down the inputs, processes and outputs for this system. Inputs Processes Outputs Word to guess. Store each letter in different index. Letter position if it is array. User's letter guess. User's word guess. Is user's guess letter in array? Is user's word guess correct? 'Not in array', if not in array. 'Correct', if they guess correctly. They lose if 10 guesses and incorrect guess. Count number of times the user has guessed. Repeat and stop when 10 letters or word is correct. Write the inputs WordToGuess <--- INPUT "Enter a 5 character word" UserLetter <--- INPUT "Enter a letter to guess" UserWord <--- INPUT "Enter a word to guess" Validation The word that is input needs to be 5 characters long so that can be validated. The character entered can be validated as to whether it is a character; there is no specific way to do this but you could use a function such as IsCharacter(). Validating the word is not as straightforward because most things could be accepted. REPEAT WordToGuess <--- INPUT "Enter a 5 character word" UNTIL LENGTH(WordToGuess) = 5 REPEAT UserLetter <--- INPUT "Enter a letter to guess" UNTIL UserLetter.IsCharacter() = TRUE UserWord <--- INPUT "Enter a word to guess" Processes Take these one at a time. First: Store each letter in a different index in an array. To split the string you can use either a function in your language, or a pseudocode function such as substring. //INPUT word to guess REPEAT WordToGuess <--- INPUT "Enter a 5 character word" 362 ) 11 Programming scenarios practi ce CONTINUED UNTIL LENGTH(WordToGuess) = 5 //store characters in array LetterArray � SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 1), SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess, 3, 1)] //INPUT user's guesses REPEAT UserLetter � INPUT "Enter a letter to guess" UNTIL UserLetter.IsCharacter() = TRUE UserWord � INPUT "Enter a word to guess" Second: Is user's guess letter in array? This will need to check all 5 values in the array and output the position if it is correct. The most efficient way to do this is to use a loop. //INPUT word to guess REPEAT WordToGuess � INPUT "Enter a 5 character word" UNTIL LENGTH(WordToGuess) = 5 //store characters in array LetterArray � [SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 2), SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess, 3, l)] //INPUT user's guesses REPEAT UserLetter � INPUT "Enter a letter to guess" UNTIL UserLetter.IsCharacter() = TRUE //check for position of user's guess FOR Count - 0 TO 5 IF UserLetter = LetterArray[Count] THEN OUTPUT "Position ", Count ENDIF NEXT Count UserWord � INPUT "Enter a word to guess" Third: Is user's word guess correct? This will involve checking the word input against the first word and outputting if it is correct. LetterArray � [SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 1), SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess, 3, 1)] //INPUT user's guesses REPEAT UserLetter � INPUT "Enter a letter to guess" UNTIL UserLetter.IsCharacter() = TRUE 363 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED //check for position of user's guess FOR Count� 0 TO 5 IF UserLetter = LetterArray[Count] THEN OUTPUT "Position ", Count ENDIF NEXT Count //check user's guess UserWord .... INPUT "Enter a word to guess" IF Userword = WordToGuess THEN OUTPUT "You win" ENDIF Fourth: Count number of times the user has guessed and repeat and stop when 10 letters or word is correct. These two are being combined because they are dependent on each other. Split the processes down to: • Repeatedly allow the user to guess the letters and word (repetition means using a loop). • Keep a count of how many guesses they have (counting requires a variable, and incrementing this value). • Stop when they get it correct or have had 10 guesses (the conditions for stopping the loop). LetterArray� [SUBSTRING(WordToGuess, 0, 1), SUBSTRING(WordToGuess, 1, 1), SUBSTRING(WordToGuess, 2, 1), SUBSTRING(WordToGuess, 3, 1)] Count = 0 WHILE(Count < 10) REPEAT //loop for 10 guesses //input user"s guesses REPEAT UserLetter� INPUT "Enter a letter to guess" UNTIL UserLetter.IsCharacter() = TRUE //check for position of user's guess FOR Count� 0 TO 5 IF UserLetter = LetterArray[Count] THEN OUTPUT "Position ", Count ENDIF NEXT Count //check user"s guess UserWord� INPUT "Enter a word to guess" 364) 11 Programming scenarios practice CONTINUED IF UserWord = WordToGuess THEN OUTPUT "You win" ENDIF Count+- 11 Count+- Count + 1 ENDWHILE Fifth: Perform the final checks: 1 2 3 4 5 6 7 Have you stored all of your inputs in variables? Have you validated inputs where possible? Have you performed all of the processes? Have you outputted the required values? Have you included appropriate messages in your outputs? Have you added comments? Return to the scenario and tick every statement that your program performs. If you don't tick a statement then you need to add that to your program. Questions 1 2 3 Which elements of a program do you first need to identify? What is a process in a program? What do you need to include in your final checks? 11.4 Method 2: Practically carrying out the program and identifying the stages In this method you walk through the task requirements and then turn the steps that you followed into an algorithm. Example - calculator: A program needs writing to act as a calculator. T he 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. 365 ) > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK Perform the actions You can do this in sequence, like in the table below. You might want to do it several times with different values: Requirement Run-through 1 Run-through 2 Steps followed Take one integer value. from the user input 10 input 2 INPUT number1 Take an operator as input; + for addition, - for subtraction, / for division, * for multiplication or A for power of. input+ input A IN PUT operator Take a second integer value from the user. input 20 input 3 INPUT number2 Output the result. output 30 output 8 Check operator and output calculation. Looking at the steps followed helps you to write the algorithm. INPUT Numberl INPUT Operator INPUT Number2 IF Operator = "+" THEN OUTPUT Numberl + Number2 ELSEIF Operator = "-" THEN OUTPUT Numberl - Number2 ELSEIF Operator = "*" THEN OUTPUT Numberl * Number2 ELSEIF Operator = "/" THEN OUTPUT Numberl / Number2 ELSE OUTPUT Numberl A Number2 ENDIF Adding extras It is best practice to add the following to your algorithms: • Messages to tell people what to input. • Validation of inputs. • Messages to say what is being output. • Comments to explain the code. 1 Messages to tell people what to input: Numberl +- INPUT "Enter the first number" Operator +- INPUT "Enter an operator2 Number2 +- INPUT "Enter the second number" 366 > 11 Programming scenarios pra ctic e IF Operator = "+" THEN OUTPUT Numberl + Number2 ELSEIF Operator = "-" THEN OUTPUT Numberl - Number2 ELSEIF Operator = "*" THEN OUTPUT Numberl * Number2 ELSEIF Operator = "/" THEN OUTPUT Numberl / Number2 ELSE OUTPUT Numberl A Number2 ENDIF 2 Validate inputs: REPEAT Numberl <- INPUT "Enter the first number" UNTIL Nwnberl.Isinteger = TRUE REPEAT Operator <- INPUT "Enter an operator" UNTIL Operator = 1 + OR Operator = OR Operator = 1" 1 1 11 1 1 11 - 11 OR Operator = 11 * 11 OR Operator = 11 /11 REPEAT Number2 <- INPUT "Enter the second number" UNTIL Nwnber2.Isinteger = TRUE IF Operator = "+" THEN OUTPUT Numberl + Number2 ELSEIF Operator = "-" THEN OUTPUT Numberl - Number2 ELSEIF Operator = "*" THEN OUTPUT Numberl * Number2 ELSEIF Operator = "/" THEN OUTPUT Numberl / Number2 ELSE OUTPUT Numberl A Number2 ENDIF 3 Messages with outputs: REPEAT Numberl <- INPUT "Enter the first number" UNTIL Numberl.Isinteger = TRUE 367 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK REPEAT Operator r INPUT "Enter an operator" UNTIL Operator = "+" OR Operator = "-" OR Operator OR Operator = nAn "*" OR Operator .. I "*" OR Operator II/ II 11 REPEAT Number2 r INPUT "Enter the second number" UNTIL Number2.Isinteger = TRUE IF Operator = "+" THEN OUTPUT "The addition = 11 OUTPUT Numberl + Number2 ELSEIF Operator = "-" THEN OUTPUT "The subtraction = " OUTPUT Numberl - Number2 ELSEIF Operator = "*" THEN OUTPUT "The multiplication = OUTPUT Numberl * Number2 ELSEIF Operator = "/" THEN OUTPUT "The division = " OUTPUT Numberl / Number2 ELSE OUTPUT "The power of = ENDIF 4 OUTPUT Numberl A 11 Number2 Comments to explain the code: //input the first number REPEAT Numberl r INPUT "Enter the first number" UNTIL Numberl.Isinteger = TRUE //input the operator REPEAT Operator r INPUT "Enter an operator" UNTIL Operator "+" OR Operator = " " OR Operator OR Operator = HAn //input the third number REPEAT Number2 r INPUT "Enter the second number" UNTIL Number2.Isinteger = TRUE //check operator and perform calculation 368 ) 11 Programm ing scenarios practice IF Operator = "+" THEN OUTPUT "The addition = " OUTPUT Numberl + Number2 ELSEIF Operator = "-" THEN OUTPUT "The subtraction OUTPUT Numberl - Number2 ELSEIF Operator = "*" THEN OUTPUT "The multiplication = OUTPUT Numberl * Number2 ELSEIF Operator = "/" THEN OUTPUT "The division - " OUTPUT Numberl / Number2 ELSE OUTPUT "The power of = " OUTPUT Numberl Number2 ENDIF A SKILLS FOCUS 11.2 TACKLING A PROBLEM In this problem an array is needed to store data within the problem. This Skills Focus will take you through the production of a solution to a problem that makes use of an array. You can then use this same methodology when solving your own problems. A 2D array stores the cost of items and the quantity sold of 100 items. For example, part of the array could store the data in the table. 10.00 15.99 20.22 13.78 8.99 2 5 Quantity 6 8 10 Cost 6.20 4.30 15 3 10.00 12.00 16 10 A program is needed to: • Ask the user whether they want to see the: • total number of items sold • total cost of all items sold • quantity of items that sold less than 10 • quantity of items that sold more than or equal to 10. • Calculate the answer to the item selected. • Output the total with an appropriate message. 369) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED Write an algorithm in pseudocode or program code to perform these actions. You do not need to initialise the values in the array. Walk through the problem Requirement Run-through 1 Run-through 2 Ask the user what they want to see. OUTPUT "Select 1 for total number, 2 for total cost, 3 for items less than 10, 4 for items more than 10". OUTPUT "Select 1 for total OUTPUT message number, 2 for total cost, 3 for items less than 10, 4 for INPUT choice. items more than 10". Enter 1. Enter 2. 1 was chosen, so add up total number of items = 5 +6+8+10+2+15+3 +16+10 2 was chosen so calculate total cost Calculate answer. cost* quantity for each item 10 * 5 +15.99+ 6, etc. Steps followed If 1 was chosen total items. If 2 was chosen, multiply cost by quantity and total values. If 3 was chosen check if each value is less than 10. If 4 was chosen check if each value is more than or equal to 10. Output answer with appropriate message. "The total number of items sold is 75". "The total cost is " total Cost OUTPUT message depending on choice and total value. Important note: this program uses an array. To check, count, or calculate using each item in an array you will need to use a loop. A count-controlled loop, e.g. for loop, is most appropriate. Take each step and turn it into pseudocode. Step 1 - output and input of choice. OUTPUT "Enter 1 for total number of items sold, 2 for total cost of all items sold, 3 for number of items less than $10, 4 for number of items $10 or more". INPUT Choice Step 2 - totalling number of items sold. IF Choice = 1 THEN Total .- 0 FOR Count .- 0 TO 100 Total .- Total + Array[Count, 1) NEXT Count OUTPUT "Total number of items sold is " , Total ENDIF 370) 11 Programming scenarios practice CONTINUED Step 3 - totalling cost of all items sold. IF Choice = 2 THEN Total <-- 0 FOR Count <-- 0 TO 100 Total<-- Total + (Array[Count, OJ * Array[Count, 1]) NEXT Count OUTPUT "Total cost of items sold is ", Total ENDIF Step 4 - totalling number of items that sold less than 10. IF Choice = 3 THEN Numberitems <-- 0 FOR Count<-- 0 TO 100 IF Array[Count, 1] < 10 THEN Numberitems <-- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold less than 10 " ENDIF Numberitems Step 5 - totalling number of items that sold 10 or more. IF Choice = 4 THEN Numberitems <-- 0 FOR Count <-- 0 TO 100 IF Array[Count, 1] >= 10 THEN Numberitems <-- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold 10 or more • ENDIF Numberitems Finally combine the code. There are four selection statements that could stay as separate IF statements, but only one of these will ever run therefore using ELSEIF will be more efficient. OUTPUT "Enter 1 for total number of items sold, 2 for total cost of all items sold, 3 for number of items less than $10, 4 for number of items $10 or more." INPUT Choice 371 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK CONTINUED IF Choice = 1 THEN Total <- 0 FOR Count <- 0 TO 100 Total <- Total + Array[Count, 1] NEXT Count OUTPUT "Total number of items sold is " , Total ELSEIF Choice = 2 THEN Total <- 0 FOR Count <- 0 TO 100 Total<- Total + (Array[Count, OJ * Array[Count, 1]) NEXT Count OUTPUT "Total cost of items sold is ", Total ELSEIF Choice = 3 THEN Numberitems <- 0 FOR Count <- 0 TO 100 IF Array[Count, 1] < 10 THEN Numberitems <- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold less than 10 " Numberitems ELSEIF Choice = 4 THEN Numberitems <- 0 FOR Count <- 0 to 100 IF Array[Count, 1] >= 10 THEN Numberitems <- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold 10 or more " Numberitems ENDIF Final checks • Messages to tell people what to input. (✓) • Validation of inputs - needs to be done. • Messages to say what is being output. (✓) • Comments to explain the code. ----- 11 Programming scenarios practice CONTINUED //Take user choice from menu REPEAT OUTPUT "Enter 1 for total number of items sold, 2 for total cost of all items sold, 3 for number of items less than $10, 4 for number of items $10 or more." INPUT Choice UNTIL Choice = 1 or Choice = 2 or Choice = 3 or Choice = 4 IF Choice = 1 THEN //if choice is 1 total number of items sold Total <--- 0 FOR Count <--- 0 TO 100 Total <--- Total + Array[Count, 1] NEXT Count OUTPUT "Total number of items sold is " , Total ELSEIF Choice = 2 THEN //if choice is 2 total cost of all items sold Total <--- 0 FOR Count <--- 0 TO 100 Total<--- Total + (Array[Count, o J * Array[Count, 1]) NEXT Count OUTPUT "Total cost of items sold is " , Total ELSEIF Choice = 3 THEN //if choice is 3 count items less than 10 Numberitems <--- 0 FOR Count <--- 0 TO 100 IF Array[Count, 1] < 10 THEN Numberitems <--- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold less than 10 " Numberitems ELSEIF Choice = 4 THEN //if choice is 4 total items 10 or more Numberitems<--- 0 FOR Count <--- 0 TO 100 IF Array[Count, 1] >= 10 THEN Numberitems <--- Numberitems + 1 ENDIF NEXT Count OUTPUT "Number of items that sold 10 or more " Numberitems ENDIF 373 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) PROGRAMMING TASKS 11.1 A character in a computer game has an x coordinate and a y coordinate, for example, x = 10, y = 20. The current position of the player is out. The user can then enter a command to move right, move left, move up or move down. Moving left decreases the x coordinate by 1. Moving right increases the x coordinate by 1. Moving up increases the y coordinate by 1. Moving down decreases the y coordinate by 1. The new position of the player is output. Getting started 1 Identify the inputs into the system. 2 Identify the processes in the system. 3 Identify the outputs from the system. Practice Write a program using pseudocode or program code to solve the problem. Challenge 1 The player's x coordinate can only be between 0 and 200. The player's y coordinate can only be between 0 and 150. 2 Add validation to your program to make sure the character's positions does not go outside these boundaries. PROGRAMMING TASKS 11.2 A guessing game stores a number in a constant. The user has 10 attempts to try and guess the number. If the user's guess is too high the program outputs "Too high". If the user's guess is too low the program outputs "Too low". If the user guesses correctly the program outputs the number of guesses they had and the game ends. If the user has 10 guesses that are all incorrect then the game outputs the number and tells the user they have lost. 374) 11 Programming scenarios practice CONTINUED Getting started 1 Identify the data that needs to be input into the system. 2 Identify the outputs that will come from the system. 3 Identify any variables or constants that you may need to use. Practice 1 Write the program using pseudocode or program code. 2 Check that your program meets all the requirements. 3 Make sure you have added comments to explain your code. Challenge This task goes beyond the specification. Programs can use random number generators. Find out how to use a random number generator and use this to declare the number at the start of the game, instead of hard coding a value into the program. Amend your program to use the random number generator. PROGRAMMING TASKS 11.3 A program takes a 2-digit hexadecimal number as input (e.g. 3C) and outputs the binary and denary equivalent of that number. Getting started 1 How do you convert a 2-digit hexadecimal number to binary? 2 How do you convert a 2-digit hexadecimal number to denary? 3 What inputs are needed in the system? 4 What outputs are needed in the system? Practice Write a program using pseudocode or program code to solve the problem. Challenge Extend your program to ask the user what type of data they are entering, and what type of data they want output. For example, they could enter the denary number 1 and want the 8-bit binary output 00000001. 375 > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) PROGRAMMING TASKS 11.4 A program asks the user to enter the cost per kilogram for a product, e.g. $1.20. The user then needs to enter the weight of each item while the total cost is less than $100.00. The program should then output how many items were entered and the total cost. Getting started 1 Identify the inputs to the system. 2 Identify the outputs to the system. 3 Identify the processes that need to take place. Practice Write a program using pseudocode or program code to solve the problem. Challenge Extend the program to store the weight and cost of each item entered in an array. When the last item is entered store the weights and costs in a text file. PROGRAMMING TASKS 11.5 A computer program allows a user to select a username and password. The array, Logins , has up to 1000 indices to store the current usernames and passwords. Part of the array is shown: Username Password Rainbow tidjsrn8 Stars 111jdk99 Foxes99 3jck285hkd Purple123 iii8800sndm GamerSS a45i12n3 The variable NumberUsers stores the how many usernames are currently stored in the array Logins . A valid username is one that does not already exist in the array Logins . A valid username has at least 8 characters, and at least one letter and at least one number. Getting started 1 Identify the inputs into the system. 2 Identify the outputs from the system. 3 Identify the requirements for the username and password. Practice Write a program using program code or pseudocode to allow a user to enter a username and password and store this in the array Logins. 376) 11 Programming scenarios practice CONTINUED Challenge This task goes beyond the specification. The usernames and passwords can be stored in a text file instead of the array. Each item can be on a different line, e.g. username1 password1 username2 password2 Find out how to read and write multiple lines from a text file. At the start of the program read in all the usernames and passwords to an array. At the end of the program write all the usernames and passwords back into the file. PROGRAMMING TASKS 11.6 The game rock, paper, scissors is played by two people. Each person selects rock, paper or scissors. The person who wins is determined by these rules: • Rock wins over scissors. • Scissors wins over paper. • Paper wins over rock. Getting started 1 Play the game with another student. 2 Identify the inputs in this system. 3 Identify the processes in this system. 4 Identify the outputs in this system. Practice 1 Write a program using pseudocode or program code for the game to be played by two players. 2 Amend your program to use a function to determine which player wins. This should take the two moves as parameters and return which player won. 377 ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK ) CONTINUED Challenge The second point of this challenge goes beyond the specification. Amend your program to allow: • The players to play 11 games and output who has won the most. • The player to choose to play another player, or the computer. The computer will need to make use of random numbers to identify which move it should make. • Use a file to record a high score and the player who achieved this. This should be updated , if necessary, after each game. SUMMARY Always read the scenario twice before starting. Walk through the requirements, acting out each statement to identify how the system needs to work. Identify the inputs, processes and outputs of a system. Include validation to any inputs. Use appropriate messages when inputting and outputting data. Add comments to explain your code. EXAM-STYLE QUESTIONS 1 A program takes a number from the user. It then counts from 1 to the number that the user has entered (inclusive). If the number being input is divisible by 5 it outputs a message. If the number being input is divisible by 7 it outputs a message. Write a program using pseudocode or program code to solve the problem. [15) 2 A program stores the name (e.g. Dahlia), maximum height in cm (e.g. 100) and if they can live in shade (e.g. TRUE) of plants in one or more arrays. The program asks the user to enter their requirement for a plant including: • The minimum height required. • If it needs to live in shade or not. The program should then output all of the plants that meet the requirements. Write a program using pseudocode or program code to solve the problem. You can assume the array(s) have already been initialised with 50 plants. [15) 378) 11 Programming scenarios practice CONTINUED 3 A computer game for two players uses a set of cards. Each card has an animal; horse, elephant, cat or lion. Each player starts the game with 15 cards stored in an array; Playerl , Player2. The first card for each player is compared. The player who wins the round follows these rules: • Lion always beats horse. • Elephant always beats lion . • Horse always beats cat. • Cat always beats elephant. The program compares each card in turn until it has compared all 16 sets of cards. The player who wins each comparison gets 1 point. If there is a winner at the end of the game, the program should store the winner's score in a text file, and output the player's name. Write a program using pseudocode or program code to solve the problem. You can assume the cards have already been divided between the two players. [15] 4 A program asks the user to enter the cost of 100 items. Each cost should be stored in an array, Costs . The program should calculate and output: • The total cost of the items. • The average cost of the item. • The cost of the most expensive item. • The cost of the least expensive item. Write a program using pseudocode or program code to solve the program. [15] 5 A program stores words in a ID array, Words , with 1000 elements. The program needs to ask the user to select one of the three actions for the program to perform. 1 Identify and output how many words have 5 or more letters. 2 Identify and output the longest word in the array. 3 Identify and output the shortest word in the array. The program needs to use a function for each of the three actions that are called from the main program. Write a program using pseudocode or program code to solve the problem. [15] You can assume the array is already initialised with 1000 words. 379) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK 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 ... - __,_ -- --- _...,_______ _ _ -- -� identify the inputs for a system. . ---- - -- - - See topic 11.2 identify the processes for a system. 11.2 identify the outputs for a system. 11.2 validate input data. 11.3 use appropriate input and output messages. 11.3 add comments to explain my code. 11.3 Needs more work Getting there -- -- - Confident to move on - --- - - - - If you haven't already, you will learn about the very important purpose of testing in the development lifecycle of a program. Testing is the stage that helps us understand whether the program works correctly in all the different ways that it should do. When a company creates a piece of technology, it also needs to thoroughly test that technology to see if it works correctly and to see if it meets the needs of the user. A company such as Microsoft creates innovative technology that goes through a thorough testing process. Often, that testing process reveals problems and issues with the technology. You may find when you test your programs that you find problems and issues that you hadn't considered. This is why testing is so important! One product that Microsoft has used extensive testing in the development of is Code Jumper. Students are able to handle the pods and interact with them to identifying their commands, joining them together to create working algorithms. These algorithms create outputs such as music and audio stores. This makes programming accessible to visually impaired or blind students, allowing them to learn the basics of programming alongside their sighted peers using block-based languages such as Scratch. This can mean that more students have a greater ability to choose programming as a career or hobby. Have you ever considered how a student who is visually impaired or blind can learn how to code? Code Jumper is an innovative and pioneering product that students that are blind or visually impaired can use to learn how to program alongside their sighted peers. It is designed by Microsoft and it helps to open the fun and exciting practice of programming to all students. Code Jumper allow students to create programs by joining small hardware pods with cables to form a sequence of commands, creating an algorithm. Each pod has a different command enabling such as play, pause and the ability to create selection and iteration. Therefore, each pod is like a statement in the program. Figure 2: Two students creating a program together. The design and creation of Code Jumper took a lot of time and innovation for Microsoft. The team at Microsoft worked with many children and designers to create the most recent product. The journey to that product has often required a great deal of problem solving, one of the fundamental skills that you are learning as a computer scientist. The software for the product had to be tested to make sure that it worked correctly, but one of the most challenging aspects for Microsoft was designing the most effective hardware for the product. It took a lot of user testing and iteration to get it right The design team needed to consider that the students using the product would be picking up and handling the product, touching it to be able to identify if it is a pod that is designed to create a variable, selection or iteration. They also had to think about the student finding the connections that enabled them to join the pods to create the program. One of the first ideas the design team had was to create a system similar to a block building computer program, a bit like a physical version of a program called Scratch, that you may have used when you were younger. Students would create programs by taking the blocks and joining them together. They would click together through the use of magnets. Microsoft spent time designing and creating the prototype for this system and trialled it with some students. The students did not use the product in the way they had anticipated. They found that the students became frustrated when trying to connect the block. They also found that they couldn't pick up their algorithms they had created with their blocks and pass them to a friend, as the magnetic connections would fall apart. This would also happen if the student knocked their algorithm off the table. They would have the frustration of having to start it all again. Microsoft initially recognised the importance of the feel and interaction of the hardware for the visually impaired students, but their initial prototype just didn't have the level and ease of interaction they were looking for. It was back to the drawing board! Other aspects of the hardware design that had to be trialled and redesigned repeatedly were the wired connection for joining the pods. The design team had to get the best level of flexibility and the simplest audio jack system so it could be easily plugged in. Some of the problems they encountered came from the way that the students would touch and feel the pod for the audio jack. This could often result in the connection being short-circuited. Just when the team thought they had the right set-up for this, they would trial it with students, who would react to it in a very different way and they would again have to review the design and change it to meet the needs of the user. created the prototype and tested this with the user. Based on the result of these tests, they repeatedly reworked and improved the technology to meet the user's needs. Without this level of test, they would not have been able to understand whether the pods and how they were joined together would work effectively for the students. The outcome of the testing informed how they needed to change and develop the product to improve it. If they had just made the product, tested it to see if all the parts work correctly, then released it, they would still have the original idea of the magnetic blocks that students didn't use in the way they had been intended. This shows that testing is so much more important than just seeing if a program and product operate correctly, it shows whether the computer system or hardware will meet the needs of the user. It is so easy to just consider what we want from a program when we are creating it. However, it is likely that thousands, possibly millions, of people could potentially use that computer program. Extensive testing can make sure that many different types of users have tested the product in many ways, to make sure it meets the needs of different types of users. Questions 1 How many different types of testing do you know? Can you name and describe any of them to a partner? 2 What problems did Microsoft find with the Code Jumper product when they tested it with the user? Do you think these problems would have been found without the testing? Why or why not? 3 Do you think that you do enough testing on your programs that you create? How do you know? What kind of evidence do you have for your testing? ACTIVITY T hink of two reasons why you think it is important to thoroughly test a product or program. Share these reasons with a partner. Write a promise to yourself that you will make sure that you test all your programming work thoroughly. Complete the following statements as part of your promise: • • Figure 3: Two students with mixed visual abilities making a program together. Microsoft applied the fundamentals of creating a piece of technology to the creating of Code Jumper. They analysed the needs and requirements of the user, designed and • • Testing is so important because ... If I do not test my work thoroughly I could get problems such as ... I will make sure I test my work by ... I will have evidence of testing my work, such as ... If you haven't learnt already, you will learn what is meant by Al and its main characteristics. As Al becomes part of almost every activity that we do, it can have a considerable impact on our lives and choices. Microsoft have to consider the impact that all of its technologies have on people and society when they create Al systems. They call the focus of creating technology in this way 'Responsible Al', making sure that both the operation and the ethics of the system have been thoroughly considered. Microsoft collaborates with researchers and academics around the globe to develop and advance responsible Al practices and technologies. Microsoft have six principles they apply when creating any Al system, these are: • Fairness - Al systems should treat people fairly. • Inclusiveness - Al systems should empower everyone and engage people. • • • • Reliability and safety - Al systems should perform reliably and safely. Transparency - Al should be understandable. Privacy and security - Al systems should be secure and respect privacy. Microsoft currently have a research project called Project Tokyo. This is an Al system that helps a blind or visually impaired person to identify people that they know around them. Researchers created a prototype of the system on an adapted Hololens device (see Figure 1). The device that the Al system operates on is a headband worn by the user. This headband contains cameras, depth sensors and speakers. Have you ever walked into a room and you just see lots of faces of people that you do not know? You may feel quite shy, you may feel a little nervous, but then you spot a face of a person that you know and you may then feel much more confident about walking into the room. Those who are without full vision have to try much harder to listen for a voice that they may recognise in the crowd, or they may just have to wait until someone approaches them. Walking into a room can be a daunting task for a visually impaired person - one they face every day! When wearing the headband, a user can walk into a room and they will be alerted if there is a person they know close by. The headset will do this by using the cameras to scan the room and using the speakers above the users ears to play sounds they recognise, that will tell them information about who is in the room, whether the user knows them and where they are. Accountability - People should be accountable for Al systems. gnise people in the room. For example, a user can walk into the room and they hear a click sound from the headset that sounds like it is approximately 1 metre away to their left side. This lets the user know that a person is stood about 1 metre to their left. If the Al system then recognises this person's face, the user will hear a bump sound and then the name of the person. If a user hears a click, but the system cannot detect the other person properly, possibly because it cannot scan their face properly, the user will hear an elastic band stretching sound that will guide the user to turn their face toward the person, to allow for a better placement for scanning. This feature can also help the user turn their face toward the other persons, to indicate that they want to communicate. Many social and communication cues are visual, and fully sighted people can often take them for granted, such as knowing when someone is making eye contact with them. This feature of the Al system can alert the user to some of those cues and give them a greater level of communication and connection with the other person. This Al system heavily relies on analysing data, it has to constantly read and update the data from the surrounding environment. It has to compare this data to stored data to see if it recognises a person. Therefore, one of the key principles of responsible Al to consider in this project is the privacy and security of data. The way Microsoft makes sure the data is kept private and secure is to only store hashes of the data for people's faces. A hash 1s a type of encrypted message that is very secure. This data is stored without any time stamp or location data to minimise the risk of anyone using this data for malicious intent. There are lots of implications that need to be considered when a system collects and stores data about people. Will they feel happy for their face and dimensions to be scanned? Will they see this as an invasion of their privacy? They may also be concerned with what happens to their data when it has been scanned. There is also the data that is stored about the people that know the user. Will the bystander need to give their consent for this data to be stored? Will the bystander worry about how this data is used? There could also be a whole range of security issues with the storage of this data that you may have already learned about if you have studied Chapter 5 of this book. Questions 1 How do you feel about your features, such as your face, being scanned by a person wearing this kind of system? 2 Do you think it is important to create responsible Al? Why? 3 Do you think the data needed for the device should be stored locally on the device or in a cloud system? Why? ACTIVITY Work in a group. Imagine you are the cyber security gurus who have been contacted by Microsoft to make sure the data they store is kept safe. Create a presentation for Microsoft to tell them what you will do to keep their data secure. Figure 2: Data of a known person being scanned into the Project Tokyo Al system Your teacher will act as the representative for Microsoft and choose who they think will do the best job. ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > Glossary Command words The command words and definitions in this section are taken from the Cambridge International syllabuses (0478/0984/2210) for examination from 2023. You should always refer to the appropriate syllabus document for the year of your examination to confirm the details and for more information. The syllabus document is available on the Cambridge International website www.cambridgeinternational.org. calculate: work out from given facts, figures or information. compare: identify/ comment on similarities and/ or differences. define: give precise meaning. demonstrate: show how or give an example. describe: state the points of a topic/ give characteristics and main features. Key words 1-dimensional array: an array that has only one index. 2-dimensionsal array: an array that has two indices. abnormal test data: data that a program should not accept. access levels: the amount of direct access a user is given to data and resources. This could be set to be only certain sections of a whole collection of data and resources. accumulator (ACC): a register that is built into the ALU that stores the result of any interim calculations. acknowledgement: a message that is sent from one device to another to indicate whether data is received correctly. active script: this is the script that is used to produce any of the interactive elements of a web page. actuator: a mechanical part that causes another device or part to move. address: a memory location in RAM. address bar: the section of a web browser where you type the web page address. address bus: wires used for the transmission of addresses between components in a computer. 386) evaluate: judge or calculate the quality, importance, amount or value of something. explain: set out purposes or reasons/ make the relationships between things evident/ provide why and/ or how and support with relevant evidence. give: produce an answer from a given source or recall/ memory. identify: name/ select/ recognise. outline: set out the main points. show (that): provide structured evidence that leads to a given result. state: express in clear terms. suggest: apply knowledge and understanding to situations where there are a range of valid responses in order to make proposals/ put forward considerations. adware: a software based cyber issue that automatically creates popup advertisements. analogue: continuous data that can be any value within a range. analogue data: a continuous stream of data that is processed by humans. analysis: the first stage of the program development life cycle that involves investigating the problem. AND operator: returns True when both inputs are True. anti-malware: a type of software that scans a computer or device with the purpose of finding and removing malware. anti-virus: a type of software that scans a computer for viruses with the purpose of finding and removing them. application software: software that allows the user to perform a useful task. architecture: the design of a computer system, including the components it contains. arithmetic logic unit (ALU): the component in the CPU that performs all the mathematical and logical operations required when processing data and instructions. Glossary arithmetic operator: a symbol that performs a mathematical function, e.g. '+' adds two values together. array: a data structure where you can store multiple data items, of the same data type, under one identifier. artificial intelligence: a part of computer science that looks at creating machines that can think and perform tasks a person would usually perform. assembler: converts assembly language into machine code. assembly language: code written in mnemonics that allows direct manipulation of the hardware. It must be converted into binary code to run. assignment: a type of programming statement that stores data in a variable or constant. asymmetric: a type of encryption that uses two different keys to encrypt and decrypt data. 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. automated: a device that is operated without human interaction. automated system: a system that is designed to operate without the need for any human intervention. automatic repeat request (ARQ): a type of error detection method that uses acknowledgement and timeout to see if data has arrived correctly after transmission. automation: the use of automated equipment in a process, e.g. a factory. average: the mean of a set of values, the total divided by the quantity. binary: a base-2 number system that uses the values 0 and 1. biometric device: a device that allows a user to record and input a biometric password. biometric password: a type of password that uses a person's biological data, such as their fingerprint. blockchain: a method that is used to track all the transactions made with a cryptocurrency. bookmark: a link that can be created to allow you to quickly find a web page again. Boolean: a data type. True or False. Boolean operator: a symbol that joins multiple logical comparisons, can be AND OR or NOT. bootstrap: the first commands loaded when a computer starts, it checks hardware and loads the firmware. 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. botnet: a network of bots that are created to carry out a DDoS attack. boundary test data: data that is on the edge of being accepted, and data that is on the edge of not being accepted. 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. bubble sort: a sorting algorithm that moves through the list repeatedly swapping values in pairs. cache: a type of storage that is built into the CPU to store the most frequently used data and instructi;ns. 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 web page. CASE statement: a type of selection construct where there is a list of different values to compare a single value against. casting: converting data from one data type to another data type. cell: the intersection of the rows and columns of transistors in solid-state storage. central processing unit (CPU): a component in a computer system that processes data and instructions. certificate authority: the awarding organisation that checks if another organisation is real and secure before awarding them a digital certificate. char: A single character, e.g. 'A!., 'l ' , '*'. character set: it contains all the characters that are in that character set and the binary value that is assigned to each character. 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. 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. cipher text: the name given to data after transmission. clock speed: the number of fetch-decode-execute cycles that can be performed in a second. cloud storage: data storage that is owned by a third party and accessed by the user, using the internet. 387 > > CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK coding: the writing of a program using one or more programming languages. colour depth: the number of bits that are used to create each colour in an image command line interface: a type of operating system where the user types commands. comment: text within a program to describe its function, it is not executed when the program is run. compiler: a translator that converts a high-level language into a low-level language. It checks all code before running the program. compression: a method that uses an algorithm to reduce the size of a file. concatenation: joining two or more strings together. constant: a named memory location that can store data. The data cannot change whilst a program is running. control bus: wires used for the transmission of control signals between components in a computer. control gate: a component that controls the flow of electric current. control unit (CU): the component in the CPU that controls all the operations in the CPU. cookie: small text file that is used to store personal data, by a web browser. core: the part of the CPU that contains all the components that are used to perform the fetch-decode­ execute cycle. count-controlled loop: a type of iteration. Code is run a finite number of times. Usually a for loop. counting: statements in a program that record how many of something there are; a type of program, it adds one for every item to find out how many there are. cryptocurrency: a type of digital currency that uses encryption procedures. current instruction register (CIR): a register that is built into the CU that holds the current instruction that is being processed in the CPU. data backup: a copy of data that is stored separate from the computer. data bus: wires used for the transmission of data and instructions between components in a computer. data packet: a unit of data that is used to transmit data across a network. decomposition: taking a system and splitting it into smaller sub-systems, which can in turn be split into smaller sub-systems. denary: a base-10 number system that uses the values 0-9. design: the second stage of the program development life cycle, which involves decomposition of the problem and algorithms created ready for implementation. digital: discrete data that is stored as 1 s and Os. 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. digital currency: a currency that exists electronically rather than physically. digital data: discrete data that only uses the values 0 and 1. digital ledger: a database that is a list of all the transactions recorded by the use of blockchain. 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. DIV: integer division. The remainder from the division is ignored, e.g. 5 DIV 2 = 2. domain name: a specific part of a URL that contains the unique name for the web server. domain name server (DNS): a special server that contains a database of domain names and their corresponding IP address. double: a data type. Decimal numbers. double entry check: two different people enter the same data which are then compared. driver: a program that controls a device, for example, a printer or a keyboard. dynamic IP: an IP address that can change each time the device connects to a network. echo check: a type of error detection method that sends a copy of the transmitted data back to the sender to be compared with the original data sent. editor: a feature of an IDE that allows the user to enter and amend program code. embedded system: a computer system that performs a dedicated function. data type: the characteristics of a piece of data. Common data types are string, integer, real and Boolean. encryption: a method of securing data for storage or transmission that scrambles it and makes it meaningless. encryption key: a type of algorithm that is used to encrypt data. database: an example of application software to store and manipulate data. ethernet: another type of connection that can be used to transmit data within a network. 388 > Glossary executable file: a file produced by a compiler that can be run independent of translator software and does not include the source code. expert system: a system that attempts to replicate the knowledge of an expert. extreme test data: data that is on the edge of what is allowed. fetch-decode-execute cycle: the cycle through which data and instructions are processed. field: an individual piece of data, e.g. date of birth. file handling: programming statements that allow text files to be opened, read from, written to and closed. firewall: a cyber security method that is used to examine incoming and outgoing traffic from a computer or network. firmware: instructions that are stored in the ROM and are loaded when the computer starts. floating gate: a component that can store electrical charge. flowchart: a diagrammatic representation of an algorithm. format check: a type of validation that makes sure the data meets a specific order, e.g. 1 number, then 3 letters. full-duplex: a transmission method where data is transmitted in both directions at the same time. function: a subroutine that does return a value to the program that called it. global scope: the variable or constant can be accessed from any part of the program. Graphical User Interface (GUI): a type of operating system that includes windows, icons, menus and pointers. hacker: the name given to a perpetrator that carries out an act of hacking. hacking: the act of gaining unauthorised access to data. This is normally done to steal or corrupt the data. half-duplex: a transmission method where is transmitted in both directions, but only one direction at a time. hard drive: a storage device that stores data permanently, until it is deleted by the user. hexadecimal: a base-16 number system that uses the values 0-9 and characters A F. high-level language: a type of programming language that uses English-like commands. hypertext markup language (HTML): a scripting (web authoring) language that is used to create web pages. hypertext transfer protocol (HTTP): a protocol that is used for the transmission of web pages and related data across the internet. hypertext transfer protocol secure (HTTPS): a secure version of the HTTP that encrypts data for transmission. identifier: a name given to a variable, constant, data structure ( e.g. array) or subroutine. IF statement: a type of selection construct where the result of the condition is either true or false. index: the number of the space in the array. inference engine: part of an expert system that makes the decisions. infrastructure: the physical structure, such as all the components and cables, that are used to connect devices. input: the user entering data into the program, usually from a keyboard. input device: a device that allows data to be entered into a computer system. instruction set: a set of commands that can be processed by a certain CPU. integer: a data type. Whole numbers. Integrated Development Environment (IDE): a piece of software that allows a user to write, test and run program code. interface: the method by which a user communicates with a computer. interference: disruption, such as electromagnetism, to data when it is transmitted. Internet of Things: the connection of computer systems and everyday devices, using the Internet, to allow data to be exchanged. internet: a very large global network that allows users to access the world wide web. internet protocol (IP) address: the unique address that is given to a device when it is connected to a network . 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. interrupt: a signal sent to the processor to tell it that its attention is required. 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). iteration: 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). knowledge base: part of an expert system that stores the facts. 389) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK length check: a type of validation that checks the number of characters is within a set limit. library routine: a pre-written subroutine that can be called from within a program. linear search: a search algorithm that visits each item of data in turn to check whether it is the data being looked for. local scope: the variable or constant can only be accessed in the subroutine it is declared within. logic expression: a mathematical representation that is used to represent an electrical circuit or system. logic gate: a very small component in a computer system that controls the flow of electricity. logical operator: a 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. loop: another name for iteration. lossless: a compression method that reduces the size of a file by temporarily altering the data. lossy: a compression method that reduces the size of a file by permanently removing data. low-level language: a language closer to the machine's language, this could be assembly language or binary code. MAC address: a unique address that is given to a computer at the manufacturing stage that can be used to identify the computer. machine code: binary code, an example of a low-level language. machine learning: a computer program that can adapt its stored rules or processes. magnetic storage: a type of secondary storage that uses the properties of magnetism to store data. maintainable program: a program that has key features to help it be understood at a later date. malware: a type of malicious software that is downloaded onto a user's computer or device. maximum: the largest item in a set of data. media access control (MAC) address: the unique address that is given to a NIC by the manufacturer. memory address register (MAR): a component in the CPU that holds the address of the data or instruction to be located in RAM. memory data register (MDR): a component in the CPU that holds the data or instruction that are fetched from RAM. 390) 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. microprocessor: an integrated circuit that is able to perform many of the functions of a CPU. minimum: the smallest item in a set of data. mnemonic: instruction code used in assembly language. MOD: remainder division. The remainder after the division is performed, e.g. 5 MOD 2 = 2. natural language interface: a type of operating system that allows the user to type or speak commands. navigate: move around web pages, or move back or forward to previous web pages. nested statement: a construct (selection or iteration) that is inside another construct. network: computers and devices that are joined together using cables or wireless technology. network interface card (NIC): the component in a computer that is used to connect it to a network. non portable: a program that cannot be run on different types and manufacturers of computers. normal test data: data that a program should accept. NOT operator: returns True if the input is False, and False if it is True. operating system: a program that manages the computer, allows the user to communicate with the computer, and allows software to be run. optical storage: a type of secondary storage that uses lasers to store data. OR operator: returns True when one, or both, inputs are True. output: data that is displayed to the user usually on­ screen. output device: a device that can be used to obtain the results of data that has been processed. overflow error: a type of error that occurs when a number larger than a register can store is generated. 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. packet sniffer: a piece of software that is used to examine the contents in a packet of data. packet switching: a method of transmitting data packets across a network. Each data packet is able to take an individual pathway across the network. Glossary page: a unit of data. parallel: a transmission method where data is sent multiple bits at a time down multiple wires. parameter: a value that is sent to a subroutine. parenthesis: brackets in a mathematical statement. They determine which calculations are performed first. parity check: a type of error detection method that adds an additional bit to each byte to create an odd or even sum. payload: the actual data that the user is sending to the receiver. perceptual music shaping: a process that is used in lossy compression that removes sounds that are not normally heard by the human ear. peripheral: a hardware device, used to input, store or output data from a computer, that is not directly part of the computer itself. perpetrator: a person that carries out an illegal or immoral action. 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. pharming: a type of cyber threat that involves downloading malicious software onto a user's hard drive, that redirects a request aimed at a genuine website to a fake website instead. The fake website will encourage the user to input their personal data, allowing it to be stolen. phishing: a type of cyber threat that involves sending a user a fake email that is designed to look genuine. It will encourage the user to provide their personal data either by clicking a link to a fake website, or by responding to the email. pixel: a very small dot of colour that is displayed with many other to create an image. plain text: the name given to data before encryption. port: an entry point into a computer or network. portable: a program that can be run on different types and manufacturers of computers. 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. 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. presence check: a type of validation that makes sure data has been entered. prettyprint: a feature of an editor that changes the colour of text, for example, to highlight key words. primary key: a unique identifier for a record. primary storage: a type of storage that is directly accessed by the CPU. procedure: a subroutine that does not return a value to the program that called it. process: an action that is performed, for example, x=x+l. program counter (PC): a component in the CPU that stores the address of the next instruction to be processed. program development life cycle: a series of structure step/ activities that are followed to produce a system. programmable: a computer that will run the commands stored in it. protocol: a set of rules for transmitting data. proxy server: a method of cyber security that examines requests sent by devices to access the web pages stored on a web server. pseudocode: code-like statements that are used to design an algorithm but do not follow any specific language. RAM (random access memory): a component in the CPU that holds data and programs that are currently in use. range check: a type of validation that makes sure data is between the minimum and maximum. 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. real: a data type. Decimal numbers. record: all of the records in a table about one object, e.g. all the personal details about one student. register: a small component in a computer system that is used to temporarily store data. render: the method of processing all the web page data, such as HTML, to display the web page. resolution: the dimensions of an image. robot: a machine that replicates human actions or movement. robotics: an area of computer science that looks at the creation and use of robots. ROM (read only memory): a type of primary storage that stores the start up instruction for the computer. 391 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK router: a network component that examines a data packet to obtain its destination address and then forwards the packet to this address. rule base: part of an expert system that stores the rules based upon the knowledge. run length encoding (RLE): An algorithm that groups together repeating patterns and indexes them. run-time environment: a feature of an IDE that allows a program to be run and lets the user interact with the program. sample rate: the number of samples recorded each second. sample resolution: the number of bits that are used to record each sound sample. scope: the sections in the code where the variable, or constant, can be accessed. script: a set of statements that are executed. search algorithm: a series of steps that searches for a specific value in a set of data. secondary storage: a type of storage that is designed to store data permanently, until it is deleted by the user. 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. selection: a programming construct. A condition is checked and this determines which code is run, or not run. semiconductor chips: an electronic circuit, where transistors are set on a semiconductor material, such as silicon. sensor: a type of input device that is used to capture data from its immediate environment. sequence: a programming construct. Instructions are run once and in the order they are written. serial: a transmission method where data is sent one bit at a time down a single wire. server: a component that acts as a central resource for the storage of data and applications or for providing a service. session cookie: a type of cookie that is deleted when the web browser is closed. simplex: a transmission method where data is transmitted in a single direction only. single: a data type. Decimal numbers. social engineering: a cyber threat that involves manipulating or deceiving people into providing confidential or personal data. 392) software: a series of instructions written in a programming language that performs a function. solid-state storage: a type of secondary storage that uses transistors to store data. sorting algorithm: a series of steps that will rearrange a set of data into an order, e.g. ascending numerical data. sound sampling: a little piece of sound that is recorded at regular time intervals. spreadsheet: a type of application software that performs calculations on data. spyware: a software based cyber threat that spies on a user's action whilst using a computer, such as logging their key presses. static IP: an IP address that does not change each time the device connects to a network. string: a data type. Any characters including letters, numbers and/or symbols. structure diagram: a hierarchical diagram that shows the decomposition of a system. Structured Query Language (SQL): a standard language used to define and manipulate databases. subroutine: a self-contained piece of code that has an identifier and can be called from elsewhere in a program. symmetric: a type of encryption that uses the same key to encrypt and decrypt data. system software: a type of software that manages the hardware and software in a computer. tab: a website function that allows you to open multiple web pages in the same window. table: a set of data about one type of object, e.g. students. test data: the input data that is used to test a system. testing: repeated use of a system to try all different possibilities to make sure the system is fully working and cannot be broken. timeout: a period of time that is set and used to wait for an acknowledgement to be received. totalling: statements in a program that add together a set of data to produce the total; a type of program, it adds up multiple values to find the total. trace table: a structure to complete when walking through an algorithm manually, where the values that change are written in each row. trailer: a section of a packet of data that contains information about any error checking methods that may be used. transistor: a device that acts as a switch or gate for electronic signals. Glossary 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. transmission media: the cables that are used to transfer data in a network. transport layer security (TLS) protocol: an updated version of the SSL protocol. trojan horse: a software based cyber threat that is used to disguise other malware to try and smuggle it into a computer or network. truth table: a method to show all the different outcomes of an electrical circuit or system, dependent on the inputs it receives. two-step verification: a process that involves inputting two different kinds of data to enter an account or device. type check: a type of validation that checks data is the correct data type. uniform resource locater (URL): another name for the text-based address for a website. USB: an industry standard that is used to transmit data. USB cable: a type of transmission media that uses the USB method to transmit data. USB connection: a collective name for using a USB cable plugged into a USB port to transfer data from one device to another. USB device: the name of a device that plugs into a USB port on a computer. USB port: a socket that is a part of a device or computer that enables you to insert a USB cable. username: a text-based identification that is given to a user that identifies the level of access that they have to stored data and resources. utility programs: system software that performs housekeeping activities. validation: the checking of data to make sure it is reasonable and within set bounds. variable: a named memory location that can store data. The data can change whilst a program is running. wrification: checking that data is entered accurately, that it is the same as the original. ,irtual memory: a type of memory that can be used as an extension to the RAM. ,irus: 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. ,isual check: comparing the data entered with the original side-by-side. rnltage: the pressure that forces the charged electrons to flow in an electrical circuit. web browser: a piece of software that retrieves and displays web pages. web page: a single page within a website. web server: a network component where the web pages for a website are stored. website: a collection of web pages, normally about a related topic or purpose. window: a viewing area that is created in which a software application or file can be opened. word processor: a type of application software that allows the user to create text-based documents. world wide web: the collection of all the web pages and websites that have been made available. 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. 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. 393 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > Index 1-dimensional arrays 270-7 2-dimensional arrays 277-84 abnormal test data 157-8 accelerometers 64, 65 access levels 120-1 accumulator (ACC) 59 acknowledgement 47 acoustic sensors 64 active script 98 actuators 127 addition 211 address bar 101 address bus 57 addresses 57 adware 113 algorithms 144-5,149 averages 171-2 bubble sort 161-6 counting 168-9 data validation 173-7 finding the maximum 170-1 finding the minimum 170 finding the purpose of 184-6 flowcharts 149-53 linear search 159-61 totalling 167 trace tables 179-83 alphanumeric data 298 analogue data 10 analysis 145-6 AND gate 327-8 AND operator 227, 308 anti-malware software 110,114 application software 80, 81, 83 arithmetic logic ui:iit (ALU) 59 arithmetic operators 209-14 arrays 270 1-dimensional 270-7 2-dimensional 277-84 accessing data 272-3, 278-9 using iteration in 274-7, 281--4 using variables as indices 273--4,279-80 artificial intelligence (Al) 136-7 case study 384-5 expert systems 139 machine learning 137-8 ASCII 21 assemblers 88 assembly language 79,86 assignment statements 198-201 auto-completion 90 auto-correction 90 automated systems 63, 126-9 automatic repeat request (ARQ) 47 automation 130-1 see also robots averages 171-2 Berners-Lee,Tim 97 binary system 9 addition 16-18 conversion to/from denary 10-13 logical binary shifts 19-20 negative numbers 20 biometric devices 107 Bitcoin 105 bits 11, 25 blockchaining 105-6 bookmarks 101 Boolean data 202, 298 Boolean logic see logic circuits; logic gates Boolean operators 227, 307-8 bootstrap 81 botnets 109-11 bots 110 boundary test data 157-8 break points 91 brute-force attacks 106-7 bubble sort 161-3 characters 165-6 numerical data 163--4 bytes 25 caches 60, 61 cascading style sheets (CSS) 98 CASE statements 216, 224-6 Index case studies responsible AI 384-5 testing 382-3 casting 203-4 CDs 68 cells 69 central processing unit (CPU) 6, 56 fetch-decode-execute cycle 57-9 performance of 60-1 certificate authorities 99 char data type 202 character sets 21 characters 298 check digits 48, 176 checksum 46 cipher text 49 clock speed 60, 61 cloud storage 70-1 comparison with local storage 72 Code Jumper 382-3 coding 157 colour depth 23 colour scales 22 command line interface 82 comments 267-9, 368-9 comparison operators 216-17 compilers 88-9 compression 27-9 computer case fans 5 computer cases 4 computer components 4-7 concatenation 206 constants 198-9 assignment 201 control bus 59 control gate 68, 69 control unit (CU) 58 cookies 101-4 cores 60 COUNT 313-14, 315-17 count-controlled loops 231-4, 240 counting 168-9, 243-4 cryptocurrency 105-6 current instruction register (CIR) 58 cyber security anti-malware software 110, 114 anti-virus software 114 data protection 115-16 encryption 109 firewalls 112, 114-15 passwords 107-8 cyber threats brute-force attacks 106-7 data interception 108-9 distributed denial of service attacks 109-11 hacking 112 malware 113-15 pharming 116-17 phishing 117-18 social engineering 119-21 data backup 115 data bus 58 data compression 27-9 data input and output 205-8 data interception 108-9 data measuring units 25 data packets 35 data storage 66-9 cloud storage 70-2 virtual memory 69-70 data transmission 34 encryption 49-50 error detection 44-8 full-duplex 41-2 half-duplex 41 interference 38 packet switching 36 parallel 39 serial 38-9 simplex 40 USB connections 43-4 data types 10, 202-3, 298 converting between (casting) 203-4 data validation 173-7, 357-8, 362, 367 data verification 177 databases 80, 296-7 defining a single-table database 299-300 primary keys 299 see also Structured Query Language (SQL) debugging 9 decomposition 146, 147-9 denary system 10 design flowcharts 149-53 pseudocode 154-5 structure diagrams 146-9 digital certificates 99-100 digital currency 105-6 digital data 10 digital ledgers 105-6 distributed denial of service (DDoS) attacks 109-11 395 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK DIV 209,210,213 division 213 domain name servers (DNS) 98 domain names 97 double data type 202 double entry checks 177 drivers 83 drones 135 dynamic IP 74-5 echo check 46 editors 90 ELSE 220-1,228-30 ELSEIF 222-4,228-30 embedded systems 56 encryption 49-50,99,109 ENIAC 79 error detection in data transmission 44-8 reading the code 188-90 using hexadecimal 9 using a trace table 187-8 ethernet 43 executable files 88,89 expert systems 139 extreme test data 157-8 fans 5,6,7 fetch-decode-execute cycle 56,57-9 fields 297 file handling 286 reading from a file 286-8 writing to a file 288-9 file management 82 file size calculation 25-7 firewalls 112,114-15 firmware 81 floating gate 68,69 flow sensors 64 flowcharts 149-53 FOR (count-controlled) loops 197-8,231-4,240 format checks 175-6 Fortran 79 full-duplex data transmission 40,41-2 functions 255,257-60 gas sensors 64 global variables 260-1,262 graphical user interface (GUI) 82 graphics cards 7 396) hacking 112 half-duplex data transmission 40,41 hard drive 7,57,67-8 hexadecimal system 9,14 benefits of 16 conversion to/from denary 14-15 high-level languages 85,87 holographic data storage 69 HoloLens 384-5 humidity sensors 64 hypertext markup language (HTML) 98 hypertext transfer protocol (HTTP) 98 hypertext transfer protocol secure (HTTPS) 99-100 identifiers 198,267 IF statements 216,218-19,228-30 ELSE 220-1 ELSEIF 222-4 image representation 21-3 indices (singular: index) 270 variables as 273-4,279-80 inference engines 139 infra-red sensors 64 infrastructure 96 input devices 57,62 inputs 207-8 validation 357-8,362,367 writing code 357,366 instruction sets 58 integers 202,298 Integrated Development Environment (IDE) 90-1 intelligence 126 see also artificial intelligence interfaces 82 interference 38 internet 96 cookies 101-4 requesting and receiving web pages 97-100 web browsers 100-2 Internet of Things 55 internet protocol (IP) addresses 35,74-5 interpreters 88-9 interrupts 83,84 IPv4 and IPv6 addresses 74 iteration (loops) 231 in arrays 274-7,281-4 conversion between types of loop 240 count-controlled 231-4 post-condition loops 237-9 pre-condition loops 234-7 trace table 181-3 Index keys (encryption) 49-50 knowledge bases 139 length checks 173--4 LENGTH command 245-6 level sensors 64 library routines 265 light sensors 64,65 linear search 159-61 local variables 260,261-2 logic circuits 334-8 creation for problem statements 347-8 logic expressions 327,328,329,331,332,333 creation for problem statements 347-8 for a logic circuit 337-8 logic gates 10,325-6 AND 327-8 NAND 330-1 NOR 331-2 NOT 326-7 OR 329 XOR 333 logical binary shifts 19-20 logical operators 216-17,305 loops see iteration lossless compression 27,28-9 lossy compression 27 LOWER command 250 low-level languages 85,86,87 machine code 86 machine learning 137-8 magnetic field sensors 65 magnetic storage 67-8 maintainable programs 267-9 malware 95-6,113-15 DDoS attacks 109-11 maximum values 170-1 media access control (MAC) addresses 16,73 memory RAM 6,57,66 ROM66 virtual 69-70 see also data storage memory address register (MAR) 57 memory data register (MDR) 58 memory management 83 metadata 22 microprocessors 56,127 minimum values 170 mnemonics 86 MOD 209,210,214 moisture sensors 65 motherboard 5 multiplication 212 multitasking 83 NAND gate 330-1 natural language interface 82 navigation 101 nested statements 251-5 network interface card (NIC) 72,73 networks 36,96 hardware 72-5 nibbles 25 NOR gate 331-2 normal test data 157-8 NOT gate 326-7 NOT operator 227 number systems binary 9,10-13 denary 10 hexadecimal 9,14-16 operating systems (OS) 80,81-3 optical drive 7 optical storage 67,68 OR gate 329 OR operator 227,308 ORDER BY 311 output devices 62-3 outputs 205-7 writing code 359-60,368 overflow errors 18 packet headers 35 packet sniffers 108 packet switching 36 packets 35 parallel data transmission 38,39 parameters 255, 262-5 parentheses (brackets) 214 parity check 45 passwords 107,112 validity checking 251 payloads 35 perceptual music shaping 27 peripherals 82-3 persistent cookies 103--4 pH sensors 65 pharming 116-17 phishing 117-18 pixels 21-3 plain text 49 397 ) ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK portable programs 85 post-condition loops 231, 237-9 power supply unit (PSU) 6 pre-condition loops 231, 234-7, 240 presence checks 175 pressure sensors 65 prettyprint 90 primary keys 299 primary storage 66 problem statements 347-8 procedures 255-7 processes 146 writing code 358, 362--4 program counter (PC) 57 program development life cycle 145 analysis 145-6 coding 157 design 146-55 testing 157-8 programming languages 79, 87, 197 high-level 85 low-level 86 programming scenario 354-5 method 1 355-65 method 2 365-73 protocols 97 proximity sensors 65 proxy servers 110 pseudocode 154-5 RANDOM 266-7 random access memory (RAM) 6, 57, 66-7 range checks 173 ransomware 113 read only memory (ROM) 66 real data type 202, 298 records 297 registers 10, 57, 58, 59 REPEAT.....UNTIL (post-condition) loops 237-9 resolution 22, 23 robots 132 uses of 132-5 ROUND 265-6 routers 36, 72, 73--4 rule bases 139 run length encoding (RLE) 28-9 run-time environments 90 sample rates 24 sample resolution 24-5 scope of a variable 260 search algorithms 159-61 398 ) search engines 100-1 secondary storage 66, 67 secure sockets layer (SSL) protocol 100, 109 SELECT case statements 224-6 SELECT.....FROM 302--4 SELECT.....FROM .....WHERE 305-6 combining conditions 307-8 values in or not in, a condition 309 selection 216 IF statements 218-24, 228-30 logical operators 216-17 trace table 179-80 self-driving cars 134 semiconductor chips 68 sensors 63-5, 127 sequence 214-16 serial data transmission 38-9 servers 70, 98 proxy servers 110 session cookies 103 simplex data transmission 40 single data type 202 smart devices 55 social engineering 119-21 software 80-1 malware 95-6, 109-11, 113-15 operating system 81-3 programming languages 79, 85-7 software updates 112 solid-state storage (flash memory) 67, 68 sorting algorithms 159, 161-6 sound sampling 23-5 spreadsheets 80 spyware 113 static IP 74, 75 stepping 91 string manipulation LENGTH 245-6 SUBSTRING 246-9 strings 202 structure diagrams 146-9 Structured Query Language (SQL) 302 COUNT 313-14, 315-17 ORDER BY 311 SELECT.....FROM 302--4 SELECT.....FROM .....WHERE 305-9 SUM 312-13, 314-15 subroutines 255, 269 functions 257-60 procedures 255-7 SUBSTRING command 246-9 subtraction 211-12 Index SUM 312-13, 314-15 symmetric and asymmetric encryption 49 system software 80 operating system 81-3 tables 297 tabs 101 temperature sensors 65 test data 157-8 testing 157-8 case study 382-3 timeout 47 totalling 167, 241-2 trace tables 179-83 finding errors in a program 187-8 finding the purpose of an algorithm 184-6 trailers (footers), data packets 35 transistors 69 translators 87-9 transmission media 72 transport layer security (TLS) protocol 100 trojan horses 113 truth tables 326-7, 328, 329, 330, 332, 333 creating logic expressions and logic circuits 339-46 creation for problem statements 347-8 Turing Test 136 two-step verification 107-8 type checks 174-5 Unicode 21 uniform resource locators (URLs) 97-8 universal serial bus (USB) interface 43-4 flash memory drives 68, 69 UPPER command 250 user accounts 83 user history 101 usernames 121 utility programs 80 validation 173-7, 357-8, 362, 367 variable watch windows 91 variables 198-9 assignment 198-201 scope 260-2 virtual memory 69-70 viruses 113, 114 visual checks 177 Von Neumann architecture 56 WannaCry malware 95-6 web browsers 80, 97 features of 100-2 web pages 96 web servers 98 websites 96 WHILE (pre-condition) loops 234-7, 240 wide area networks (WAN) 96 windows 101 word processors 80 world wide web 96-7 worms 113 XOR gate (EOR gate) 333 zombies 110 399 > ) CAMBRIDGE IGCSE™ & 0 LEVEL COMPUTER SCIENCE: COURSEBOOK > Acknowledgements The authors and publishers acknowledge the following sources of copyright material and are gratejitl for the permissions granted. While every effort has been made, it has not always been possible to identify the sources of all the material used, or to trace all copyright holders. If any omissions are brought to our notice, we will be happy to include the appropriate acknowledgements on reprinting Thanks to the following for permission to reproduce images: Cover Nerthuz/Getty Images; Inside Introduction Yuichiro Chino/GI; Flashpop/GI; Sompong Rattanakunchon/GI; Compassionate Eye Foundation/Robert Daly/GI; Monty Rakusen/GI; THOMAS SAMSON/GI; Justin Paget/GI; Deepblue4you/GI; Maximum PC Magazine/GI; Science Photo Library/GI; Mikroman6/GI; PC Format Magazine/ GI; Maximum PC Magazine/GI; OMAR TORRES/GI; PC Format Magazine/GI; Georges Mir/GI; Blackred/ GI; Chapter I KTSDESIGN/SCIENCE PHOTO LIBRARY/GI; Matejmo/GI; Fotosearch/GI; Chapter 2 Andrew Brookes/GI; shapecharge/GI; Westend61/GI; Carol Yepes/GI; Alengo/GI; Chapter 3 Viaframe/GI; AndreyPopov/ GI; Yod67/GI; Artiemedvedev/GI; fStop Images Caspar Benson/GI; Anthony Danielle/GI; Steve Russell/GI; Westend61/GI; Deepblue4you/GI; Zelma Brezinska/GI; Karl Tapales/GI; lvcandy/GI; Powerbeephoto/GI; Kittichai Boonpong/GI; Chapter 4 Andriy Onufriyenko/GI; Everett Collection/Shutterstock; Andrew Steele/GI; Mikimad/GI; Lushik/GI; MaIII Themd/Shutterstock; OMAR TORRES/GI; Daniel Acker/Bloomberg via GI; Science & Society Picture Library/GI; Chapter 5 Aaron Tian/GI; MoMo Productions/GI; Harry Kikstra/GI; zf L/GI; Fotograzia/GI; popjop/GI; Brian Killian/Wireimage/GI; MARK GARLICK/SCIENCE PHOTO LIBRARY/GI; Sorbetto/GI; Daniel Sambraus/GI; Sitthiphong/GI; ET-ARTWORKS/GI; Tommy/GI; Luis Alvarez/GI; Eternity in an Instant/ GI; Education Images/Universal Images Group via GI; Jakub Porzycki/NurPhoto via GI; Chapter 6 MR.Cole/GI; Science & Society Picture Library/GI; Construction Photography/Avalon/GI; Christopher Furlong/GI; Heritage Images/GI; Alexander Koerner/GI; Chris Hondros/GI; Scharfsinn86/GI; Smith Collection/Gado/GI; Bruce Bennett/ GI; SEBASTIEN BERDA/GI; Chapter 7 Rizky Panuntun/GI; Stanislaw Pytel/GI; mikroman6/GI; Chapter 8 Filo/ GI; Marc Volk/GI; Chapter 9 Yuichiro Chino/GI; PM Images/GI; Chapter 10 Nikada/GI; benimage/GI; Chapter 11 MarsYu/GI; Westend61/GI; Klaus Vedfelt/GI; Microsoft case studies SeventyFour/GI GI= Getty Images Images within case studies supplied by Microsoft Research, photos by Jonathan Banks for Microsoft. Microsoft product screenshots are used with permission from Microsoft. Microsoft is a registered trademark of Microsoft Corporation. Adobe product screenshot(s) reprinted with permission from Adobe. 400) anywhere and ✓ Supports the full Cambridge !GCSE, !GCSE (9-1) and O Level Computer Science syllabuses (0478/0984/2210) for examination from 2023 Has passed Cambridge lnternational's rigorous quality-assurance process ./ Developed by subject experts For Cambridge schools worldwide 1 1 11111111 ISBN 978-1-108-9151� 9 781108915 4