Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
170 views
Computer Science Textbook PDF
Uploaded by
Khaled Emam
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Computer Science Textbook.pdf For Later
Download
Save
Save Computer Science Textbook.pdf For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
170 views
Computer Science Textbook PDF
Uploaded by
Khaled Emam
AI-enhanced title
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save Computer Science Textbook.pdf For Later
Carousel Previous
Carousel Next
Save
Save Computer Science Textbook.pdf For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 408
Search
Fullscreen
AQAZ ‘Approved AQA AS and A Level __. Computer at mr ccreE = 7AQA AS and A Level Computer Science P.M. Heathcote R.S.U. Heathcote Published by PG Online Limited “The Old Coach House 35 Main Road Tolpudde Dorset 12 7Ew United Kingdom
[email protected]
woww.pgonline.co.uk 2016 PG ONLINEAcknowledgements We are grateful to the AQA Examination Board for permission to use questions ftom past papers. ‘The answers in the Teacher's Supplement are the sole responsiblity of the authors and have neither ‘been provided nor approved by the examination board. ‘We would also like to thank the following for permission to reproduce copyright photographs: Screenshots of Arriva Bus App © Arriva PL. Colossus photograph © The National Archives Google Maps ‘StreetView’ © Google 2015 ‘Screenshot from Roboform website © Roboform Alan Turing © By kind permission of the Provost and Fellows, King's College, Cambridge from Archives Centre, King’s College, Cambridge. AMT/K/7/12 ‘Trans-continental internet connections © Telegeography Internet registries map © Ripe NCC ther photographic images © Shutterstock Graphics: Rob Heathoote and Rager Stayte Cover picture © ‘South Coast Salling’ 2014 Cilon canvas 60x600m Reproduced with the kind permission of Heather Duncan. \wowheatherduncan.com Design and artwork by OnTrvee \wonw.on-three.com ‘Typeset by Chapter One (London Lid, lan Kingston Fst edition 2016, reprinted 2016, Api 2017, June 2017 ‘catalogue entry for this books svaabi fom the Brith Library ISBN: 978-1-910523-07-0 CCooyraht © PM Heatncate and RS. Heathcote 2018 ‘Alvights served [No part ofthis publication may be reproduced, stored in aretrival system, or transmitted Inany form or by any means without the prior writen permission of the copyright owner. Prat ana boul in Great BetaPreface ‘The aim of this taxtbook is to provide detailed coverage of the topics in the new AQA AS and A Level Computer Science specification. The book is divided into twelve sections and within each section, each chapter covers material that can comfortably be taught in one or two lessons. In the fist year of this course there willbe a strong emphasis on leaming to program. You will start by learning the syntax of your chosen programming language — that is, the rules of how to write correct, statements that the computer can understand. Then you will code simple programs, building up your skils to the point where you can understand and make additions and amendments to a program Consisting of several hundred lines of code. Sections 1 and 2 of this book can be studied in parallel wth your practical programming sessions. It will sive you practice in the skills you need to master. In the second year of this course the focus will turn to algorithms and data structures, covered in Sections 7 and 8. These are followed by sections on regular languages, the Internet and databases. Object Oriented Programming and functional programming are cavered in the final section, which describes basic theoretical concepts in OOP, as well as providing some practical exercises using the functional programming language Haskell. Lists, the fact-based model and ‘Big Data’ are all described and explained. Two short appendices contain A Level content that could be taught in the first year of the course as an extension to related AS topics. ‘The OOP concepts covered may also he helpful in the coursework element of the A Level course. Each chapter contains exercises and questions, some new and some from past examination papers. ‘Answers to all these ate available to teachers only in a Teacher's Supplement which can be ordered trom ur website www.pgonline.co.uk. Approval message from AQA This textbook has been approved by AGA for use with our qualification. This means that we have ‘checked that it broadly covers the speciication and we are satisfied with the overall quality, Ful details of ur approvall process can be found on our webste. We approve textbooks because we know howr important it is for teachers and students to have the right, resources to support their teaching and learning. However, the publisher is ultimately responsible for the editorial control and quality of this book. Pease note that when teaching the A Level Computer Science course, you must refer to AQAS specification as your definitive source of information. While this book has been writen to match the specification, it cannot provide complete coverage of every aspect of the course. ‘Awide range of other useful resources can ke found on the relevant subject pages of our website: www.aga.org.uk.Contents Section 1 Fundamentals of programming Chapter 1 Programming basics 2 Chapter 2 Selection 8 Chapter 3 Iteration 13 Chapter 4 Arrays 7 Chapter 5 — Subroutines 2 Chapter 6 Files and exception handling 29 Section 2 Problem solving and theory of computation 33 Chapter 7 Solving logic problems 34 Chapter 8 Structured programming 39 Chapter 9 Writing and interpreting algorithms 42 Chapter 10 Testing and evaluation 48 Chapter 11. Abstraction and automation 52 Chapter 12 Finite state machines 60 Section 3 Data representation 67 Chapter 13 Number systems 68 Chapter 14 Bits, bytes and binary 72 Chapter 1 Binary arithmetic and the representation of fractions 7 Chapter 16 Bitmapped graphics 83 Chapter 17 _ Digital representation of sound 88 Chapter 18 Data compression and encryption algorithms 93Section 4 Hardware and software 99 Chapter 19 Hardware and software 100 Chapter 20 Role of an operating system 103 Chapter 21. Programming language classification 106 Chapter 22 Programming language transiators 110 Chapter 23 Logic gates 14 Chapter 24 Boolean algebra 118 Section 5 ‘Computer organisation and architecture 125 Chapter 25 Internal computer hardware 126 Chapter 26 The processor 132 Chapter 27 The processor instruction set 138 Chapter 28 Assembly language 142 Chapter 29 _Input-output devices 148 Chapter 30 Secondary storage devices 154 Section 6 Communication: technology and consequences. 158 Chapter 31_Communication methods 159 Chapter 32 Network topology 164 Chapter 33. Ciient-server and peer-to-peer 168 Chapter 34 Wireless networking, CSMA and SSID 474 Chapter 35 Communication and privacy 176 Chapter 36 The challenges of the digital age 179Section7 Data structures 187 Chapter 37 Queues 188 Chapter 38 Lists 194 Chapter 39 Stacks 198 Chapter 40 Hash tables and dictionaries 202 Chapter 41 Graphs 207 Chapter 42 Trees ait Chapter 43 Vectors 217 Section 8 Algorithms 223 Chapter 44 Recursive algorithms 224 Chapter 45 Big-O notation 229 Chapter 46 Searching and sorting 235 Chapter 47 _Graph-traversal algorithms 243 Chapter 48 Optimisation algorithms 249 Chapter 49 Limits of computation 254 Section9 Regular languages 259 Chapter 50 Mealy machines 260 Chapter 51 Sets 265 Chapter 52 Regular expressions 269 Chapter 53 The Turing machine 273 Chapter 54 Backus-Naur Form 278 Chapter 55 Reverse Polish notation 283Section 10 ‘The Internet 287 Chapter 56 Structure of the Internet 288 Chapter 57 Packet switching and routers 292 Chapter 58 _ Internet security 294 Chapter 59 TCP/IP, standard application layer protoco!s 300 Chapter 60 IP addresses 307 Chapter 61 Client server model 313 Section 11 Databases and software development 318 Chapter 62 _ Entity relationship modeling 319 Chapter 63 Rolational databases and normalisation 323 Chapter 64 Introduction to SQL. 330 Chapter 65 Defining and updating tables using SQL 336 Chapter 66 Systematic approach to problem solving 342 Section 12 OOP and functional programming 346 Chapter 67 Basic concepts of object-oriented programming 3a7 Chapter 68 Object-oriented design principles 353 Chapter 69 Functional programming 360 Chapter 70 Function application 367 Chapter 71 Lists in functional programming ani Chapter 72 Big Data 374 References 379 Appendix A Floating point form 380 Appendix B Adders and D-type flip-flops 387 Index 391villSection 1 Fundamentals of programming In this section: Chapter 4 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Programming basics Selection Iteration Arrays ‘Subroutines Files and exception handling 13 7 a1 20,‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING Chapter 1 — Programming basics Objectives © Define what is meant by an algorithm and pseudocode ‘+ Lear how and when oiferent datatypes are used + Leatn the basic arithmetic operations available ina typical programming language + Become fariar wth basic string handing operations + Distinguish between variables and constants What is an algorithm? An algorithm is a set of rules or a sequence of steps specitving how to solve a problem. A recipe for chocolate cake, a kriting pattern fora sweater or a sot of directions to get from A to B, are all algorithms of a kind. Each of them has input, processing and output. We will be looking in more detail at properties of algorithms in Section 2 of this book. In the context of programming, the series of steps has to be written in such a way that it ean be translated inte program code which is then translated into machine code and executed by the computer. Using pseudocode Whatever programming language you are using in your practical work, as your programs get more ‘complicated you will need some way of working out what the steps are before you sit down at the ‘computer to type in the program code. A useful tool for developing algorithms is pseudocode, which is «a sort of hallway house between English and program statements. There are no concrete tules or syntax for how pseudocode has to be written, and there are diferent ways of writing most statements. We will Use a standard way of writing pseudocode that translates easly into a programming language such as Python, Pascal or whatever procedural language you are leaming. This book does not teach you how to program in any particular programming language - you will learn how to write programs in your practical sessions — but it will help you to understand and develop your (own algorithms to solve problems.(CHAPTER 1 - PROGRAMMING BASICS. An introduction to pseudocode statements Input/output statements Most programs will have input and output statements to alow the user to enter data and display or print results. Here is the pseudocode for a simple example: OUTPUT "What is your name? " #idisplay text on the screen fwait for user input and assign the value to the variable myname myname € USERINPUT OUTPUT "Hello, ",myname ‘This program will ask the user to input their name, and then display ‘Hello, Jo* or whatever name the User entered. Notice that in this pseudocode, text such as “Hello,” will be wrapped in speech marks to distinguish it from variables, We will also use the pseudocode myname € USERINPUT "What is your name? " which combines the OUTPUT and USERINPUT statement to display the prompt "What is your name? * ‘and then wait for the user to enter text and press the ENTER key. Comments Note also that anything following a # willbe treated as a comment and will have no effect on the running, of the program. Comments are very important when you come to code your programs, to document the code (specifying the name, author, date written and purpose of the program, for example) and to explain how any tricky bits of the program work, Data types Al programming languages have built-in elementary data types. Different deta types are held diiferently in the computer's memory so you need to use the correct data type for the task. The most common data types include: © integer a whole number such as -25, 0, 9, 28679 © realfioat a number with a fractional part such as -18.5, 0.0, 3.142, 100.0001 © Boolean a Boolean variable can only take the value TRUE or FALSE + character a letter or number or special character typically represented in SCI, such as a, A, 7 or %. Note that the character "4" is represented differently in the computer from the integer 4 or the real number 4.0 * string anything enclosed in quote marks is a string, for example "Peter”, "123", or "This is a string’. Either single or double quotes are acceptable in many languages. Common arithmetic operations ‘The symbols +, -, "and / are used for the common arithmetic operations of addition, subtraction, multiplication and division. 2.9. Suppose the billin a restaurant comes to £20, and you want to civide it equally among 3 or 4 friends. bill € 20 billBetweené € bill/4 — willrotum the value 5 billBetween3 € bill/3 returns 6.666666667 poeSECTION 1 - FUNDAMENTALS OF PROGRAMMING $i In pseudocode you can assume that bi11Between3 will be automatically defined as a real variable and will store a value such as 6.686666867, though this may not be the case in every programming language. The Round function You can round this number using a function round, billBetween3 € round(billBetween3,2) #round to 2 decimal places This will oturn the value 6.67. The Trunc function ‘Some languages have a truncate or tzrunc function, which rounds a real number down to the nearest whole number. Exponentiation {you want to find, for example 2%, § is called the exponent and you need to use exponentiation, You can wite this operation in pseudocode as: x © 2885 or, using variables as: x € ytn Integer division and finding a remainder ‘Sometimes you may want to perform integer division and find a remainder. For example: Twenty apples are to be divided between 6 people. How many will each receive, and how many will be lft over? In this case you need to use the div operator to find the whole number of apples each person will receive, The mod operator will find the remainder. ‘These two operations are coded differently in different programming languages, but in pseudocode you ‘could write the following statements: apples € 20 applesPerPerson € 20 div 3 (witten applesPerPerson = 20//3 in Python) This willretum 6 in applesPerPerson. applesRemaining € 20 mod 3 (witten applesRemaining = 20%3 in Python) This willrotum 2 in applesRemaining.(CHAPTER 1 - PROGRAMMING BASICS. String-handling functions Programming languages have a number of bult-n sring-handling methods or functions. Some of the common ones in a typical language are: len (string) Returns the length of a string string. substring (index, index2) Retums a portion of string inclusive of the characters at each index position string. find (str) Determines if st occurs in a string. Returns index (the position ofthe first character in the string) if found, and -1 ‘otherwise. In our pseudocode we will assume that string(t) is the frst element of the string, though in Python, for ‘example, the first element is string(0) ord (va) Retutns the integer value of a character (97 in this example) che (97) Returns the character represented by an integer (var in this exarnple) To concatenate or join two strings, use the + operator, e.g. “Johnny” + "Bates" = “JohnnyBates” String conversion operations int ("0") ‘converts the character "1 tothe integer 1 ste (123) ‘converts the integer 123 into a sting "123" float ("123.456") ‘converts the string "123.456" to the real number 123.466 sex (123.456) converts the real number 123.456 to the string "12.456" date (year, month, day) returns a number that you can calculate with Converting between strings and dates is usually handled by functions built in to string brary modules, e.g, strtodate("01/01/2016"). Example: datel € strtodate ("18/01/2015") date? € strtodate ("30/12/2014") days € date - datez OUTPUT datel, date2, days ‘This will output 2015-01-18 2014-12-30 19‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING si Constants and variables ‘Some programming languages require you to declare all variables and constants before they are used in the program. For example: var totalMark: integer const VAT = 20.0 Variables are identifiers (names) given to memory locations whose contents will change during the course of the program: we have seen plenty of examples of these ~€.9. in the statement below, the variable myname will change according to what the user enters, myname € USERINPUT ‘You should always try to use meaningful names for variables, rather than x, y and z, as this helps to make the program easy to follow and update when required, ‘Some programming languages also allow you to define constants, whose value never changes while the program is being run. For example, if your program involved calculating the area of a circle, you could define pl at the start of the program as a constant having the value 9.14189, Or, you might hold the company phone number as a constant, declared at the start of the program as const companyPhone = "01453 123456" Advantages of using constants ‘The advantage of using a constant is that in a long, complex program there is no chance that a ‘programmer will accidentally change its valua by using the identifer for a different purpose. It also means that if the value of a constant (e.g. VAT) changes from say 20.0 to 17.5, the programmer does not have to hunt through the program to find al the lines where the value 20.0 has been used. In addition, using constants makas programming code more readable than using values. ‘Some languages such as Python do not require or even allow you to define variables or constants ~ you just use them as and when required in the program, 1. A-school keeps data about each of its pupils. State the most suitable date type for each of the following data items: Pupil's surname ‘Assingle letter indicating whether they are mele or female “The amount owed for school trips ‘The number of schoo! trips they have participated in ‘Whether or not the pupils entitled to free school meals 5) 2. (a) Write pseudocode for a program which asks the user to enter the total bil fora restaurant meal, and the total number of people who had a meal. The program should add 10% to the bil as a tio, ‘and then celculate and display to the nearest penny what each person owes, assuming the billis evenly spl. (6)(CHAPTER 1 - PROGRAMMING BASICS. Exercises continued {b) Complete the folowing table showing an addtional two sets of test data, the reason for each test and the expected result. a ‘Total amount exactly divisible by 700.00 ° number of people 11.00 (b) Name two ways in which you can help to make your programs understandable for another programme. a Imagine that you have had a stall at the Summer Fayre. At the end of the day you count up the number of each tp, 2p, 5p, 10p, 20p and S0p coins you have received. Wiite a pseudocode algorithm to allow the user to input the number of coins of each value, and to calculate and display the total takings. Make use of two ways of making the program understandable given in your answer to part (a). a) poe‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING 1-2 Chapter 2 — Selection Objectives + be able to use relational operators + be able to use Boolean operations AND, OR, NOT, XOR + bo able to use nested eelection statements Program constructs ‘There are just three basic programming constructs: sequence, selection and iteration. ‘Sequence is ust two or more statements folowing one afte the other, such as OUTPUT "Please enter a nunber: * fh € USERINPUT nsquared € n * n ‘The last statement is an assignment statement in which a value is assigned to a variable. In this chapter and the next, we will look at selection and iteration. Selection Selection statements are used to select which statement will be executed next, depending on some condition. Conditions are formulated using relational operators. Relational operators The following operators may be used in pseudocode for making comparisons: > greater than <_ loss than >= gfeater than or equal less than or equal = equal <> not equal Selection staterents can take different forms, for example: IF (expression!) THEN (do these statements) ENDIF Expression! is an expression involving a relational operator such as IF (AGE >=17) THEN canDrive € TRUE ENDIFCHAPTER 2~ SELECTION Ifexpreseioni does not evaluate to TRUE, control passes to the next statement atter the IF statement. Alternatively, you can specify what should happen if the condition does not evaluate to TRUE: IF (expression1) THEN (do these statements) ELSE (do these statements) ENDIF For example: IF mark >= 50 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" OUTPUT "You will have to retake this test." ENDIF ‘A nested’ selection statement may have another IF statement inside one or both of the code blocks for the cases of the outer IF IF (expression1) THEN IF (expression2) THEN (do these statements) ELSE (do these statements) ENDIF ELSE (do these statements) ENDIF Example 1 A bank offers different interest rates according to how much is in the account. There are three thresholds of £500, £3,000 and £10,000: If amount less than 500, rate = 1% If amount greater than or equal £500 but less than £3000, rate If amount greater than or equal £3000 but less than £10000, rat Ifamount greater than or equal £10000, rateis 3.5% ‘The selection statement can be written as follows: IF (amount < 500) THEN rate € 0.01 ELSE TF (amount < 3000) THEN rate € 0.015, ELSE IF (amount < 10000) THEN rate € 0.02 ELSE rate € 0.035 ENDIF 2% pod‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING The CASE statement ‘Some programming languages suppor the use of a CASE statement, an alternative structure to @ nested JF statement. tis useful when a choice has to be mace between several alternatives, Example 2 Periorm diferent statements according to an option choice entered by the user. CASE choice of 1: OUTPUT "You have selected option 1" (more statements here) 2: OUTPUT "You have selected option 2" (more statements here) 3: OUTPUT "You have selected option 3" (more statements here) ELSE, OUTPUT "You must enter 1, 2 or 3° ENDCASE Example 3 AA statement to calculate the number of days in each month between 2001 and 2099 may be written: CASE month of "gan", "Mar", "May", "Jul", "Aug", "Ock", "Dee": daysTaMonth € 31 ‘apr, "Jun", "Sep" daysinonth € 30 "peb": IF year MOD 4 = 0 THEN daysInYonth € 28 ELSE GaysTnMonth € 28 ENDIF 1-2 ENDCASE Boolean operators AND, OR, NOT ‘More complex conditions can be formed using the Boolean operators AND and OR, Example 4 IP (a > b) AND (a > ¢) THEN max € 8 ELSE IF (b> a) AND (b > c) THEN max €b BLSE max € ¢ ENDIF 10CHAPTER 2~ SELECTION Example 5 Write pseudocode for a program to allow the user to input the day of the week and output "Weekday" or "Weekend! day © USHRINPUT IF (day = "Saturday") OR (day = "Sunday") THEN OUTPUT "Weekend" ELSE OUTPUT "Weekday" ENDIF Example 6 ‘Atourist attraction has a daly charge for chidren of £5.00 on a wookday, or £7.60 on a weekend or bank holiday. Aduits are charged £8.00 on weekdays and £12.00 on weekends and bank holidays. Write pseudocode to allow the user to calculate the charge for a visitor. OUTPUT "Enter W for weekend, B for bank holiday or D for weekday" day € USERINDUT OUTPUT “Enter A for adult, ¢ for child" visitor € USERINPUT IF ((day = "W") OR (day = "B")) AND (visitor = "A") THEN charge € 12.0 ELSE IF ((day = "W") OR (day = "B")) AND (visitor = "C") THEN charge € 7.5 ELSE IF (visitor charge € 8.0 ELSE, charge € 5.0 ENDIF "A") THEN ‘The NOT operator ‘You can usually avoid the use of the NOT operator, replacing it with an appropriate condition, eg NOT (a = b) is equivalent to a <> b NOT (a ¢ b) is equivalent to a >= b The XOR operator XOR stands for exclusive OR, s0 that a XOR_b means “either a orb but not both’ This can be implemented with a combination of AND, OR and NOT consitions: (a AND NOT b) OR (NOT a AND b) Note that NOT takes precedence over AND. Add extra brackets if you are in any doubt! " pod‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING 1-2 12 Exercises 1. Below is a segment of an algorithm to determine at what times diferent members are allowed to use the competition pool at the local Sports Centre. owinPime € False IF (Membership = "Premier*) THEN ewimTime € TRUE ELS IF ((Menbership = "Adult") AND (Day = "Weekday") AND (Time < 1500)) oR (Membership = "Adult") AND (Day = "Weekend")) ‘THEN swimPime € TRUE ELSE IF (Membership = "Junior") AND (Day = "Weekend") THEN write down the values of ewinTime affer the segment of the algorithm has executed with the swinTime € TRUE ENDIF following data’ () Membership: Premier Day: Weokday (Membership: Adult Day: Weekday (i) Membership: Junior Day: Weekday Qu) Membership: Adult Day: Weekend () Membership: Adult Day: Weekday ‘Time: 1700 ‘Time: 1100 Time: 1000 Time: 0800 Time: 1530 5) 2. (@) Write a pseudocode algorithm for 2 program which calculates the cost of carpeting a room. The carpet is supplied in a roll 4m wide. The cost of the carpet is °10 por square metre. The program should ask the user to enter the longest dimension (length) and shortest dimension (width) of the room, then calculate and display the length and width and cost of carpet that wal, be suppiied. You can assume that the width of the room is not more than 4m. If width of more than Am is centered, display an error message and quit the program, The length could be more or less than 4m, (5) (©) Calculate the expected results for the following room sizes: Length =5, width = 3 Length =5, width = 4 Length width = 2 Length width = 2 Length width = 5 5)‘CHAPTER 3 ~ ITERATION Chapter 3 — Iteration Objectives + Understand and use tree diferent types of iterative statement WHILE, REPEAT and FOR + Be familar with, and be able to use, random number generation Performing a loop In the last two chapters we looked at sequence and selection statements. The third programming construct is iteration. iteration means repettion, so trative statements alvays invoWe performing a loop inthe program to repeat a number of statements. There are three diferent yp of loop to be considered, athough some programming languages do not implement al thre. + Indefinite iteration where the tration continues untl some spectied consiton is met, includes WHILE... ENDWHILE loops and REPEAT... UNTIL loops + Definite iteration, where the number of times the loop isto be executed is decided in advance, is implomented using FOR ... ENDFOR loop The WHILE ... ENDWHILE loop AWHILE ... ENDWHILE loop has two properties: ‘+ The expression controling the repetition of the loop must be of type Boolean ~ that is, one which evaluates to True or False ‘This expression is tested at the start of the loop ‘Ths Is best explained by means of an example. Suppose you wanted to input the daily maximum temperatures for one month, calculate and output the average of these measurements. ‘The program has to work for any month, 80 when you have entered all the temperatures you will enter 2 ‘dummy’ vaiue -100 to signify that there are no more temperatures to enter. ‘A first attempt at the pseudocode might look tke this: temp € 0 #initialise temp totaltemp € 0 #initialise total of temperatures numberOfTemps € 0 #initialise number of temperatures WHILE temp <> -100 OUTPUT "Enter next temperature" temp € USERINEUT totalremp € totalTemp + temp numberofTemps € numberofvemps + 1 ENDWHILE averageTemp € totalTemp/numberofTemps OUTPUT averageTemp 13SECTION 1 - FUNDAMENTALS OF PROGRAMMING Bo) 4 ‘Test this algorithm with temperatures 8, 12 and -100. We can draw a trace table showing the value of the variables as they change during execution of the program. 0 0 ‘TRUE 8 8 1 TRUE 12 20 2 TRUE ‘You should have ended up with 3 temperatures and an average temperature of -26.66667 instead of 10. The problem is that the expression controling the loop is tested only once each time round, at the beginning of the loop, and not atter each statement within the loop as it is executed. Therefore, we have to make sure that as soon as the number -100 is entered, the next thing that happens is that the Boolean expression is tested. totaltemp € 0 #initialise total of temperatures numberofTemps € 0 #initialise number of temperatures OUTPUT "Enter next temperature" temp € USBRINPUT input first temperature WHILE temp <> -100 cotalTemp € totalTenp + temp numberOfTemps € nunberOfTemps + 1 OUTPUT "Enter next temperature" temp € USERINPUT ENDWHILE averageTemp € totalTemp/nunberofTemps OUTPUT averageTemp Note that with a WHILE ... ENDWHILE loop, if the Boolean expression is TRUE at the start, the loop wil not be executed at all and control wil pass straight to the next statement after ENDWHILE. The REPEAT ... UNTIL loop This type of loop is very similar to the WHILE ... ENDWHILE loop, with the difference that the Boolean exoression controling the loop is written and tested at the end of the loop, rather than at the beginning. This means that the loop is always performed at least once,‘CHAPTER 3 ~ ITERATION Example 1 \Write pseudocode for a program which tests someone on the squares of numbers up to 25, program to test a user on the squares of numbers random(a,b) generates a random integer between a and b REPEAT mum € random (1,25) numequare € num * num OUTPUT "What is the square of ", num answer € USERINPUT() IF answer = numsquare THEN OUTPUT "Correct, well done" ELSE OUTPUT "No, it is ", numequare ENDIF OUTPUT "Another go? Answer ¥ or NY anotherGo € USERINPUT UNTIL (anotherGo = "N") OR (anotherGo = "n") The FOR ... ENDFOR loop ‘This type of loop Is useful when you know how many iterations need to be performed. For example, suppose you want to display the two times table: FOR count € 1 70 12 product € 2 * count ourpur "2 x", count, * ENDFOR product. ‘The value of count starts at 1 and is incremented each time round the loop. When it reaches 12, the loop terminates and the next statement is executed. Nested loops Loops can be “nested one inside another. Suppose we want to display all the multiplication tables. between 1 and 12, We can do this with two FOR loops, one inside the other. Example 2 FOR table € 1 TO 12 FOR count € 170 12 product € table + count OUTPUT table, " x ", count, " ENDFOR ENDFOR‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING Example 3 Use a random number generator to simulate throwing a di to find out how many throws it takes to get a 6 answer € ty" WHILE (answer = "y*) or (answer = nunberofThrows € 0 throw € 0 WHILE throw <> 6 throw © random(1,6) numberOfThrows € nunberOfThrows + 1 OUTPUT "You threw a ", throw ENDWHILE OUTPUT "That took ",numberOfThrows," throws* OUTPUT "Another go? (¥ or y)" answer € USERINPUT ENDWHILE Example 4 You can count backwards as well as forwards in & FOR ... ENDFOR loop. Here is a pseudocode program Which uses the ‘sleep’ methad to count down in seconds to blast-off. It uses a function called sleep which suspends execution for a given number of seconds: ReadyForCountdown € USERINPUT "Press enter when you're ready to start" FOR cece € 10 TO 0 STEP -1 ourpur secs sleep(1) #suspends execution for 1 second ENDFOR OUTPUT "BLAST-OFF! Exercises 1. Write a pseudocode algorithm to allow the user to input two integers highestNumber anc multip! ‘The program should output the results of multiplying integers 2, 3... highestNumber by multiplier. For example ifthe user enters 100 for jhestNumber and 7 for multiplier the program should ‘output the numbers 14, 21 ... 700. 5) 2. White pseudocode for a program that asks the user which times table they would like to be tested (on, and then gives them 5 random questions on this table. The computer should tell them each time whether they got the answer right or wrong, 6)(CHAPTER 4— ARRAYS: Chapter 4 — Arrays Objectives Be familiar with the concept of a data structure ‘Use 1- and 2-dimensional arrays in the design of solutions to simple problems Data structures A data structure is a collection of elementary data types such as integer, real, Boolean, char, and builtin methods to facilitate processing in some way. Computer languages such as Python, Pascal and \VB have some builtin structured data types such as string, array or list and record. Other data structures such as stacks and trees can be created by the programmer to suit a specific purpose. 1-dimensional arrays ‘An array is defined as a finite, ordered set of elements of the same type, such as integer, real or char. Finite means that there is a specific number of elements in the array. Ordered implies that there is a first, second, third etc, element of the array. For example, (assuming the first element of the array is myAxray [0] and not myarray [1]): myarray € (51, 72, 35, 37, 0, 3] x € myarray (2] fassions 35 to x Example ‘An array of strings could be used to hold the names of the birds, and an array of integers to hold the results as they come in. As a simple example we wil hold the names of & birds in an array: birdName € ["robin", "blackbird", "pigeon", "magpie", "bluetit", "thrush", "wren", "starling"] We can reference each element ofthe erry using an index. For example: birdWane [2] € "pigeon" #the index here is 2 Most languages have a function which will turn the length of an array, go that nunspecies € len(biraNane) will assign @ to nunspecies. 7‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING chy 18 To find at which postion of the array a particular bird is, we could use the following algorithm: bird © USERINPUT birdFound € FALSE numSpecies € len(birdName) FOR count € 0 TO numSpecies - 1 IF bird = birdName[count] THEN birdIndex € count birdFound € TRUS ENDIF ENDFOR IP birdFound = PALSE THEN OUTPUT "Bird species not in array" ELSE, OUTPUT "Bird found at", birdIndex ENDIF We need a second array of integers to accumulate the totals of each bird species observed. We can Initialise each element to zero. birdcount € [0,0,0,0,0,0,0,0] ‘To add 5 to the blackbird count (the second element inthe lst) we can write a statement birdcount [1] € birdcount [1] + 5 ‘The following algorithm enables a member of the Birdwatch team to enter results as they come in from members of the public. birdName € ["robin", "blackbird", "pigeo "thrush", "wren", "starling"] birdcount € [0,0,0,0,0,0,0,0] OUTPUT "Please input name of bird (x to end] bird © USERINPUT WHILE bird <> "x" birdFound € FALSE FOR count € 0 TO 7 IF bird = birdName [count] THEN birdFound € TRUE OUTPUT "number observed: " birdsObserved € USERINPUT birdcount [count] € birdCount [count] + birdsObserved ENDIF ENDFOR IF birdFound = FALSE THEN OUTPUT "Bird species not in array" ENDIF OUTPUT "Please input name of bird (x to end): " bird € USERINPUT ENDWHILE finow print cut the totals for each bird FOR count € 0 TO 7 ourPur birdName{count], birdcount [count] ENDFOR "magpie", "bluetit",(CHAPTER 4— ARRAYS: 2-dimensional arrays An array can have two or more dimensions. A two-dimensional array can be visualised as a table, rather like a spreadsheet. Imagine a 2-dimensional array called numbers, with 3 rows and 4 columns. Elements in the aay can be referred to by their row and column number, so that numbers [1] [3] = 8 in the example below. ‘An alternative syntax used in some programming languages is numbers [1,3] or numbers (1,3) Row 0 1 2 3 4 Row 1 5 6 7 8 Row 2 ° 10 11 12 Example Write @ pseudocode algorithm for @ module which prints out the quarterly sales figures (given in integers) for each of 3 sales statf named Anna, Bob and Carol, together with the total annual sales for al staff. ‘Assume that the sales figures are already in the 2-cimensional array quartersales. The staff names are held in a 1-cimensional array staf. staff © ["Anna", "Bob", "Carol"] quarterSales € [[100,110,120,110), (350,355, 360,360], (200, 210,220,220]) annualsales € 0 FOR 6 € 0 to.2 foutput staff name (insert statement here) FOR gq € 0 to? ourpur "quarter ",g, quartersales(s] [q] annualsales € annualSales + guarterSales{s] (ql ENDFOR ENDFOR OUTPUT “Annual sales for all staff: *,annualsales Arrays of n dimensions ‘Arrays may have more than two dimensions. An n-dimensional array is a set of elements of the same type, indexed by a tuple of n integers, where a tuple is an ordered list of elements. In a 3-dimensional amay x, a particular element may be referred to as x [4] [5] [2], for example. The first element would be referred to as x0] [0] [0] (assuming the array indices start at 0 and not 1).‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING chy Exercises 41. Referring to the BiedWatch program given earlier in this chapter: (@) Explain why the FOR ... ENDFOR loop repeated below is not the most efficient type of loop inthis situation ) FOR count € 0 to 7 IF bird = birdName {count} THEN birdFound € TRUE OUTPUT "number observed: * birdsObserved € USERINPUT bivdCount [count] € birdCount [count] + birdsObserved ENDIF ENDFOR (©) Rewrite the algorithm using a diferent type of loop. (3) 2. The birth weights in grams of 100 babies, which vary between 1600 to 4000 grams, are held in ananay weight ‘Write pseudocode for an algorithm which calculates the average birth weight, and then prints out the number of babies who are more than 500 grams below the average weight, together with the average weight of these, (5) 3. The marks for 3 assignments, each marked out of 10, for a class of 5 students are to be input into a two-dimensional array mark so that mark [3] [2], for example, holds the second mark achieved by the 4th student. Any missing assignments are given a mark of zero. Draw a table representing this array, and fil it with test data. 2 ‘Write a pseudocode algorithm which allows the user to enter the marks for the class. Calculate the average mark for each student, and the class average. (4) 4. Inacertain game, treasure is hidden in a 10x10 gtid. The grid coordinates are given by grid [row] [col] where grid 0] [0] represents the top left hand corner and grid [9] [91 the bottom right corner. The grid coordinates of the treasure are signified by a 1 at grid [row] [col]. All other grid elements are filed with zeros. What is the purpose of the following pseudocode algorithm? 2 FOR row € 0 TO 9 FOR col € 0 TO 9 IF grid{row] (col) = 1 THEN OUTPUT "row", row, "column", col ENDIF ENDFOR ENDFOR Write pseudocode statements to initaise the grid and “hide the treasure’ at a random location Inside the gti. (5)‘CHAPTER 5 - SUBROUTINES. Chapter 5 — Subroutines Objectives + Be familar with subroutines, thelr uses and advantages + Be able to use subroutines that return values tothe caling routine + Bo able to describe the use of parameters to pass data within programs + Bo able to contrast the use of local and global variables Types of subroutine A subroutine is @ named block of code which performs a specific task within a program. Most high-level languages support two types of subroutine, functions and procedures, which are caled in a slightly cifferent way. Some languages such as Python have only one type of subroutine, namely functions. ‘Al programming languages have ‘builtin’ functions which you will have already used if you have written ‘any programs. For example, in Python: print ("what is your nane? ") yName = input print (*Hello, ",myvane) age = input ("How old axe you? ") ‘A subroutine is called by wring ts name in a program statement. Some functions rtu a result, ke the we Snput function above, and some do not retun ary result, Ike the print function. Notice that th ast statement above combines the print and input functions; when the statement is executed, the computer will spay the question How old are you?" and walt forthe User fo input an answer, veh wl be assigned to the veriabe age. In languages which distinguish between functions and procedures, a function is called lke the input function above, always assigning a return value to a variable. A procedure is called by writing its name bbut not assigning the result to a variable, lke the print statement above. However, as we shall see later, a procedure can stil pass values back to the caling program if necessary. In Chapter 1, we listed some string-handling functions, and we can wit, for example, pseudocode such as x © int("s67") to call the int function, which will convert the string "567" into an integer. a4‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING poy 22 User-written subroutines You can write your own subroutines (tunctions and/or procedures) and call them from within the program {28 many times as needed. The subroutine (or subprogram) rst needs to be defined, typicaly above the Cade in the main program. Example 1 Using pseudecode, write a subroutine which displays a menu of 4 options in a game. SUB displayNenu #declare the subroutine OUTPUT "Option 1; Display rules" OUTPUT "option 2: Start new game" OUTPUT "option 3: Quit” OUTPUT "Enter 1, 2 or 3: " ENDSUB To call the subroutine from the main program, you simply write its name: displaywenu This subroutine always produces the same result whenever it is called: It simply displays this menu. Example 2 ‘Sometimes, you may want a subroutine to return a value to the main program: SUB getChoice OUTPUT "Option 1: Display rules" OUTPUT "option 2: Start new game* OUTPUT "option 3: Quit” OUTPUT "Enter 1, 2 or 3: " choice € USERINPUT RETURN choice ENDSUB ymain program starts here option € getChoice OUIFUT "You have chosen ", option In this example, when the program is run, the fist line to be executed isthe first statement in the main program, option € getChoice. The subroutine is called, it displays the menu, gets the user's choice In choice and retums this to the main program using the statement RETURN choice. Execution continues where it loft of, at the statement OUTPUT "You have chosen ", option. The subroutine is called in a slightly different way from the subroutine éigpayMenu - compare this to the two citferent ways in which buit-in OUTEUT and USERINPUT subroutines are called. OUTPUT "What is your name?" myName € USERINPUT OUTPUT "Hello, ", myName ‘The OUTPUT subroutine does not return a value, the USERINPUT subroutine doss.‘CHAPTER 5 - SUBROUTINES. Subroutines with interfaces Frequently, you need to pass values or variables to a subroutine. The exact form of the subroutine intertace vaties with the programming language, but will be similar to the examples below: SUB subroutineName (parameter, parameter 2,. ) ‘There are two mechanisms for passing parameters: by value and by reference. When parameters ‘are passed by value, changing a parameter inside the subroutine will not affect its value outside the subroutine, All parameters are passed this way in Python, In other languages auch as Vieuel Basic, the programmer can specify whether the parameter is to be passed by value or by reference. When a parameter is passed by reference, the address of the parameter, and not its value, is passed, so any change made to It in a subroutine willbe reflected in the calling program. Example 3 Consider a simple subroutine which calculates the volume of a cylinder. In the main program, the user is asked to enter values for the radius and length of the cylinder. These variables are then passed as Parameters to the subroutine for use in the calculation, The values (or addresses) of the parameters radius and Length inline 11 are passed to the subroutine where they ara referred to using the identifiers x and Len respectively. The order in which the parameters are written when caling the subroutine is important: radius is passed to r, Length is passed to Len. The return value vo! is passed back to the main program, where itis assigned to volume in ine 11. SUB cylindervolume(r, len) pi € 3,142 vol © pitrertlen RETURN vol ENDSUB main program ourpur vadius ourpur length, velune ourpur sgnter the radius of the cylinder:" © USERINPUD “Enter the length of the cylinder:" © USERINPUT € cylindervolume (radius, length] “The volume of the cylinder is ", volume 23 poy‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING poy 24 Local and global variables Variables used in the main program are by default global variables, and these can be used anywhere in the program, including within any subroutines. Within a subroutine, local variables can be used and these exist only during the execution of the subroutine. They cannot be accessed outside the subroutine ‘and changing them has no effect on any variable outside the subroutine, even ifthe variable happens 10 hhave the same name as the local variable. The ability to dectare local variables is very useful because It ensures that each subroutine is completely self-contained and independent of any global variables that have been declared in the main program. The principles of data hiding and encapsulation ofall the variables needed in a subroutine are very important in programming. A subroutine written according to these principles can be tested Independently, and used many times in many different programs without the programmer needing to know what variables it uses. Any variable in the calling program which coincidentally has the same name {6 a local variable declared in the subroutine will not cause an unexpected side-effect. Example 4 1 SUB printNunbers (x) 2 aea 2 bea 4 ces 5 OUTPUT "In the subroutine, a,b,c and x have values ", a,b,c,x 6 ENDsUB 7 tain program e ace s bes loces al x € 10 12 OUTPUT "In the main program, a,b,c and x have values ", a,b,c,x 13. printNumbers (x) 14 OUTPUT "In the main program, a,b,c and x now have values ", a,b,¢,x‘CHAPTER 5 - SUBROUTINES. Modular programming ‘When a program is short and simple, there is no need to break it up into subroutines. With a long, complex program, however, a ‘top-down’ approach, in which the problem is broken down into a number of subtasks, is generally very helpful in designing the algorithm for reaching a satisfactory solution, Programming with subroutines Using subroutines in a lage program has many advantages: +A subroutine is small enough to be understandable asa unt of code. itis therefore relatively easy to Understand, debug and maintain especialy i ts purpose is clearly defined and documented '* Subroutines can be tested independently, thereby shortening the time taken to get a large program working + Once a subroutine has been thoroughly tested, it can be reused with confidence in alerent programs or parts of the same program + In avery large project, several programmers may be working on a single progrem. Using a modular ‘approach, each programmer can be given a specific set of subroutines to work on. Ths enabies the winole program to be fished sooner + Alarge project becomes easier to monitor ancl control Example 5 ‘A proaramis to be written which simulates a dice game in which 2 payers take turns. The rules ofthe game are as folows: Payers take turns to throw two ce. I the throw isa ‘double’, Le. two 2s, two 3s, ete, the player's Score reverts to zor and their turn ends. the throw isnot a ‘double’, the total shown on the two dice is addd to tha players score. A playor may have as many throws as thoy like in any turn until they ether throw a douile or pass the dice. The fst player to reach @ score of 50 wins the game. \We il design the solution in a top-down manner. A fst attempt at sting the major tasks to be performed might be: REPEAT display the menu (display rules, play gane or quit) get the user's choice (1 to display rules, 2 to play, 3 to quit) call a routine to either display the rules, play the game or quit UNTIL the user chooses quit ourpur "Goodbye"SECTION 1 - FUNDAMENTALS OF PROGRAMMING ‘The major tasks can be spit into subroutines, which can each be tested independenty, We need the following subroutines: SUB menuChoice #display menu and get user's choice SUR displayRules SUB playGame Playing the game needs to be broken down further. At this stage we can start writing pseudocode for a subroutine playGame which will do the following: SUR playGame initialise scores of each player (scorei and score2) to zero ask for the players' names (playeri and playerl) WHILE scorel < 50 AND score? < 50 scorel € playerTurn (playert, score) # player 1's turn IF scorel >= 50 THEN OUTPUT "You win!" ELSE score2 € playerTurn (player2, score2) # player 2's turn IF score2 >= 50 THEN oureur "You wini" ENDIF ENDIF ENDWHILE ce ENDSUB Finally, we have to design the subroutine player Turn. This is incorporated into the pseudocode for the whole program, which is given below. In some languages it may be necessary to import a library containing the random function program to play a 2-player dice game SUB menuChoice OUTPUT "option 1: Display rules" OUTPUT "option 2: Start new game* OUTPUT "option 3: Quit” OUTPUT "What would you like to do?” choice € USERINPUT WHILE choice < 1 OR choice > 3 OUTPUT "That is not a valid choice." OUTPUT "Please enter a number hetween 1 and 3: " choice € USERINEUT ENDWHILE RETURN choice ENDSUB 26‘CHAPTER 5 - SUBROUTINES. subroutine to display rules SUB displayRules OUTPUT "The rules of the game are as follows: Players take turns to throw two dice. Tf the throw is a ‘double’, i.e. two 2s, two 3s, ete., the player's score reverts to zero and their turn ends fete.) ENDSUB Hsubroutine for each player to take a turn suB playerTurn (player, score) OUTPUT "Your turn, ", player anotherGo € "Y" scoreThisTumn € 0 WHILE anctherGo = "¥" OR anctherGo = "y" diel € random(1,6) call a built-in function diez € random(1,6) OUTPUT "You rolled ", diel," and", diez IF diel = diez scoreThisTurn € 0 cumulativescore € 0 OUTPUT "Bad luck! Press any key to continue" anyKey € USERINPUT accept any keypress from user anctherGe € "Nt ELSE scoreThisTurn € scoreThisTurn + diel + diez cumulativescore € score + scoreThisTurn OUTPUT "Your score this turn is ",scoreThisTurn OUTPUT player, "Your cumulative score is ", cumulativescore IF cumulativescore anotherGo € "N" ELSE OUTPUT "Ancther go? (Anewer ¥ or M)* anotherGo € USERINPUT ENDIF ENDIF ENDWHILE RETURN cumulativescore ENDSUB 50 THEN 2 poy‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING subroutine to play game SUB playGame scoral € 0 score2 € 0 OUTPUT "Enter Player i's name: playerl € USERINPUT OUTPUT "Enter Player 2's name: player2 € USERINPUT WHILE scorel < 50 AND score? < 50 scorel € playerTurn(playeri, score1) IF scorel >= 50 THEN OUTPUT "You win!" ELSE score? € playerTurn(player2, score?) IF score2 >= 50 THEN oureur "You wint" ENDIF ENDIF ENDWHILE ENDSUB ‘main program starts here option € menuChoice WHILE option <> 3 IF option = 1 THEN displayzules ELSE playGame ENDIF option € menuChoice ENDWHILE OUTPUT "Goodbye!" Exercises 11. Referring to the program code above, answer the following questions {@] Give one example ofa global variable and ane example ofa local variable used inthis program. Wrist good practice to use local variables whenever possible? 4) (©) Give one example of a parameter in this program. What is the advantage of using subroutines with parameters? (3) (6) The first statement in the main program is option € menuChoice Explain what this statement does. 2CHAPTER 6 — FILES AND EXCEPTION HANDLING Chapter 6 — Files and exception handling Objectives + define the terms fel, record, fle + be able to 1000 from and write toa txt fle + understand when and how to use exception handing in & program Fields, records and files It you want to store data permanently so that you can read or update it at a future date, the data needs to be storad in a fle on disk. The most common way of storing large amounts of data conveniently is to use a database, but sometimes you need to create and interrogate your own fles. Generally, a file consists of a number of records. A record contains a number of fields, each holding cone itern of data. For example, in a file holding data about students, you might have the following record, structure: 1453 Gemma Baines 01/05/2004 26 1768 Paul Gerrard 17/11/2003 2G 2016 Brian Davidson 03/08/2002, 3H ‘The tabla shows a file containing three records, each record having 5 folds. im some languages, a record structure will be declared in the folowing manner: student = Record integer ID string Firstnane string Surname date Dateofairth string Clase End Record This is an example of a user-defined data type. ‘Another way of storing a fle isto use text ile, described below. Writing to a text file Suppose that you want to write to a tex fle containing the names of birds seen and the numbers of each bird reported by an individual participating in the RSPB's Big Garden Birdwatch described in Chapter 4, page 17. You may be starting a new fle or appending data to an existing fle - there are ciferent ‘modes! in which a fle can be opened including read, write and append, We will assume that if you open the fle in ‘append! mode it will create a fe if one does not already exist in the folder. Programming languages have different syntax for writing to and reading from a file, but pseudocode for a program to write data to a new file would be something ike the following:‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING oe 30 OPEN birdFile to append data OUTPUT "How many records do you wish to write?" numRecs € USERINPUT POR n € 1 TO numRecs OUTPUT "Enter bird name: " birdName € USERINPUT OUTPUT "Enter number of birds reported: " birdsReported € USERINPUT WRITELINE (birdFile, birdName + birdsReported) ENDFOR CLOSE birdFile Reading from a text file ‘Some programming languages such as Python wil allow you to read an entire text fle using just a single ‘statement. You can also read a text file ine by line (or record by record). Each racord will have a number of fiotds commonly separated by commas, as in a CSV (comma-separated values) file ‘Suppose you want to search birdFile for a specific bird name and print out the number of birds. ‘Assume that this fle has 8 records. OPEN birdPile for reading OUTPUT "What bird ave you searching for? " birdNaneSearch € USERINPUT FOR n € 1708 READLINE (birdFile, n) fread the nth record split record into individual comma-separated fields birdName € field (0) birdsSeen € field(1) IP birdName = birdNameSearch THEN OUTPUT birdName, birdsseen ENDIF ENDFOR CLOSE birdFileCHAPTER 6 — FILES AND EXCEPTION HANDLING Overwriting text in an existing file Sometimes you may want to overwrite existing data; for example, to correct a record in the file In that case, you can open the record for both reading and writing, search through the file for the record you want, and write a new record in its place. Binary (non-text) files itis posable to read and write binary fles as wel as text fas, A binary fle can contain records with diferent types of fld such as string, integer, real, Boolean. Each ofthese fetds may ocoupy a diferent number of bytes; for example a real number stored as text may occupy 12 bytes for a 12-figure number, but considerably fewer as a pure binary number. Reading a binary file is lanquage-specific but always involves knowing exactly what each field type in the record is and how many bytes t occupies. The fle needs to be opened ina moda which species that isa binary fle, Exception handling itis @ good idea to include in your programs some exception-handling routines to specty what should happen ian error occurs that would normally cause the program to crash. Common erors of this sort include + trying to read non-existent fe + trying to convert a non-numeric sting entered by the user, to anintagor or a real number + trying to perform calculations with a non-numoie variable '* division by zero Most languages provide an easy way of handing exceptions with a txy.except clause. Here are three examples: Example 1 TRY OPEN birdFile for reading EXCEPT OUTPUT ("Sorry, can’t find this file") ENDEXCEPT Example 2 Blow is an example ofa validation routine that could be used inthe program shown inthe last chapter to simulate a simple dice game. 3‘SECTION 1 - FUNDAMENTALS OF PROGRAMMING oe SUB menuchoice OUTPUT "option 1: Display rules" OUTPUT "Option 2: Start new game* OUTPUT "option 3: Quit” OUTPUT "What would you like to do? " choice € USERINPUT WHILE choice < *: TRY choiceAsinteger € int (choice) #try to convert string to integer EXCEPT OUTPUT "That is not an integer!" ENDEXCEPT 4 The user entry may be an integer but not between 1 and 3.. OUTPUT "Please try again. enter a number between 1 and 3: " choice € USERINEUT OR choice > ENDWHILE RETURN choiceAsInteger ENDSUB Example 3 ‘This example shows the use of TRY... EXCEPT... BLS. n € 10 TRY birdRec = READLINE(birdFile, n) EXCEPT OUTPUT "Attempt to read beyond end of file" ELSE, split record into individual comma-separated fields Ry birdsSeen € int (field[1]) #convert string to integer EXCEPT birdsSeen = 0 OUTPUT "This is not an integer" ELSE cotalBirdsSeen € totalBirdsSeen + birdsSeen ENDEXCEPT ENDEXCEPT Exercises 4. Wite pseudocode for a program which reads a text fle containing the current highest score for a game. Compare the current highest with a variable called myscore and if myscore jis greater than the one on the file, replace the record with the new high score. 5) 2. (a). Explain with the aid of an example, the purpose of exception-handling in programs involving file handling 2) (©) Explain why exception-handiing routines are useful for validating data input by the user. (3) 92Section 2 Problem solving and theory of computation In this section: Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Solving logic problems ‘Structured programming Wiring and interpreting algorthms Testing and evaluation Abstraction and automation Finite state machines 34 20 42 48, 52 60 33‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION 27 34 Chapter 7 — Solving logic problems Objectives * Define the stages of systems development ‘+ Be able to develop solutions to simple logic problems '* Be able to check solutions to simple logic problems: Stages in software development Software isthe name given to any program vrtten forthe computer ‘There are several well-defined stages in wiring software, once your programs progress past the trivial ‘and become more challenging. The stages are: HE Briefly, the tasks performed at each of these stages are: ‘+ Analysis: the requirements and goals of the project must be established, and a data model created. ‘The needs of the end user are considered, and alternative solutions to the problem may be suggested ‘+ Design: data structures will be specified, algorithms, user interfaces, screen designs and reports will all be designed ‘+ Implementation: the program code is written + To: 1e whole system must be tested for the presence of errors, using selected tast data covering normal, boundary and erroneous data * Evaluation: the system is evaluated according to given criteria lis not necessary or even desirable that one phase is finished before another stats. In an evolutionary prototyping approach, some parts ofthe design, such as the user interface, may be implemented and shown to the customer, who then gives feedback. I itis not what they wanted, further work is done on the design. Testing may begin on parts of the implementation before other parts are completed, At each stage, it may be necessary to revisit previous stages. Customer feedback at every stage is crucial for successful project development.CHAPTER 7 ~ SOLVING LOGIC PROBLEMS. We will go through the frst four of these stages in this Section, starting with some problem-solving ‘exercises which will get you thinking creatively about how to solve problems ~ a useful skill for analysing a problem and designing a solution. The typas of problems we willbe looking at are “computational” rather than “data-processing” problems. Problem-solving Solving logic problems is good training for "computational thinking” basically, the ability to think logically about a problem and apply techniques for solving it. This is closely related to the skill of designing algorithms which can be turned into computer programs. This chapter is designed to get you thinking about developing and checking solutions to simple logic problems. (Solutions to the example problems are given at the end of the chapter) (One type of problem asks you to find a method of solving a problem which has a goal and a set of resources, as in Question 1. Q1: There are two jugs, A and B. Jug A has a capacity of three litres. Jug B has a capacity of five litres. There are no markings on the Jugs, so it is not possible to tell exactly how much Is in a jug just by looking at it, unless itis full or empty. There is a sink with ‘a water tap and a drain. How can exactly one litre of water be obtained from the tap using the two jugs? Tip: Create a table lke the one below with 3 columns headed Step, A (3 litres), B (5 litres), and several blank rows. Write the contents of each jug after each step. Step | A(litres) | BG litres) 1 3 0 2 etc ‘Some problems require you to work out a method of solution and use the clues to find the answer, as in the following problem. An example of this type of problem is shown below Q2: The police are interrogating five suspects after a bank robbery. Each of them makes two statements, but it tums out only five of these statements are true. Can you work out who committed the crime? What strategy will you use to work it out? Alan said: It wasn't Ben. It was Cart. Ben said: It wasn't Alan. It was Dave. Carl sai wasn't Dave. It wasn't Ben, either. Dave said: It wasn't Eddie. It was Alan, Eddie said: It wasn't Caf. It was Dave. Tip: What is the key fact given in the statement of the problem? 35 27re 36 ‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION Example 3 is a classic logic problem, wich has many different variations on the same theme, Strategies for problem solving There are some general strategies for designing algorithms which are useful for solving many problems in computer sclonce, First of alt is usetu to note that there are two types of algorthmic puzzle. Every puzze has an input, which defines an instanee of the puzzle, The instance can be either specific (€.g. fill a magic square with 3 rows and 3 columns), or general (n rows and n columns). Even when, aiven a general instance of a problom, itis often helpful to solve a speci instance of it, which may ive an insight into solving @ more general case Exhaustive search For example, suppose you are asked to fil a ‘magic square’ with 3 rows and 3 columns with distinct Integers 1-9 so that the sum of the numbers in each row, column and corner-to-comer diagonal is the same, This is a specific instance of a more general problem in which there are n rows and n columns. Some problems can be solved by exhaustive search — in this examoie, by trying every possible combination of ‘numbers. We can put any one of 9 integers inthe frst square, and any ofthe remaining 8 in the second square, giving 9x8 = 72 possibillies for just the first two squares. There are Qx8x7x6x5x4x3x2 = 362,880 ‘ways of filing the square. f you are a mathematician you wil know that this is denoted by 9, spoken as “nine factoria", You might think a computer could do this in a fraction of a second. However, looking at the more general problem, where you have n x n squares, you wil find that even for a 5 x § square, there are so many diferent combinations (25! or 25 factorial) that it would take a computer performing 10 tilion operations a second, about 49,000 years to find the answer! So, to solve this problem we need to come up with a better algorithm. It tums out to be not very difficuit {0 work out that for a 3x 3 square, each row, column and diagonal must add up to 18 and the riddle ‘number must be 5, which considerably reduces the size of the problem. (The details of the algorithm are not discussed here.)CHAPTER 7 ~ SOLVING LOGIC PROBLEMS. Divide-and-conquer To find a particular item in a sorted lst, one strategy is to 100k at every item starting from the beginning Lnti you find what you are looking for (the exhaustive search strategy). A far more efficient strategy is to perform a binary search: Step 1: Look at the midale item of the lst first. if this isthe item being sought, stop searching Stop 2: Otherwise, if the middle item is greater than the one being sought, the item you are looking for ‘must be in the first half of the list so you can discard the second half. Otherwise, discard the first half of the list Step 3: Repeat with the new lst until the item Is found, ‘Sometimes a problem requires a flash of insight to solve. if you have seen the flim “The Imitation Game" about Alan Turing and how he cracked the Enigma Code during World War I you will recall his insight in realising that most messages ended with the words “Hell Hille. This proved crucial in reducing the ‘exhaustive search algorithm, which could never provide the solution in the 24 hours before the code was changed, to one which the code-breakers used to decode the messages every day. Solutions to examples 1: Fill the S-itre jug and pour it into the S-litre jug. Then refil the G-litre jug and pour 2 litres Into the 5-lire jug to fit. What remains in the 3-litre jug is 1 tre, 2: If Alan did it, that means that 6 of the statements are true. Try out each person in turn. Eddie is the only one who fits the criterion that exactly 5 statements are true. (This is the key fact) @3: The man and the chicken cross the river, (the fox and corn are safe together). He leaves the chicken on the other side and goes back across. The man then takes the fox across the river, and since he can't leave the fox and chicken together, he takes the chicken back with him. Then, since the chicken and corn can't be left together, he leaves the chicken and he takes the corn across and leaves it with the fox. He then returns to pick up the chicken and heads across the river one last time. 37 27‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION 27 38 Solutions to examples continued Exercises 41. Three days ago, yesterday was the day before Sunday. What day wilt be tomorrow? 2. There are two martied couples who need to cross a river. They have a boat that can hold no more than two people at a time. The husbands insist that at no time can thelr wives be lett alone in the company of the other man. How can they cross the river? 3. You have an 8-pint jug ful of water, and two empty jugs of 5- and S-pint capacity, How can you get exactly 4 pints of water into one of the jugs by completely filing up and/or emptying jugs into others? 4, The following problem has become very popular since it is reputed to have been set to candidates during job interviews at Microsoft. ‘A group of four people, who have one torch between thom, need to crs a rickety bridge at night ‘A maximum of two people can cross the bridge at one time, and any party thal crosses (ether one Cr two people) must have the torch with them. The torch must be walked back and forth ~it cannot be thrown. Person A takes one minuto to crass the bridge, person 8 takes 2 minutes, person C ‘takes § minutes and person D takes 10 minutes. A pair must walk together atthe rate ofthe slower person's pace. Find the fastest way they can accomplish this task.(CHAPTER &~ STRUCTURED PROGRAMMING Chapter 8 — Structured programming Objectives + understand the structured approach to program design and construction + be abe to construct and use hierarchy charts when designing programs + be abe to explain the advantages o the structured approach The structured approach ‘The structured programming approach aims to improve the clarity and maintainability of programs. (See Chapter 5, page 25, "Programming with subroutines") Using structured programming techniques, ony three basic programming structure are used ‘= sequence ~ one statement following another ‘© selection —IF ... THEN ... ELSE... ENDIF and CASE ... ENDCASE statements ‘Iteration - WHILE ... ENDWHILE, REPEAT... UNTIL and FOR ... ENDFOR loops Languages such as Python, Pascal and Cit are block-structured languages which allow the use of just thtee types of control structure. They may allow you to break out of a loop, but ths is not recommended in structured programming. Each block should have a single entry and exit point. Block-structured languages Abiock is a section of code consisting of one or more statements. For example, a block may be a single IF ... ENDIF statement, with the beginning of the block denoted by, for example, the keyword IF or an opening curly bracket, and the end denoted by either the end of indented code, (as in Python), a curly bracket or a keyword such as END or ENDIF Ablock may also be a subroutine such as a function or procedure. Another important aspect of structured programming is to keep subroutines independent of the program which calls them, which ‘means that they should not make use of global variables. Any variable declared in the main program should be passed as a parameter to a subroutine iit is needed, Designing structured programs Top-down design is the technique of breaking down a problem into the major tasks to be performed; each of these tasks is then further broken down into separate subtasks, and so on until each subtask is suffciontiy simple to be written as a self-contained module or subroutine. Remember that some programs contain tens of thousands, or even millions, of lines of code, and a strategy for design is absolutely essential. Even for small programs, top-down design is a very useful method of breaking down the problem into small, manageable tasks. 39‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION Advantages of structured (modular) programming ‘The advantages of thes structured approach may be stated as: ‘+ Individual modules can be separately tested ‘+ Modules can be kept in a module library and roused in other programs ‘+ Large programs can be spit nto modules that are easier to read, debug and maintain ‘+ Several programmers in @ team can work on separate modules, thus shortening development time for a large project Hierarchy charts Anierarchy chart is a tool for representing the structure of a program, showing how the modules relate to each other to form the complete solution. The char is depicted as an upside-down tee structure, with ‘modules being broken down further into smaller modules untl each module is only afew lines of code: (never more than a page). Example 1 Draw a hierarchy chart for @ program which calculates and prints @ customer's monthly gas bil. ‘This can be broken down into several steps. ‘Caleulate units used! and ‘Calculate total bil’ may now be further broken down. one cS Pere] coer ear(CHAPTER &~ STRUCTURED PROGRAMMING Limitations of a hierarchy chart Note that a hierarchy chart does not show the detailed program structures required in each module for example, it does not show selection and iteration. A greater level of detail may be shown in a structure chart but these are not covered here. Example 2 Draw a hierarchy chart for @ program which asks the user which times table they would lke tobe tested (on, and then cisplays five questions, getting the user's answer each time and teling them whether they wete right or wrong. I they are wrong, the correct answer is displayed, Exercises 1. Using local rather than global variables in subroutines is one way of helping to make a program easy to maintain (i) Explain why this is the case. (3 (i). Describe briefy three othor ways in which a program can be made easy to understand and maintain, (6) 2. Draw a hierarchy chart for a quiz program which does the folowing: ‘+ asks the user 10 random multiple-choice questions from a bank of 100 questions held in a file ‘ifthe user gives the correct answer, gives feedback and adds 1 to the user's score + ifthey give the wrong answer, gives feedback and displays the correct answer + atthe end of the questions, gives the score out of 10 ‘+ asks if they want another 10 questions fa‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION 42 Chapter 9 — Writing and interpreting algorithms Objectives + To understand the term ‘algorithm’ * To lear how to write and interpret algorithms using pseudocode Properties of an algorithm A recipe for chocolate cake, a knitting pattern for a sweater or a set of directions to get from A to B, are all algorithms of a kind. Computational algorithms ‘The definition of an algorithm is: + thas clear and precisely stated steps that produce the correct output for any set of veld inputs ‘= Itmust always terminate at some point ‘A.good algorithm also has the folowing properties: ‘It should alow for vais inputs + Itshould execute efficiently in 2s few steps as possibie + should be designed in such a way that other people willbe able to understand itand mocity ititnecessary What kinds of problem are solved by algorithms? ‘There are thousands of diferent practical applications of algorithms. Some of the best-known applications include: * Internet-related algorithms. Algorithms are used to manage and manipulate the huge amount of data stored on the Internet. How does a search engine find all the pages on which particular information resides in a fraction of a second? + Route-finding algorithms. Given two locations, how does a route-iner determine the shortest or best route betwoen the two points? There may be thousands of possible routes. This ype of algoritnfs used not only for diving a vehicle from Ato B, but also for many other applications, for example, finding the best route to transmit packets of data from A to B over a network ‘+ Compression algorithms. These are used to compress dat files so that they can be transmitted faster or held in a smaller amount of storage space. For example, MPS files are compressed so that you can hold thousands of tracks on a mobile phone + Encryption algorithms. When someone purchases something over the Internet and sends their credit card number and other personal details te the tore, the data needs to be encrypted so that even itis intercepted, it cannot be read‘CHAPTER Q~ WRITING AND INTERPRETING ALGORITHMS Asimple computational algorithm ‘Suppose you are given the square of an integer and you need to tind the integer itself (.¢, the square root of the given numb), Your calculator can add, subtract, mutioly anc dvide but it does not have a square root function, Here is one way of finding the square root of the integer number: 1ne€o vinitialise n 2 nequared € ntn 3. Is nsquared = number? 4 If yes, output n. If no, add 1 to n and repeat from step 2 ‘When you start to program, itis tempting to get straight to the computer and type in some code to solve a given problem. However, it will generally save time to figure out the steps needed using paper and pencil before you start coding using pseudocode. Pseudocode is a way of expressing the solution in @ way that can easily be transiated into a programming language. ‘The algorithm described will do the job, but a better solution is based on the well-known binary search algorithm, which we looked at briefly in Chapter 7, Question 6. A “Divide and Conquer” algorithm ‘This algonthm uses the “Divide and Conquer" strategy to halve the search area every time a quess is made. It goes lke this: 1, Set low € I, high € number, guess € (low + high) /2andnsquared € guess* 2, Ifnsquared > number, set high € guess to eliminate the top half of the range, otherwise set Low € guess to eliminate the bottom haif of the range 3, Set guess € (low + high) /2andasquared € guess* 4, Popeat stops 2 and 3 until nquarea = number out 43‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION ‘The chart represents the blocks of program code that we will use to solve the problem. The solution is short, so it's not necessary to put each block in a separate subroutine, number € 19321 low € 1 high € number guess € int((low + high) / 2) nequared € guess ** 2 BLOCK 1 SEQUENCE WHILE nsquared <> number IF nsquared > number THEN high € guess ELSE low € guess ENDIE guess € int((low + high) / 2) squared € guess ** 2 BLOCK 2 ~ TTERATION ENDWHILE OUTPUT "Square root is ",quess BLOCK 3 - SEQUENCE Sorting algorithms Sorting isa very common task in data processing, and fraquenty the numberof tems may be huge, 50 using a.good algorthm can considerably reduce the time spent on tha task. There are many ofcient sorting algorthms such as quicksort and merge sort but you vil not be required to use these in this course, s0 we wil look ata simple but rather inefficient sort algorithm as an example, Bubble sort ‘Tho Bubble sot is one ofthe most basic sorting algorithms and the simpst to understand. The basic ‘idea is to bubble up the largest (or smallest) item, then the second largest, then the third largest and 30.00 untl no more swaps are needed. ‘Suopose you have an erray of nitems: + Go through the array, comparing each item withthe one nex oi. tis greater, swap them © The last item in the array will be in the correct place after the first pass + Ropeat n - 1 times, reducing by one on each pass, the number of items to be examined‘CHAPTER Q~ WRITING AND INTERPRETING ALGORITHMS Example 1 \Write pseudocode for a bubble sort to sort the numbers 45, 62, 19, 98, 9, 50 into ascending sequence. Print the numbers efter each of the 6 passes through the list numbers € [45,62,13, 98, 9,50] nunTtens € len (numbers) fget number of items in the array FOR i € 0 TO nunttens - 2 FOR j € 0 TO numItems - i - 2 IP numbers (j] > numbers(j + 1) THEN # Swap the nunbers in the array temp € numbers{i] numbers (j] € numbers(j + 1] aunbers(j + 1) € temp ENDIF ENDFOR OUTPUT numbers ENDEOR It you run this program, the output is (45, 13, 62, 9, 60, 98] [13, 45, 9, 50, 62, 98] [18, 9, 45, 50, 62, 98] (9, 13, 45, 50, 62, 98] [9, 13, 48, 50, 62, 98] Interpreting programs ‘A.usetul skill is to be able to Iook at someone else's program and decide what it does and how it works. Of course, ifthe programmer has putin lots of useful comments, used meaninglul variable names and spl a complicated program into separate modules, that should not be too dificut! Strategy for interpreting programs. Here are some tins, which may seem fairly obvious. 1, Read the comments in the program Look at the variable names to see if they give any clues Follow the steps in the program ~ the one botow starts withthe statement shift € 3 Trya “dy run" with some test data 45‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION Evaluating a program When two programs written to solve the same problem are not the same, is one program better than the other? it may be that one program is well documented with comments, uses meaningful variable names ‘and property indented code, does not contain statements that are not needed, and uses a more efficient algorithm, Once @ program has been waitten and tested, you need to be able to: * articulate how it works * produce test data and results to snow that it works correctly * get user feedback to show that nothing has been omitted, that it performs all the required tasks and does so efficiently Q7: What will be the output from the algorithm below if the user inputs “Hi, Jo!” Explain brietly the purpose of the algorithm. SUB code (message, shift) message € lowercase (message) codedMessage € "* FOR x IN message IF x IN Yabedefghijkimnopgrstuvuxy2" THEN num € ord (x) # convert to ASCIT value nun € num + shift IF num > ord("2") THEN # wrap if necessary num € num ~ 26 ENDIF char € chr (num) # convert back to character codedNessage € codedMessage + char ELSE, codedNessage € codedMessage + x ENDIF ENDFOR RETURN codedNessage ENDSUB # main program shift € 3 OUTPUT ("Enter your message: ") msg € USERINPUT codedMessage € code (msg, shift) OUTPUT ("The encoded message is: ", codedMessage)‘CHAPTER Q~ WRITING AND INTERPRETING ALGORITHMS Exercises 1. (@) Three types of programming constructs are sequence, selection and iteration. Describe what is meant by each of these. (b) A computer program cantains the folowing instructions: x€ 10 ¥€ 20 xey ourpur x, ¥ (0. State which of the constructs in part (a) has been used. (i) What willbe output by this code? 2, In.a football league, the resits of each match are input to the computer, which updates each team’s points In the case of a draw, each team (Team A and Team B) gets one point It Team A wins, then Team A gets 3 points and Team B gets no points. ‘The algorithm for updating points in the case of a draw is: IF TeamAGoals = TeamBGoals THEN TeamAPoints € TeamAPoints + 1 TeamBPoints € TeamBpoints + 1 EMI Witte an algorithm for updating the points if there is a winner. 3. Expert jugglers learn new juggling patterns according to certain rules represented by numbers, In this example, the rules for patterns of throe numbers aro: Rule 1: the total value of the numbers in the list must be a multiple of & Rule 2: No number must be one less than the previous number, even ifthe pattern 's repeated indefinitely. Here are some valid patterns of three numbers: 744 aay Here are some examples of invalid patterns with three numbers: 421 (44241 =7, which is not a multiple of 3, so does not obey rule 1) 651 (isone less than the previous number, so this does not obey rule 2) 627 (when this is repeated, 627 627 62 7... 6 is one less than the previous number, 0 this does not obey rule 2) (e) State why the following Iists of 8 numbers are not valid patterns of numbers, o 516 @ 442 (b) Write pseudocode for a program which: ‘Prompts the user to enter 3 numbers, one after the other + Qutouts “INVALID PATTERN’ if the sequence of numbers does not obey the two rules. (a) (1 O11 3] O ia} va ar‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION ro) 48. Chapter 10 — Testing and evaluation Objectives + Understand the purpose of testing ‘+ Dovise a tet plan © Select test data covering normal (typical), boundary and erroneous data + Chack an algorithm by completing a dry run * Know the criteria for evaluating a system The purpose of testing We have looked brielly at problem-solving strategies and the design of solutions using structured programming techniques. You wil have implemented several algorithms in your practical sessions. Testing your solutions for correctness can be a complex and time-consuming task, but one that needs tobe done thoroughly and systematically, ‘The purpose of testing is not to show that your program usually works correctly ifthe user is careful when entering input data, The purpose of testing is to try and uncover undetected errors. ‘Your program should work correctly whatever data is input. If invalid data is entered, the program should detect and report this, and ask the user to enter valid data. Some data may be valid, but may nevertheless cause the program to crash if you have not allowed for particular values. We need to choose test data that will test the outcome for any user input. To do this, we need to select normal, boundary and erroneous data, ‘+ normal data is data within the range that you would expect, and of the data type (teal, integer, string, etc.) that you would expect. For example, it you are expecting an input between O and 100, you should test 1 and 99 ‘+ boundary data is data at the ends of the expected range or just either side of it - for example -1, 0, 1,99, 100, 101. Test 0 and 100 to make sure that these give the expected results if the valid range is between 0 and 100 * erroneous data is data that is either outside an expected range, €.9. -1, 101 or is of the wrong data type — for example, non-numeric characters when you are expecting a number to be input For each test, you should specify the purpose of the test, the expected result and the actual result(CHAPTER 10 ~ TESTING AND EVALUATION Example 1 ‘The following program is intended to calculate and print the average mark for each student in @ class, for all the tests they have attempted: OUTPUT "How many students? " students € USERINEUD FOR n € 1 TO students OUTPUT “Enter student name" name € USERINEUT OUTPUT “Enter total marks for totalNarks € USERINPUT OUTPUT "How many tests has this student taken? * nunTests € USERINPUT averageMark € ROUND(totalMarks/numTests) OUTPUT "Average mark ",averageMark ENDFOR The test plan wil look something like this: Nunber of sudnts = 4 or 1 | tests 8 Nora ct, 8 8 Jo: total marks 27, tests 3 ‘ Norra da Tom: tia mars 3, 2 | Tem nowioperrenit | 8 8 rounded op G | Bat tear mats 28, [Normal data 5 5 tess rout rounded down Aina ial aS Pagan | Amn Noteststaen 0 Progen 5 | Numberotetucents abe |Testinetadata | Pear | You can probably think of some other input data that would make the program crash. For example, what ifthe user enters 31.5 for the total marks? The program should validate all user input, so some: ‘amendments will have to be made. Dry-runi 1g a program Auseful technique to locate an error in a program is to perform a dry run, with the ald of a trace table. {As you follow through the logic of the program in the same sequence as the computer does, you note down in the trace table when each variable changes and what its valus is. Examples of this are given in the exercises below.‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION ru) 50 Evaluating a computer system (Once a system has been written and thoroughly tested, the final stage is evaluation. This will take place ‘over a period of time, during which the user may run the new system in parallel to an old one. The criteria, that may be used for evaluation include: * Does it moet the performance criteria: ‘© Can it handle the amount of data or users that it needs to in a live environment? © Is the speed of operation satisfactory? + Does it always perform as expected? ‘+ Is the system reliable or does it crash at intervals? + Is the system easy to uso? ‘+ Is the interface pleasant to work with, all spelings correct, navigation simple and not ‘clunky’? ‘+ Has all the functionality documented in the original specification been implemented, or has one or more of the requirements been overlooked? ‘= Has it been well documented? * Willi be easy to maintain? ‘+ How far has the system been ‘future-proofed’ - wil t be easy to upgrade or add new features in the future? ‘+ How cost effective is the system - wil it increase ineome, decrease costs, or both?(CHAPTER 10 ~ TESTING AND EVALUATION Exercises 4. Complete the trace table below to show how esch variable changes when the algorithm is performed on the text data given. x€0 yeo 20 we & USERINEU? REPEAT kext yeyel w © USERINEU? unrin w <0 pexsy oureur 2 Tost data: 5 7224-1 8] 2. Explain what is meant by an algorithm. fl (One way of checking that an algorithm is correct is to complete a dry run. Dry run the algorthm below by completing the table below. a Assume that x has a value of 7. The oD operator calculates the remainder resulting from an intoger division, Answer € True FOR Count € 2 to (x-1) DO Remainder € x MOD Count IF Remainder = 0 THEN Answer € False ENDIF ENDEOR ‘Answer Count True = 2 ‘What is the purpose of this algorithm? (1 AQA Comp 1 Qu 5 June 2010‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION poke 52 Chapter 11 — Abstraction and automation Objectives + Describe the skis involv in computational thinking ‘+ Understand the concept of abstraction + Give examples ofcliferent types of abstraction + Doserbe the process of automation for sokng problems Computational thinking By this time, you are probably fairly clear about the idea of an algorithm and a problem which involves computation, But what is computational thinking? It is not about following an algorithm in one's head to carry out a mathematical task lke adding two numbers. Rather, itis about thinking how a problem can bbe solved, This involves two basic steps: ‘+ Formulate the problem as a computtional problem — potentially solvable using an algorithm other words, state it in such @ way that itis ‘= Try to construct an algorithm to solve the problem ‘A computational thinker will not be satisfied with any old algorithm, though; it must be a ‘good’ solution ~ that is, a correct and efficient solution. A programmer needs to be able to show that a solution is correct and efficient by using logical reasoning, test data and user feedback. Clearly, then, computational thinking is a vital ski for a programmer, and in fact it is not possible to be ‘programmer without It. It includes the abilly to think logically and to anply the tools and techniques of ‘computing to thinking about, understanding, formulating and solving probloms, Computing has been called the automation of abstractions, so let's move on to talk about abstraction. Abstraction Representational abstraction can be defined as a representation arrived at by removing unnecessary detats. Here are some examples of abstraction. ‘+ Any computer model, say of the environment, a new car of a fight simulator, is an abstraction. ‘+ Ifyou are planning to write a program for a game involving a bouncing ball, you will need to decide what properties of the bal to take into account. If i's bouncing vertically rather than, say, on a snooker table, gravity needs to be taken into account. How elastic is the ball? How far and in what direction wil t bounce when it hits an edge? What you are required to do is build an abstract model of a real-world situation, which you can simplify; remembering, however, that the more you simplify, the lass likely t becomes that the model will mimic realty.CHAPTER 11 ~ ABSTRACTION AND AUTOMATION ‘= A builder who is planning to build 100 houses on a new estate may use a physical model of the new estate, or in the first instance, a plan on paper or on a computer screen. In either case the model will bbe greatly simpifiad. All the houses may appear identical in the model. They may lack windows, doors Cor chimneys. All the trees in the model may be of identical size, colour and shape. ‘+ The map of the London Underground is a simple mode! of the actual geography of the Tube stations. ‘The map tells you what line each station is on and which other lines each station is connected to. Its very useful for a person travelling around London, but of very litle use to an engineer who is planning where to dig tunnels for a proposed new line, Abstraction applied to high level programming languages ‘Abstraction is the most important feature of high level programming languages such as Python, C#, Java ‘and hundreds of other languages written for diferent purposes, To understand why, we need to look at differant generations of programming language. ‘© The fist generation of language was machine code ~ programmers entered the binary Os and 1s that the computer understands. Writing a program to solve even a shor, simple problem was a tedious, time-consuming task largely unrelated to the algorithm itself, ‘= The second generation was an improvement; mnemonic codes were used to represent instructions But as you wil soe in lator chapters in Sections 4 and 6, it was stil an enormously complex task to write an assembly language program and what's more, if you wanted to run the program on a diffrent type of computer, it had to be completely rewritten for the new hardware, ‘+ The third generation of languages, starting with BASIC and FORTRAN in the 1960s, used statements like X = A + 6, finally frosing the programmer from all the tedious details of where the variables X and ‘A were stored in memory, and all the other fiddly implementation details of exactly how the computer was going to carry out the instruction, Finally, programmers could focus on the problem in hand rather than worrying about irrelevant, technological detals, and that is a good example of what abstraction is all about. 53‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION Abstraction by generalisation There is @ famous problem dating back more than 200 years to the old Prussian city of KOnigsberg. This beautiul city had seven bridges, and the inhabitants liked to stroll around the city on a Sunday afternoon, making sure to cross every bridge at least once. Nobody could figure out how to cross ‘each bridge once and once only, or alternatively prove that this was impossible, and eventually the ‘Mayor turned to the local mathematical genius Leonhard Euler The map of 18th century Kénigsberg Euler's first step was to remove all irralevant details from the map, and come up with an abstraction: We mi ‘To really simpity it, Euler represented each piece of land as a circle and each bridge as a ine between them. Wat we now have is a graph, with nedes representing land masses and edges (ines connesting the nodes) representing the bridges. Now that Euler had his graph, how could he solve the problem? 54CHAPTER 11 ~ ABSTRACTION AND AUTOMATION He did not want to try every possible solution; he realised that this was just a particular instance of a more {general problem and he wanted to find a solution that was applicable to similar problems. He noticed a Critical feature of the puzzle: since each bridge could be crossed only once, each node had to have an ‘even numbar of connections, because you must enter and leave a node by a different edge. The only exceptions are the start and end node, since you don't have to enter a start node or leave the end node. ‘All the nodes in this graph have an odd number of nodes, so itis therefore impossible! Euler had laid the foundation of graph theory, which you wil come back to in the second year of this course, BBy abstracting the problem, Euler made possible the solution of innumerable related problems. Not only does it apply to different ctios with cifferont numbers of bridges, it applies to many other problems with similar requirements. ‘Abstraction by generafsation, as ilstrated above, is @ grouping by common characteristics to arrive at a hierarchical relationship of the “is a kind of" type. Thus Euler's problem is a particular instance of graph theory, ‘This type of abstraction is very common in object-oriented programming. A class of object, say an Animal, will be defined with its own attributes such as gender and whether itis carnivore or vegetarian, and its own behaviours, methods or procedures such as move, sleep, eat, etc. Other objects such «as Dog, Cat, Mouse and so on may be defined as sub-classes of Animal - they all share common characteristics which are defined in the Animal class, but have their own attributes and behaviours as well. In other words Dog ‘is a kind of" Animal, as are Cat and Mouse. Procedural abstraction Computer science is, in broad terms, the study of problem-solving, and as such, is also the study of abstraction. As we have seen, abstraction allows us to separate the physical reality of a problem from the logical view. Thus, for example, you can send an email, play music or download an image without knowing any of the detail of how these things are actually dane. On the other hand, the computer engineers, technicians and system administrators who enable these things to happen have a very different view. They need to be able to control the low-level details that users are not even aware of. Procedural abstraction means using a procedure to carry out a sequence of steps for achieving some task such as calculating a student's grade from her marks in three exam papers, buying groceries online or drawing @ house on a computer screen, Consider, for example, how you could code a program to create the plan for an estate of 100 new houses. You could use a procedure which will draw a triangle of cortain dimensions and colour at a particular place on the screen. The colour and dimension are passed as arguments to the procedure, for example: procedure draw?riangle (colour, base, hei she) This may be called using the statement drawTriangle("red", 4.5,2.0) 55‘SECTION 2 ~ PROBLEM SOLVING AND THEORY OF COMPUTATION poke 56 The programmer does not need to know the details of how this procedure works. She simply needs to know how the procedure is callad and what arguments are required, what data type each one is and what order thay must be written in. This is caled the procedure interface. Similarly, there may be a procedure to build a rectangle that is defined by parameters colour, height and width, which are passed as arguments: drawRectangle ("beige", 4.0, 5.0) ‘To draw @ house at a given position on the screen, the programmer may write a procedure: bul ld#ouse {) which uses the drawTriangle() and drawRectangle () procedures, aligns them and positions the house at a particular position on the screen. All these variables will be passed as arguments to the procedure, ‘Several houses could be combined to make a street. Several streets could be drawn to represent the estate. ‘Then, if the builder of the new estate decides to make all the houses larger, the procedure for drawing the house does not need to be changed - itis simply called with new arguments. Procedure for drawing street Hides detail from [ | Depends on Procedure for drawing house Hides detail from [ | Depends on Procedures for drawing rectangle and triangle Functional abstraction ‘A function is called to return the result of a particular problem. For example, x = sqrt (17) ‘The computation method is of no concern to the user and is hidden. Functional abstraction, then, is a mapping from one set of values to another. The result of this mapping is Unique to a given set of inputs, and a value must always be retumed.CHAPTER 11 ~ ABSTRACTION AND AUTOMATION Data abstraction A similar idea is that of data abstraction. ‘The details cf how data are actually represented are hidden. For example, when you use integers or real numbers ina program, you are not interasted in how these numbers are actually represented in the computer. In a higher level language, itis possible to create abstract data types such as queues, stacks and trees. The abstract data type, for example 2 queue, is a logical description of how the data is viewed and the operations that can be performed on it. For example, elements can be added to the rear of the queue and removed from the front, The queue may have a maximum size that cannot be exceeded. The programmer Using this data structure, however, is concerned only with the operations such as Add Pooueus or RemoveF rongueue and does not need to know how the data structure is implemented using, for ‘example, an array and pointers to the front and rear of the queue. Information hiding Information hiding is where data is not directly accessible and can only be accessed through defined procedures/lunctions. This is most commonly seen in object-oriented programming, for example in & class where the data or attributes of the class are private and can only be accessed through public functions, Decomposition and Composition Decomposition is breaking down a complex problem into a number of sub-problems, each of which performs an identifiable task. Composition is the opposite ~ combining procedures to form compound procedures (0.9. BuildHouse, BulldStreet). It can also mean combining objects to form compound data, for example records or a data structure such as a queve, tree or ist. Problem abstraction Problem abstraction involves removing detalis unti the problem is represented in @ way that itis possible to solve because it reduces to one that has already been solved. For example, the problem of how to find your way through a maze can be reduced to a problem of traversing a graph, for which there is an algorithm - something you willbe studying in the second year ofthis course! (See Chapter 47 of the A Level textbook) Consider the folowing problem: ‘Tere are four knights on a 3x3 chessboard: the two white krights are atthe bottom two corners, anc the tio black knights are at the two upper comers. The goal is to switch the knights in the minimum number of moves so thatthe white knights are in the upper corners and the black knights are in the bottom comers. (A knight can only move in the following manner: one or two squares horizontally or vertically, folowed by two squares or one square at right angles, moving 3 squares in total) a @ AA = A i |a |@ We can abstract this problem by first numbering the squares of the chessboard, 1 to 9. Now we can draw lines from 1 to 6 and 1 to 8 representing the two possible moves from square 1. Do the same for each square in turn, and you end up with the graph shown in (b). (Square 5 can’t be reached with @ knight's move so itis omitted trom this graph.)
You might also like
Predicted IGCSE Computer Science Paper 2025
PDF
0% (1)
Predicted IGCSE Computer Science Paper 2025
15 pages
Aqa As and A Level Computer Science Heathcote P M Annas Archive 2
PDF
100% (1)
Aqa As and A Level Computer Science Heathcote P M Annas Archive 2
412 pages
Z Notes Comp p2
PDF
No ratings yet
Z Notes Comp p2
9 pages
As Computer Science 9618
PDF
No ratings yet
As Computer Science 9618
76 pages
Computer Science Notes
PDF
0% (1)
Computer Science Notes
36 pages
AQA As and A Level Computer Science (P M Heathcote)
PDF
No ratings yet
AQA As and A Level Computer Science (P M Heathcote)
408 pages
2017 Unit 1 Traditional Scenario
PDF
No ratings yet
2017 Unit 1 Traditional Scenario
8 pages
Paper 2 Theory For 9618
PDF
No ratings yet
Paper 2 Theory For 9618
33 pages
Answers Teachers Document (First Edition)
PDF
No ratings yet
Answers Teachers Document (First Edition)
148 pages
Computer Science Aqa Specification Checklist
PDF
No ratings yet
Computer Science Aqa Specification Checklist
17 pages
Isaac Cs Ocr Book 2022
PDF
No ratings yet
Isaac Cs Ocr Book 2022
354 pages
Cambridge IGCSE (9-1) : Computer Science 0984/22
PDF
No ratings yet
Cambridge IGCSE (9-1) : Computer Science 0984/22
2 pages
9618 Y21 SP 4 Evidence
PDF
No ratings yet
9618 Y21 SP 4 Evidence
4 pages
WJEC A-Level Computer-Science PDF
PDF
No ratings yet
WJEC A-Level Computer-Science PDF
30 pages
Chapter Four: Database Concepts, 6 Edition
PDF
No ratings yet
Chapter Four: Database Concepts, 6 Edition
54 pages
Computer Science: AQA AS and A Level
PDF
0% (1)
Computer Science: AQA AS and A Level
30 pages
Eduqas GCSE Computer Science Guidance For Teaching
PDF
No ratings yet
Eduqas GCSE Computer Science Guidance For Teaching
52 pages
OCR As and A Level Computer Science (Heathcote... (Z-Library)
PDF
No ratings yet
OCR As and A Level Computer Science (Heathcote... (Z-Library)
385 pages
Computer Science Book
PDF
100% (1)
Computer Science Book
385 pages
OCR As and A Level Computer Science by Heathcote P M, Heathcote R S U
PDF
No ratings yet
OCR As and A Level Computer Science by Heathcote P M, Heathcote R S U
385 pages
As and A Level: Computer Science
PDF
No ratings yet
As and A Level: Computer Science
14 pages
Isaac Cs Gcse Book 2022
PDF
No ratings yet
Isaac Cs Gcse Book 2022
223 pages
Data Base PDF
PDF
No ratings yet
Data Base PDF
95 pages
Cambridge International AS & A Level: Computer Science 9618/22
PDF
100% (1)
Cambridge International AS & A Level: Computer Science 9618/22
94 pages
igcse_compsci_2ed_python_sol
PDF
No ratings yet
igcse_compsci_2ed_python_sol
138 pages
GCSE OCR J277 Question - Practice
PDF
100% (1)
GCSE OCR J277 Question - Practice
44 pages
1.3.2 Wired and Wireless Networks, Protocols and Layers - OCR GCSE
PDF
No ratings yet
1.3.2 Wired and Wireless Networks, Protocols and Layers - OCR GCSE
24 pages
2023 2025 Syllabus
PDF
No ratings yet
2023 2025 Syllabus
55 pages
OCR Reference Language Guide Cheat Sheet
PDF
No ratings yet
OCR Reference Language Guide Cheat Sheet
9 pages
A Level CS CH 5 9618
PDF
No ratings yet
A Level CS CH 5 9618
11 pages
Computer Science Revision
PDF
No ratings yet
Computer Science Revision
17 pages
Answer Sheet - 38 Functions and Procedures
PDF
No ratings yet
Answer Sheet - 38 Functions and Procedures
7 pages
A-Level Computer Science (7517) : Non-Exam Assessment (NEA) Guidance
PDF
No ratings yet
A-Level Computer Science (7517) : Non-Exam Assessment (NEA) Guidance
23 pages
Computer Science GCSE Knowledge Organisers
PDF
No ratings yet
Computer Science GCSE Knowledge Organisers
26 pages
1.1.1 Number Representation
PDF
100% (1)
1.1.1 Number Representation
21 pages
Computer Science Revision
PDF
No ratings yet
Computer Science Revision
17 pages
CS Revision Guide
PDF
No ratings yet
CS Revision Guide
113 pages
1.5 System Software
PDF
No ratings yet
1.5 System Software
71 pages
A Level Computing 9691 Paper 2 Notes
PDF
100% (1)
A Level Computing 9691 Paper 2 Notes
85 pages
Edexcel GCSE ICT Revision Guide
PDF
100% (1)
Edexcel GCSE ICT Revision Guide
40 pages
A Level CS CH 10 9618
PDF
No ratings yet
A Level CS CH 10 9618
6 pages
A Level Computer Science Wider Reading
PDF
0% (1)
A Level Computer Science Wider Reading
2 pages
CS 9618 Notes
PDF
No ratings yet
CS 9618 Notes
17 pages
A Level CS CH 6 9618
PDF
No ratings yet
A Level CS CH 6 9618
9 pages
Cs Book2
PDF
No ratings yet
Cs Book2
265 pages
Edexcel AS and A Level Modular Mathematics Core Further Mathematics 3
PDF
100% (1)
Edexcel AS and A Level Modular Mathematics Core Further Mathematics 3
228 pages
Topic: 4.1.3 Abstract Data Types (ADT) : Chapter: 4.1 Computational Thinking and Problem-Solving
PDF
No ratings yet
Topic: 4.1.3 Abstract Data Types (ADT) : Chapter: 4.1 Computational Thinking and Problem-Solving
6 pages
Y13 Revision - A Level Past Paper Pack - Sample Papers - Complete
PDF
No ratings yet
Y13 Revision - A Level Past Paper Pack - Sample Papers - Complete
186 pages
IGCSE CS 0478 Paper 1 and 2 Revision Exams For 2024 and Bonus Past Exams Data Analysis For All Paper 1 2023
PDF
No ratings yet
IGCSE CS 0478 Paper 1 and 2 Revision Exams For 2024 and Bonus Past Exams Data Analysis For All Paper 1 2023
68 pages
IT CourseBook Complete
PDF
No ratings yet
IT CourseBook Complete
344 pages
Mark Scheme h446 02
PDF
No ratings yet
Mark Scheme h446 02
29 pages
Aqa A Level Computer Science Programming v1
PDF
No ratings yet
Aqa A Level Computer Science Programming v1
18 pages
Topical Past Papers For Alevels Computer Science
PDF
No ratings yet
Topical Past Papers For Alevels Computer Science
16 pages
AI
PDF
No ratings yet
AI
12 pages
1 2 1-Data-Transmission
PDF
No ratings yet
1 2 1-Data-Transmission
24 pages
GCSE (9-1) Computer Science Getting Started Guide 2020
PDF
No ratings yet
GCSE (9-1) Computer Science Getting Started Guide 2020
43 pages
Lab Manual Csc103 PF v2.1
PDF
No ratings yet
Lab Manual Csc103 PF v2.1
119 pages
Cambridge International AS and A Level Computer Science Coursebook 2nd Edition Sylvia Langfield - The ebook in PDF format with all chapters is ready for download
PDF
100% (1)
Cambridge International AS and A Level Computer Science Coursebook 2nd Edition Sylvia Langfield - The ebook in PDF format with all chapters is ready for download
57 pages
Dokumen - Pub Aqa As and A Level Computer Science 9781910523070
PDF
100% (1)
Dokumen - Pub Aqa As and A Level Computer Science 9781910523070
408 pages