Cambridge IGCSE Computer Science Textbook PDF
Document Details
Uploaded by PoisedChalcedony9073
Beaconhouse School System
Cambridge
David Watson, Helen Williams
Tags
Related
- Cambridge IGCSE and O Level Computer Science Second Edition_removed.pdf
- Cambridge IGCSE Computer Science 0478 Past Paper Chapter 6 PDF
- Cambridge IGCSE & O Level Computer Science Second Edition PDF
- IGCSE Computer Science Chapter 4 - Software PDF
- Cambridge IGCSE Computer Science Past Paper PDF
- IGCSE Computer Science - Chapter 7: Algorithm Design and Problem Solving PDF
Summary
This textbook provides a comprehensive introduction to computer science concepts. It covers topics like binary systems, logic gates, operating systems, and programming. The book includes activities, practice questions, and example solutions to help students learn.
Full Transcript
ENDORSED BY ~;~.~ CAMBRIDGE \t.~ lnt~mational F.11aminarmns Cambridge IGCSE® Computer Science - ,.,,.,.__ ,ff David Watson Helen Williams /. 1 HODDER...
ENDORSED BY ~;~.~ CAMBRIDGE \t.~ lnt~mational F.11aminarmns Cambridge IGCSE® Computer Science - ,.,,.,.__ ,ff David Watson Helen Williams /. 1 HODDER EDUCATION Cambridge IGCSE® Computer Science This page intentionally left blank Computer Science David Watson Helen Williams i.7 HODDER EDUCATION AN HACHETTE UK COMPANY Acknowledgements p. l tTCi.Stockphoto.com/Dcnn}~Bisogno 0 etc t - top 0 h - bottom.l - left 0 , - right 0 , - ccntn: Computer hardw= ond 101iware brand nama mentioned in thi, ""°" «protected by their rnp«ln'< tndenurlu 2nd :arcadmowkdged. S..T.1.tchi>dcvdopcdbytheLifclongKindezuryk- Fotolia; p.82 tCl Mauro Rodrigues/Fotolia, b CManin Dolun/Scknce Photo Libr-.ry; p.83 C Nornun Chan - Fotolia; p.85 C Studio 10 /Alamy; p.86 C Brcnn:rn ~tg,t.";;:t:_~:::.~~~~~~~Jt',t')~~~~~ ~!:t..:.!~t;/~;{_;!ehctte UK', poHcy is to me p>p that an: natucal, renewable 2nd =ydable products and made &om wood grown in susuinablefuccm.Thcloggingandmanuh.turingproccssc,:arc expce 0 6--IOKirbyStrcct 0 LondonECIN8TS CoverphotoCScannil-FotoHa Thirdeditiontypactinll/13ptGalliardRomanbyAptaralnc. Acrcaloguc:«cordfo,thi, titlcis:n.. ilablefromthcBritishl.ibr:uy I SBN 978 1471809309 Contents Introduction viii Section 1 Theory of computer science Chapter 1 Binary systems and hexadecimal 1.1 Introduction 1.2 111c binary system 1. 3 M easurement of the size of computer memories 1.4 Example use ofbinary 1. 5 The hexadecimal system 1.6 Use of the hexadecimal system Chapter 2 Communication and internet technologies 14 2.1 Introduction 14 2.2 Data transmission 14 2.3 Error-checking methods 17 2.4 lntcrnet technologies 22 Chapter 3 Logi c gates and logic circuits 26 3.1 Introduction 26 3.2 Logic gates 26 3.3 Truth tables 26 3.4 The fimction ofthe six logic gates 27 3.5 Logic circuits 29 3.6 Logic circuits in the real world 38 Chapter 4 Operating systems and computer architecture 42 4.1 Introduction 42 4.2 Operating systems 42 4.3 Interrupts 43 4.4 Computer architecture 45 4.5 The fetch-execute cycle 49 Chapter 5 Input and output devices 51 5.1 Introduction 51 5.2 ln putdeviccs 51 5.3 Outputdevices 67 Chapter 6 Memory and data storage 76 6.1 Introduction 76 6.2 File formats 76 6.3 Lossless and lossy file compression 80 6.4 Memory and storage 81 6.5 H ow to estimate the size ofa file 88 Chapter 7 High- and low-level languages 90 7.1 Programming languages 90 7.2 Translators 92 7.3 What happens when things go wrong? 94 Chapter 8 Security and ethics 97 8.1 Introduction 97 8.2 Security and data integrity 97 8.3 Cookies 100 8.4 Loss of data and data corruption 101 8.5 Firewallsandproxyservers 102 8.6 Security protocols 103 8.7 Encryption 104 8.8 Applications 109 8.9 Computer ethics 110 8.10 Freesoftware,freewareandshareware 111 Section 2 Practical problem-solving and programming 114 Chapter 9 Problem-solving and design 115 9.1 Introduction 115 9.2 Algorithms 118 9.3 Test data 119 9.4 Validation and \·erification 120 9.5 Using trace tables 125 9.6 Identifying and correcting errors 127 9.7 Producing algorithms 129 Chapter 10 Pseudocode and flowcharts 134 10. l Introduction 134 10.2 Assignment 134 10.3 Conditional statements 135 10.4 Loop structures 137 10.5 Input andoutputstatements 139 l 0.6 Standard actions 139 10.7 Exan1ples of algorithms in pseudocode 139 10.8 Standard flowchart symbols 142 Chapter 11 Programming concepts 146 11. l Introduction 146 11.2 Programming 146 11.3 Declaration and use of variables and constants 149 11.4 Basic data types 150 11.5 How to make your program work 151 Chapter 12 Data structures: arrays and using pre-release material 163 12.1 Introduction 163 12.2 Arrays 163 12.3 Using pre-release material 168 Chapter 13 Databases 169 13.1 Introduction 169 13.2 What are databases used for? 169 13.3 TI1e strucrnre ofa database 169 13.4 Practical use of a database 171 Index 178 I ntrod ucti on A ims l11is textbook has been written to provide the knowledge, understanding and practical skills that a student would need for the Cambridge Internntional F.xaminations Computer Science I GCSE and GCE O Level courses. The textbook is part of a package which includes a student CD-ROM. A teacher's CD-ROM is also available separately which includes additional guidance and other useful information ( see later in this introduction ). This OC>Ok and accompanying student CD-ROM provide: practice end-of-chapter questions which include questions from past Cambridge International Examinations papers activities which gi\·e students additional guidance and practice sample program solutions for programming activities hints and tips where these provide additional help and knowledge. Although this book has been written with the Cambridge lnter11atio11al F.xaminatiom syllabus in mind, it can still be used as a useful reference textbook for other GCSE computing courses. It is also a useful source of information for those srudcnts starting an A le\·el computer science course ~ especially at AS level. Using the book 111c textbook contains 13 chapters. Although it is possible for some elements of the practical problem-solving chapters to be examined in Paper I (Theory of Computer Science ), and vice versa, the sections for the theory work are in Chapters 1 to 8 and the practical work in Chapters 9 to 13. The book has been split into Section 1 (TI1eory of computer science ) and Section 2 ( Practical problem-solving and programming) to follow the Cambridge International F.xaminatiom syllabus as closely as possible. Activities are shown throughout the books as follows: ( Activity 1.1 ) Student CD-ROM TI1e accompanying student CD-ROM contains additional guidance to enhance the learning process in a number ofkeyareas in the textbook. The CD-ROM uses animation and verbal commentary wherever this is found helpful in the learning process. The CD-ROM includes sample program solutions for the programming activities. Where book topics are included in the CD-ROM the following symbol is used: 0 Teacher's CD-ROM An additional teacher's CD-ROM is available to accompany this textbook. TI1is CD-ROM includes the following material: possible responses to sample examination and other guestions each guesrion part suggests a level of difficulty expected responses to the guesrions at that level are included additional notes on why the responses meet the required level only answers to the end-of-chapter 'luestions in this textbook and to some of the activities where relevant program files in Python and Java for activities and end-of-chapter questions. a scheme of work to help teacher's plan their r.110 -year computer science course; this scheme includes: chapter numbers from the book topic to be covered from the chapter approximate time alkx:ation adllised to cover the topic Cambridge lnten1ational F.xaminationssyllabus reference relevant page numbers from the textbook activities found in the textbook to help in the teaching process any additional notes to help plan the lessons. The teacher's CD-ROM has not been through the Cambridge endorsement process. David Wdtherem.;nderfmmbottomtotop 16 Figur 1.5 7 ,emaamier: 13 0 ,em.;nder : 7 1'0' togetthehexadecimalnOO'lber: Activity 1.7 Convertthelollowingdenarynumbers intoheXddecimal{uloingbothmethods): a 98 b 227 c 490 d 511 e 826 f 1000 g 2634 h 3743 i 4007 j SOOO 1.6 Use of t he hexadecimal system This section reviews five uses of the hexadecimal system. 111c information in this chapter gives the reader sufficient grounding in each topic at this le\'el. Further material can be found by searching the internet, but be careful that you don't go off at a tangent. 1.6.1 Memory dumps Since it is much easier to work with: B 5 A 4 I A F C rather than: l O 1111001110 1 olo 10010001110101111111100 hexadecimal is often used when developing new software or when trying to trace errors in programs. The contents of part of the computer memory can hold the key to help solve many problems. When the memory contents are output to a printer or monitor, this is known as a MEMORY DUMP: 0 1 BINARY SYSTEMS AND HEXADECIMAL 1-··....... ··················1 009901'77 00990E9 E 00990EA5 n 74 20 6D 65 6D 6F H 20 73 12 69 79 20 6F 77 64 69 75 6D 70 20 66 72 6F 6D 20 20 797069636l6C2020636F6D707574657220206D85 6D 6F 72 611 67 20 74 68 65 20 20 63 6F 61 61! 00990EBC 746561?74 73206F66206l206ll756D62657220206F66 00990ED3 6C6F63 6l 74696F61173 2020696E2020696578202020 00990BIIA 6116F74 6l 74696F61120200000000000000000000000 Figu re 1.6 A program developer can look at each of the hexadecimal codes ( as shown in Figure 1.6) and determine where the error lies. The value on the far left shows the memory location so that it is possible to find out exactly where in memory tl1e fault occurs. This is clearly much more manageable using hexadecimal rather than using binary. It's a very powerfid fault-tracing tool, but requires c.onsiderable knowledge of computer architecture in order to interpret tl1e results. 1.6.2 HyperText Mark-up Language (HTM L) HYPERTEXT MARK·UP LANGUAGE (HTML ) is used when writing and de\·eloping web pages. HTML isn't a progranuning language but is simply a mark -up language. A mark -up language is used in the processing, definition and presentation of text ( for example, specifying the colour of tl1e text ). HTML uses which are used to bracket a piece of code; for exan1ple, starts a standard cell in an HTML table, and ends it. Whatever is berween tl1e two tags has been defined. H ere is a short section of HTML code: 1000 rpm and wind velocity> 120 kph logic statement: (S - 1 AND W - 1 ) iii bearing temperature 120 kph logic statement: (T - NOT 1 AND W - 1 ) Stage 2 This now produces three intermediate logic circuits: Figu,.3.20 i ! ====O- Figu.. 3.21 Figu,.3.22 Each of the three original statements were joined together by the word OR. Thus we need to join all of the three intermediate logic circuits by two OR gates to get the final logic circuit. We will start by joining (i) and (ii ) together using an OR gate : Figu,.3.23 3.5 Logic circuits Finally, we connect the logic circuit in Figure 3.23 to Figure 3.22 to obtain theammrer: Figur 3.24 The final part is to produce the truth table. We will do this using the original logic statement. This method has the bonus of allowing an extra check to be made on the logic circuit in Figure 3.24 to see whether or not it is correct. It is possible, howe\'er, to produce the truth table straight from the logic circuit in Figure 3.24. There were three parts to the problem, so the truth table will first evaluate each part. Then, by applying OR gates, as shown below, the final value, X, is obtained : i (S - NOTIANDT - 1) ii (S - 1 ANDW - 1) iil (T - NOT I ANDW - 1) We find the outputs from parts (i) and (ii) and then OR these two outputs together to obtain a new intermediate, which we will label part (iv ). We then OR parts (iii) and (i\') together to get the \'alue ofX. lnouts Outcut T (i)(S:NOT 1 (ii)(S:1AND (iiQ(T:NOT 1 (iv) X ANDT: 1) W: 1) ANDW: 1) 3 LOGIC GATES AND LOGIC CIRCUITS Activity 3.4 Twoscenariosaredesc:ribedbelow. lne.Khu11e,producethelogiccircuitandcompleteatruth tabletorepreseotthesc:enario iiAchemicalprocessisprotectedbyalogicdrcuit.Therearethreeinputstothelogiccircuit representing key parameters in the chemical process. An alarm, X, will give an output value of1 dependingoncertainconditionsinthechemicalprocess. The following table describes theprocessconditionsbeingmonitored: Puam t..rdHcription Parametu Binarvvalu o -riptionofcondition che mkalrea 115°( b Apo1Nerstationhasasaletysystemcontrolledbyalogiccircuit. Threeinputstothelogic circuit determine whether the output, S, is 1. When S = 1 the power !ilation shuts down. Thefollowingtabledescribestheconditionsbeingmonitored Param.ierdHcription Parame tu Binaryvalu D-riptionofcondition gas temperature O astemperature 160'C AND water temperatureisJnOfedataintheprinte,buffe,.then!hewholeprocessfmmst.,.ge5is ,epeateduntilthebufferisfinaltyempty Onc:etheprinterbufferisempty. theprinterseodsan interrupt (seeSection4.3)to!he processo,in!hecomputer;thisisa,equestlorJnOfedatatobesenttotheprinte,;the wt.oleprocesscontim,esuntilthewhaeolthedor:umenthasbeenprinted 5 INP(JT AND OUTPUT DEVICES 5.3.2 Laser printers LASER PRINTERS differ greatly from inkjet printers in the way they print pages. l11ey use dry powder ink rather than liCJuid ink and make use of th e properties of static electricity to produce the text and images. Unlike inkjet printers, laser printers print the whole page in one go (inkjet printers print the page line byline). Their advantage is the speed at which they can carry out large print jobs (e.g. 2000 leaflets) and the fact that they don't run out of ink halfway through. The following table describes briefly the stages that occur when a document is printed using a laser printer: Figure5.27Lue,printef SU inproc..s c..c,iptionofwhathappe ns 1 Thedatafromthedocumentissenttoa ?"int0ichisasetoll>eatedrolle,s;thel>eatmelts theinksothatitf,xPSpe,manentlytothepaper Atthevef"jend.adischargelampr alltheek>ctricchilfgefromthedrummaking itreadytoprintthenextp.:,ge App li cati o ns of inkj et a nd laser printe rs The choice of whether to use an inkjct printer or laser printer depends on which fcamres make it the most appropriate output device for the given application. INKJET PRINTERS are best for one-off photos or where only a few pages of good quality, colour printing arc needed; the small ink cartridges or small paper trays would not be an issue with such applications. LASER PRI NTERS produce high quality printouts and arc very fast when making multiple copies of a document; any application that needs high -volume printing (in colour or monochrome ) would choose the laser printer ( for example, producing a large number of high quality flyers or ix,sters for ad\·crtising) - they have two advantages: they ha\·c large toner cartridges and large paper trays (often holding more than a ream of paper). 5.3 Output devices Activity 5.8 Find out how the operation of colour laser printers differ,; from the operation of monochrome laser printers 5.3.3 3D printers @ 30 PRINTERS are primarily used in COMPUTER·AIDBD DESIGN (CAD) applications. They can produce solid objects which actually work. The solid object is built up layer by layer (refer to Section 5.2.l for more details ) using materials such as powdered resin, (X)Wdered metal, paper or ceramic powder. The motorcycle in Figure 5.29 was made using an industrial 3D printer. It was made from many layers (0.1 mm thick) of powdered metal using a technology known as BINDER 30 PRINTING. The following describes some of the features of 3D printing: Various types of 3D printers exist; they range from the size of a microwave oven up to the size of a small car. 30 printers use ADDITIVE manufacturing ( i.e. the object is built up layer Figure5.283Dprinter by layer ); this is in sharp contrast to the more traditional method of SUBTRACTI VE manufacturing (i.e. removal of material to make the object ). For example, making a statue using a 30 printer would involve building it up layer by layer using powdered stone until the final object was formed. The subtractive method would im·olve car\'ing the statue out of solid stone (i.e. remo\'ing the stone not required ) until the final item was produced. Similarly, CNC machining removes metal to form an object; 30 printing would produce the same item by building up the object from layers of powdered metal. Direct 30 printing uses inkjet technology; a print head can move left: to right as in a normal printer. H owever, the print head can also move up and down to build up the layers of an object. Figure5.29 Motossiblc to read ifit is somehow intercepted by, for example, a hacker. The same hashing algorithm has to be applied at both ends (se nder and receiver) for the message or key to be understood. In summary, the encryption algorithm converts messages using an encryption key into 'meaningless' text; the same key has to be used to decrypt the message. 1l1csc keys can, however, be intercepted which makes the encryption process less secure. To overcome this problem, a hashing algorithm is applied to the message or key, producing a string of characters which are virmally impossible to 'break' if intercepted. This considerably increases the security of the whole process when sending personal or sensitive data across, for example, the internet. The use of hashing and encryption is further discussed in Scction 8.7.4. An example ofa well -known hashing algorithm is ,\1D4 which generates a 128-bit string whenever a value is nm through it. For example, the following 16 -digit code: 1234 5678 9012 3456 would produce the following value when put through the MD4 hashing algorithm: 543FC7DDEAOCF5EAFS4279CBADCA180D (Note: this contains 32 hexadecimal digits (i.e. 128 bits) - sec Section l.5. ) Strings which are 128 bits long gi\'e 3 x 1038 possible combinations which makes them \·cry secure. Some newer systems use 256-bit strings which ha\·c 1 x 1077 possible combinations. Older systems employ strings which arc only 56 bits in length, which gives them only 7 x 1Ql6 possibilities - this has become rclati\ cl y easy to break since modern computers arc so fast at number crunching! But it is clear that the larger the key size, the more secure the encryption will be. 8.7 Encryption Activity 8.2 Using the internet, carry out a 51!arch for M04 and MOS hash ing algorithm generators (e.g. httpJMWW.online-convert.m m/) Then try various numbers, letters and messages to ,;ee how the 128-bit mde varies. Even just changing a few letters in a message can have a dramatic effect oo the 128-bit value For example 'Thi1isanex.ample': 1F312F8138628926E44AOC899161F4A8 'Thisisanotherexample': 2EAEB50E8870FD5418366CE235107F21 Tryout anumbi!rofex.amplesloryour,;ell. 8.7.3 Plain text and cypher text PLAIN IBXT (sometimes written as a single word 'plaintcxt') is described as the text or normal representation of data before it goes through an encryption algorithm. CYPHER TEXT (sometimes written as 'cyphertext' or 'ciphcrtext') is the output from an encryption algorithm: Figur S.13 8.7.4 Authentication AurHENTICATION is used to verify that data comes from a trusted source. It works with encryption to strengthen internet security. Examples include: Usualy auser,d/nameandpasswo,dareusedtologontomilllysystem,;both userodlnameillldp;rsswo,dare ~1 IF Mark c: OverallLowest THEN OverallLowest.. Mark IF Mark c: SubjectLowest THEN SubjectLowest... Mark IF Mark > OverallHighest THEN OverallHighest.. Mark IF Mark > SubjectHighest THEN SubjectHighest.. Mark OverallTotal.. OverallTotal + Mark SubjectTotal... SubjectTotal + Mark NEXT SubjectAverage.. SubjectTotal/600 PRINT SubjectName PRINT "Average is", SubjectAverage PRINT "Highest Mark is", SubjectHighest PRINT "Lowest Mark is " , SubjectLowest ; ov,,callAv,m,10.. OverallTotal/2400 Average is", OverallAverage overall Highest Mark is", OverallHighest b For the algorithm to be tested by dry running, it would be a good idea to reduce the number of students to 5 and the number of subjects to 2. Activity 10.6 11Identify the changes you would need to make to the algorithm for Example 2 to reduce the numberofstudentsto5andthenumberofsubjectsto2 b ldeotilythetestdataneededtotestEXilmple2withthereducednumberolstudeotsand subjects. c Withthe..etofdatayouhavechosen,setupandcompleteatracetablesothatyoucan compare your expected results with the actual results when you dry run the algorithm 10 PSEUDOCODE AND FLOWCHARTS 10.8 Standard flowchart symbols Flowcharts are drawn using standard symOOls. 10.8.1 Begin/End Terminator symbols are used at the beginning and end of each flowchart. Figure10.5lermonatofsymbols 10.8.2 Process Process symbols are used to show when values are assigned to an item/variable like an assignment in pseudocode. Figu re 10.6 Proces,,)fflbol 10.8.3 Input/Output Input/Output symbols are used show input of data and output ofinformarion. Figure10.7 1nput!Outputsymbol 10.8.4 Decision Decision symbols are used to decide which ac tion is to be taken next. These can be used for selection and repetition/iteration. Figure10.8 0ecisionsymbol 10.8.5 Flow lines Flow lines are used to show the direction of flow which is usually, but not always, top to bottom and left to right. Figu re 10.9Rowline 10.8 Standard flowchart symbols Exa m ple 1 (co ntinued) Tickets arc sold for a concert at $20 each, iflO tickets are bought then the discount is I 0%, if 20 rickets are bought the discount is 20%. No more than 25 tickets can be bought in a single transaction. c Draw a flowchart for the algorithm to calculate the cost ofbuying a given number of rickets. Output Yourticket o cost , co ot Figur 10.10Flowd>artforExampje1 Activity 10.7 Draw a flowchart for the algorithm given in Example 2. Choosethemethodyouthinkistheclearest way to show this algorithm and explain why it is the dearest 10 PSEUDOCODE AND FLOWCHARTS End-of-chapter questions 5 The temperature in an apartmen t must be kept betwee n 18°C and 20"C. l fthe temperature reaches l Show two ways of selecting diffen:nt actions using 22°C then t he fun i.s switched on; if the temperature pscudocode. reaches 16°C then the he.:iter is switched on, 2 You have been asked to write the pscudocodc to otherwise: the fun and the heaters arc switched off. choose the correct routine from the menu shown The following library routines an: available: below. GctTempcrature a Decide which type of conditional statement you FanOn a.re going to use:. FanOff b Explain your choice. H catcrOn c Write the psc:udocode. H caterOff d Select your test dau and e.~plain why you chose Write an algorithm, using pscudocodc or a each value. flowchart, to keep the temperature at th e right level. 6 Daniel lives in Ital y and travels to Me,dco, India and New Zealand. The time differences arc: 1 Set upnewAccOU'I\ 2Mahchangestoan&.istjr.gAccount Country 4V;ewMy Orclers 6Alter..nE! :: ::c:~~u 0 O, lluurw.l,U "'-"MoooR""T~FX. Pl"'l~ l'(n~ X od f311il o o~l ~tafR l ~~ l \r l t ~LCBtii / "'., 1 a!}!D l 'il !ii:i: _ :' ~SCHPT u.nz=>: "Jn Ser·p~ " ~ va.r Hro c11unr,,,, - o : va.r SecandRmber - O; FirotNer - vind- 20 " copyrl~"t", credH " o r "Hce n, el) ror mo re 1nror=t1o n »> - - - - - - - - - - - -- - -- RL STMer,i, to Figure 11.1 [email protected] f ;i,, {di: ~ "h '{~ f"'![!d J..,ngUO'j t 'icrOtr1cr«,t:1< l >e !>wu>...,,.rtl>Chc ""t..,_,. ,,,,,.1., u n - -pr-,CI (..,_rtlfheH " h· f Uo,e» Sion.. " · a- liiil -..i - f,..,. ,.My· ,~,.,- e - li?l Iii o Figur 11.28 Program tPStingExample 1 inJavaSaipt Activity 11.7 Usingthehigh-levelprogramminglanguagethatyourschoolhaschosentouse,writeaprogram for Ex.ample 1. look at the test data used with the Python and Ja~aSuipt solutions; explain how you would improve this test data to ensure that your program was fully tested 11 PROGRAMMING CONCEPTS 4 Write three programs showing the diffe rent ways End-of-chapter questions that can be used to add up five numben and print l Explain the difference between a variable and a out the total. Explain which loop is the most constant in a program. efficic:ntto usc. 2 State four different basic data types. 11lustrateyour 5 A sweet shop sells 500 different sorts of sweets. answer by declaring a variable for each o ne and Each sort of s-,vcct is identified by a unique four· assigning it a value. digit code. All sweets that start with a one ( 1) are 3 A school with 600 students wants to produce some chocolates, all s-,veets that start "~th a two (2) are information from the results of the four standard tests in Maths, Science, English and IT. Each test is out of l 00 marks. The information output should j:1~:s~~l :;~::~~hs:~:::;~i~i~:~;:!3Js:~d can start \\1th any other digit except zero. be the highest, lowest and average mark for each a Write a program, which inputs the four-digit ttst and the highest, lowest and average mark code for all 500 items and outputs the number O\'erall. All the marks need to be input. of chocolates, toffeu and jellies. a Write: a program to complete: thiis task. b Explain how you would test your program. b Explain how you would test your program. @ and Data structures: arrays using pre-release material lnthischapteryouwillle.-imabout e dedaratklnolone-dimensionalarrays e theuseolooe-dimensionalarrays e theuseolavariableasanindexinanarray reading and 'Miting values in an array using a FOR _ TO ·- NEXT loop e usingpre-releasematerial 12.1 Introduction One of the advantages of using computer systems is their ability to accurately repeat the same tasks many times, for example, producing electricity bills or calculating exam scores. In order to do this, programs are written with loops for repetitions to work with lists of similar items. These lists are identified by the use of a single name and each item in the list can be found by an index number showing the place in the list. This type of list is called a one-dimensional array. The items in the list are the elements of the array. Figure12.1Ustorm>e-dimensiooala,,ay 12.2 Arrays 12.2.1 One-dimensional arrays In order to use a one-dimensional array in a computer program, you need to consider: what the array is going to be used for, so it can be gi\'en a meaningful name how many items arc going to be stored, so the size of the array can be determined what sort of data is to be stored, so that the array can be the appropriate data type. 12 DATA STRUCTURES: ARRAYS AND USING PRE-RELEASE MATERIAL For example, if a one-dimensional array for all the students' test marks in a class was to beset up: array name StudentMarkTest number of items - number of students in the class, this could be a constant NoStudents whole numbers need to be stored, data type Integer. Arrays usually start at element O or element 1. Often if an array starts at clement 0, the size of the array is given as one more than re'luired and clement O is not used. ~:fo':::::::1,:! ~~-e~l=r~t;;I positioo,1 to30them.mberofelements inthea,rayneedstobe31 Figure 12.2Alfif'jdeclaratiooinJavaSc:ript Array declaration in Python Listdelorethetestmarksloradassol3051udents 12.2 Affays 12.2.2 Using a variable as an index in an array In order to repeat the same task many times for all the items in a list, each item needs to be referred to in the same way using the index number for each element of the one -din1ensional array. !fa variable is used for this index number, then the same code can be re -used for each item. StudentMarkTeot(Counter] - int(input( "P l eaoe EnterMark")). Python StudentMarkTe ot(Counter] - winOOW.pro,apt('PleueEnterMark',''); StudentMa rkTe ot(Counter] - p,,.uelnt(StudentMarkTeot[Counter)); JavaScript Figure 12.4Us;ngav,.-iableasanir>dexinana1ray This allows se\·eral arrays to be used together with the same index number to show related information, for example, each student could sit more than one test and the name and gender of the student could also be recorded. StudentHa!Ml(Counter] - window.pr~t('EnterStudentHa..., , JavaScript StudentGender(Counter] - window.proq,t('EnterStudentGender', ''); StudentMarkTestl(Counter] - window.proq,t( EnterStudentllarkforTestl', StudentMarkTe otl(Counte r] - p a r oeint(StudentMarkTe o tl[Counte r]); StudentMarkTest2(Counter] - window.proq,t{'EnterStudent!larkforTe ot 2 ' , StudentMarkTe o t2. 7 t e r ] - par oeint(StudentMarkTeot2(Counter]); r;.:::.::a.:·.:"' _. ;;') l ~ferent,.-,ays J StudentHa-. append ( input ( Plea0