You are on page 1of 24
EOI y-1 oh kta Algorithm design and problem solvin (ster areaco ne ‘+ [eam about the use of, and stages in, the program development life cycle ‘+ use decomposition to split a system into sub-systems ‘+ create structure diagrams, flowcharts and pseudocode algorithms + explain how a bubble sort and linear search works ‘© describe and produce algorithms that include finding the maximum, minimum and average values Understand the need for validation and verification and write programs that use both ‘identify appropriate test data for an algorithm ‘complete a trace table for an algorithm learn how to check a program for errors and amend the program learn how to explain the purpose of an algorithm. CIENCE: COURSEBOOK > CAMBRIDGE IGcse™ & 0 LEVEL COMPUTERS Write down a set of + objects ‘ hava vr example, stating Set up an obstacle course using chairs and ft Jpstacle course, fo instructions to guide a friend through the o how many steps to take, which way to turn, et low the instructions safely to oll 7 ions until your ‘Amend the instruct le cours Give the instructions to a friend and ask ther (e.g, stop if they are about to hit something). iend can successfully get through the obstacl es og GORITHM: Consider what is meant by an algorithm. Ifyou search for algorithm then you wil fin! answers such as a process, ora set of rues, that ae followed, This does nt mean they are limited to computers You can find algorithms in all areas of life. You will ave followed many of these without even considering thst they are algorithms. For example, in mathematics you will have followed 2 series of steps to solve a problem. Algorithms can take many forms, and use a variety of words or structures, itten as a series of instructions that the computer Computers follow algorithms. Programs are wri millions of lines long, and they have to make use of then follows. Algorithms for software might be specific instructions to tell the processor what to do. ‘A.computer can only run machine cade, that is binary. you enter a command into the computer, this has to be converted into binary for the processor to execute (run) it. Different programming languages have different focuses. Some different types are shown: Declarative This declares rules and you can ask it questions and it wll give an answer based upon the rules. For example, here are some facts: person (ali) Allis @ person. person (jennifer) Jennifer is a person. person (tyler Tyler is a person. friend (jennifer, tyler) Jennifer is fiends with Tyler is a person. friend (tyler, ali) ‘Tyler is friends with Ali | From this you could ask who Jennifer is friends with, and it will return Tyler. Object-oriented This allows the user to create objects that have features (attributes) and proc 10d). Te yon erik tewoecee archer saree oe hoe ne ahiaies Ite processes are move forward, move backwards, turn engine size, number Event driven Some programs use buttons, text boxes and other items thatthe user can interact with. An event aormanianguage has code that only run when one ofthese items x cick nce aah The code Cre yan from stat to finish, each item has is own code, ed ot canes 7. Algorithm design and problem solving Procedural ‘This has statements that are run inthe order that they are writen It makes use of subroutines (orocediures and functions) that can be cae from other parts ofthe program. Tiss the type of language that you are mos ikely to start leaning to program with Figure 7.1: A person reading programming statements Discussion questions 1 What are the key features of an event driven language? 2 Why do you think there is @ need for different types of programming language? Can you think of any types of problem that lend themselves to one type of language? 7.1 Program development life cycle When a person, or organisation, creates a new computer program they will use a Struetured, organised plan of how to ereate the program. This i called the program ‘evelopment life cycle program There are several varieties of life cycle, including eycic, spiral, waterfall and rapid development, These all include the stages analysis, design, coding and testing a system. problem, development life cycle: a series of structure step / activities that are followed to produce ‘analysis: the frst stage of the program development life cycle that involves investigating the ep SCIENCE: COURSEBOOK > camerince iscs 0 LEVEL COMPUTE sded, The problem 7.2 Analysis ie is ft stage in seat ptm al : Thine tases nit pep ae eT Decimation | tats ee re abl no subproblens Subproblens se 8 ag | andor requirements foreach component part, and thet sete sh can inetenedas | smalersgitte a wich ane ‘Once you have decomposed the problem, each a subprogram, be spitint a tint sub-systems, see ta stage of the pat develope rae ope thd decomposition (of the problem and algoriny aoe, implementa 7.3 Design ‘Once the requirements hav how the program will work int program using a structure diagram, and pseudocode. vera designers can bein pli’ Th jude an overview of the canine algorithms using flowcharts 1 been identified, the the design phase. This 1d the designing of Structure diagram ‘A stuctre diagram is developed by decomposing progam nti PPPOE TS op and below this its SUBDTOETams ‘The diagram has the name of the program Each subprogram can be spit dwn further as well f required structure diagram hierarchical dagen that shows the decomposition fa Example 1 system ‘A calculator needs to allow the and the symbol, calculate the result and outp user to enter numbers yt this process: an acion that is performed, for exemple, ‘The name of the program is at the top. The boxes xoxo Tae tuy ropes Fu 72) seals epasnal agua ink "seer Rus diz eae ee eee fies ‘One way of si of inputs, processes an ‘an input, processes and output, ‘added to the diagram (Figure 7.2) “The subprograms can then be split further, The calculator needs two numbers and a Jjmbol to be entered (eg. 2+ 3). Ad these boxes below input (Figure 7.4. 'sdependent on the symbol entered. In ths calculator, there is +, —,* ‘could be given a separate box (Figure 75). The process is and /, Each of these asa Srlnput prem and outpit ar ackedto Figura 74e trucure diagram ‘gure 7.4: Band he input subprograms Figure 7- the cal 7. Algorithm design and problem solving ]0cess subprograms Both of these are valid, There are lots of ways you can desompose a problem, and decompose: the everyone could doit lightly differently but the sation sil aid action of performing Finally the output needs identifying (Figure 7.7) decomposition: spiting 2 system in | which ean in turn be Figure 7.7: finished structure diagram forthe calculator This program was fairly small, so it has been split into very precise instruetions that «can then be programmed, The next example isa larger problem, A computerised version of chess is being developed. Two players can enter their and then a new board wil be displayed. The players take it in turns to select pieces to ‘move and the positions to move them to, The program will check that the moves Valid and then move the pieces. It will remove any pieces that have been taken in each ‘Move, and check if anyone has reached checkmate. ‘COMPUTER SCIENCE: > cannes reese 4.0 LEVEL ae a Example 2 The name ofthe program sat the top Figue78. i ao outputs, but this = essesand ts, processes se fiterent functions instead. The fi his is given the name “New jayers ean then move thei eckmate Paes Ace The program could be decomposed into input isa large program so it ean be spit down by d Part is that there are two players who need entering. tl Playets. Then the game is set up ‘New game’. The pl Pieces (‘Make move’). The program will check if someone has ch we (Check won’) (Figure 7.9) chess program Figure 7.9: Subprogram far the chess program ‘These ean then be split further. They are cach given their own sub-diagram ere so that they are easier to view (Figures 7.10-13} Es me es Figure 7.10: The Now players subproge Figure 7.11: The New game subprogiam Figure 7.12: The Make move subprogram Figure 7.13: The Check won subpr ws > 7. Algorithm design and problem solving Can you split any of these subprograms down further? In ‘Check won’ (Figure 7.13) what should happen ifthe result is checkmate? Should there be an output? What if there is check but not checkmate? Should this be output? Peer Assessment ‘Compare your subsystems with a friend. Did you have the same answers? Ifs0, are they both valid structure diagrams even though they are diferent? (nce you have decomposed your program into subprograms, you will need to des an algoritn foreach pat, This could be the lew! | (heft row below the top box) like inthe calculator example t could be fora lower level, ik inthe game of chess Each box should become an individual algorithm, When you write your program. each of these individual algorithms might bea separate function or procedure (sce Caper 8, Setion 12). Together, these individual algorithms should come together 10 crete te whole system. Questions 1 Describe the process of decomposition. 2 program asks the user to enter two numbers. The program then adds the numbers orether and outputs the total, Draw astrutue diagram forthe program, 3 Asatllte navigation system needs to ask the user to input thei destination, It then finds the route to the destination and outputs the instructions to the user. Draw a structure diagram forthe system, 4 Alogin system asks the user to ener their username and password. Tt checks these ate valid and either outputs that they are correct, or incorrect and prompts to reenter Draw a structure diagram for the sytem. Flowcharts Aftoychart isa diagrammatic representation of an algorithm. Figure 7.14 shows some | flowchart: a ofthe et of standard symbols. diagrammatic representation of an algorithm, Process Figure 7.14: Flowchart symbols ‘A flowchart shows each step of a process, in the order that each step i performed, Each shape has one statement within it, for example, input number, or add 1 tox The shapes are joined with arrows to show the direction of flow and the content inside each box ean be written as Words, or as pseudocode statements. Table 7.1 shows examples of how the flowehart symbols are used. BOOK > caMBRiDGE 1Gcse™ & 0 LEVEL COMPUTER SCIENCE: COURSE! Starvstop —_| A flowchart begins with a Start box, with one arrow from it. A flowchart ends with a Stop box, with one arrow going into it. st f Figure 7.15: Start/Stop input ‘A single input of a value with an identifier for that value. input number One arrow should go into the box, and one arrow should ttt come out. input letter Figure 7.16: Input Output ‘An output of text in speech marks, and/or the identifier of avalue output “error” utput “number is” Process An action that is being performed, usually a mathematical calculation. One arrow goes into the box, and one arrow comes out of the box. t number = number + 1 1 4 message = “hello” & “world” 1 Figure 7.18: Process Decision = A question with two outcomes, yes or no (or true or false). The question is a comparison from: = equal to > greater than < less than >= greater than <= less than, You can have more than one condition by including AND or OR. See Chapter 8, Section 6 for the use of these operators. One arrow goes into the box. Two arrows come out, one labelled yes (or true) and the other no (or false). Table 7.1: Flowchart symbol examnles YES NO YES Figure 7.19: Decision Process ‘An action that Ee performed, usually a ‘mathematical calculation, oe arrow goes into the box, the box. ad Decision 7. Algorithm design and problem solving number = number + 1 Figure 7.18: Process ‘A.question with two outcomes, yes or no (or true or false). The {question is a comparison from: = equal to > greater than < less than >= greater than = less than. You can have more than one condition by including AND or OR See Chapter 8, Section 6 for the use of these operators, One arrow goes into the box. ‘Two arrows come out, one labelled yes (or true) and the other no (or false). YES, No No. ves Figure 7.19: Decision Table 7.1 owchart symbol examples Itis important that all arrows are complete, i. all boxes lead somewhere else so that ‘you cannot get stuck in the flowchart with nowhere to g0. Example 1 Figure 7.20 shows a flowchart for a calculator. Start input numt / input symbol / YES answer = nut + num2| answer = num! — num. answer = nurnt / num2 ‘answer = num * numa. eee | Figure 7.20: A flowchart for a calculator =~ Questions 5 Write the name of each flowchart symbol in the shape a ~~ < > a ——t eance fStop 7 Draw flowchart to take three numbers as input, find and output the largest number 7.4 Pseudocode Em Pseudocode refers to any code that is not written on a computer to run. There isno one | pseudocode: « set pseudocode, because if there was then this would be code with a specific language like statements Instead it’s term for any readable code like statements that all progearsmers will are used to design ‘understand. This means that it uses keywords, and constructs such as IF statements, algorithm but dort WHILE loops, etc. These constructs oceur in almost all languages, so any programmer | follow any would be expected to read them and translate them into the aetual progeamnming language. language they are using. oo Example pseudocode: INPUT Number1 IF Numberl < 10 THEN TPUT “too small" ourpur ‘valid ENDIF This uses the keywords INPUT, IF and OUTPUT. These can then be translated into whatever language the programmer is using. Here the pseudocode nes converted into Python, VBNET and Java, le program is a 154) Pe en and problem solving python musberl = input () Sf mumber < 10 print ("E00 smali*) else: print (*valia) VBNET munberl = console. readline() if number < 10 then console.writeline(*too small") else console. writeline(*valid*) endif Java munber = Integer.parsetnt (scanner-nextbine()); if (number < 10)( system.out.printin(*too small"); jelset System.out.printIn(*valia*) ; ) ‘Thete are many different valid pseudocode formats. Some wll aways use capitals forthe commands, eg. INPUT, IF, FOR. Some will use instead of an = fr assignment. If {you write your pseudocode in almost perfect ‘code’ i, you actually write Python code, because itis not to be run and you can have all sorts of syntax errors itisstill pseudocode, ‘What is important is that the program is split into steps that can be easily converted into a ‘eal program. Table 7.2 shows some examples of valid and invalid pseudocode, INPUT Value Input the value X FoR x = 0 to 9 Loop 10 tines ourrur value + x [in each loop output the loop nunber added to the input value ext x Faun = inpue Tnpat = num jnun2 = input input = num2 if mum > nun2 then |if muml is greater than nun? then output muni print (num) Af numl is not greater than nun? then output nun? else print (nun2) Bodie ble 7.2: Vale/rvalic pseudocode examples ‘The syllabus includes information about the pseudocode conventions that wl ‘pear within examinations. The pseudocode conventions inthis book don't sivays exactly follow the conventions you will seein your exams, but they are sill valid. Remember that your syntax doesn't have to be perfect — it is your logie that is important. 7. Algorithm design and problem solving Tey < 6 THEN jada 3 to the value entered Store the value entered in the variable newalue fvaluel = INPUT(*Enter a number") TF aurnber is more than 10 WHILE nunberl <> 0 40. Write a pseudocode algorithm to: take three values as input + multiply the numbers together © output the result 11. Writea pseudocode algorithm to: take 10 numbers as input (using loop) add together the values © output the total with an appropriate message. 7.5 Coding ‘Once you have decomposed your problem into subproblems, and you have designed the algorithms using flowcharts and/or pseudocode then you can start writing the program in your chosen programming language. This is often referred to as coding, ‘This will also include some iterative testing. This i testing that is carried out while the program is being developed, for example, if you write the program code for one of the fubproblems, then you will test it with a range of different data to make sute itis fully working before moving onto the next step. 7.6 Testing ‘When you have finished your program, you need to carty out (esting to make sure it uly works + doesnot crash + meta oqiements You will need to identify appropriate test data fo use to test the program. ‘There are four types of test data: * Normal — data that the program should aecept Abnormal ~ at thatthe program should ot weep * Extreme data thas atthe ede of what i llowed * Boundary — data that ison the edge of being accepted and being rejected coding: the writing of a program using one or more programming languages. testing: repeated use of a system to ty all different possibiltes to make sure the system is fully working and cannot be broken. test data: the input data that is used to test a syste, normal test data: data that a program should accept. abnormal test data: data that a program should not accept. extreme test data: data that is on the edge of what is allowed. boundary test data: data that ison the edge of being accepted, and data that is on the edge of not being accepted. $s 7.7 Common algorithms ‘Asearch algorithm checks a set of data to identify whether a specific value exists in the | search algorithm: a series of steps that sort of data a searches for a specific A sorting algorithm takes a set of data and rearranges it to be in a specific order, Peat data, or not, One example of this isa linear search, cg in ascending alphabetical order, One example ofthis isa bubble sort. sorting algorithm: a series of steps that will rearrange a set of data into an order, e.g. ascending numerical data Nise ee Keeney Sorting data and searching for data are activities that a very large proportion cof programs will use at some point. For example, outputting alist of data may need sorting into order. A user may enter a username and the program needs to search for ths in the set of valid usernames. There are many different searching and sorting algorithms, each one has its benefits and drawbacks depending on the problem. This could be the number cof data items it has to sort through, or whether the data is already in order to search for a value. It's up to the programmer to identify the algorithm that is ‘most appropriate for their program to make sure itis as efficient as possible {oth in the time it takes to run, and the amount of memory it needs to perform this tas Linear search Ina program you might need to look for a specific value in a set of data. A linear linear search: a ‘search will check each item one at atime, starting with the first tem and continuing search algorithm that ntl it either finds the item, or it checks the lst valuc. Visits each item of data in turn to check ACTIVITY 7.5 whether itis the data being looked for Get a set of playing cards. Select 10 random cards and place them face down on the table in a row. Perform @ linear search to see if the Ace of Spades isin the set. 1. Turn over the first card, 2 \sit the Ace of Spades? 3. fits, then stop searching, you've found it 4 IFitisn’t, turn over the next card. Repeat from 2 7. Algorithm design and problem solving ‘This algorithm is inefficient because if it finds the search value then it still conti searing. This wel ifyou wan to know hehe the sah sale appears more ‘than once. ‘the ch value appears more Different ‘You can make the algorithm more efficent by stopping as som as the values found, programming aoe languages use different characters to indicate the start of ona s7Pane hevovtodex © 0 cnt eres iin white the value is not founa, and you have not checked | 42D rece) fat eleneat Pecexmple check if the current inden ie the cata searched tor | 3d Tous, IF DataArray[ArrayIndex] = SearchValue THEN. characters when //3£ Ae 4s output where it was found ‘writing pseudocode, OonHUn Found ate areyite Binay one ofthese (yet Scop round © TRUE //4f it is not found, increment arrayIndex to the next value ArrayIndex * ArrayIndex + 1 ENDIF NDA: Bubble sort When writing a program you may need to sorta set of data into a specifi order, forexample, ascending numerical order or descending alphabetical order. (One method of sorting data is using a bubble sort bubble sort: ‘A bubble sort takes the first 2 value: value 1 and 2, and compares them. If they are the | Sorting algorthm ‘wrong way around it swaps them. It then puts these back and takes values 2. and 3 and compares them. If they are the wrong way around it swaps them, This repeats until it has ‘worked all the way through the list once, It then starts again with the first two values. kis called « bubble sort because it acts ike a bubble moving across all the elements 10 theend, then starting from the beginning. There are two ways to tell the algorithm when to stop. 4. The algorithm has been through the entie list, the number of elements in the list “I. So if there are 10 elements, the algorithm runs 9 times. If there are 100 elements, the algorithm runs 99 times If there are XELements, the algori runs XElenent's ~ 1 times. This isthe easiest way to program it, bu itis not efficient. All elements might bein the correct order to begin with, but itis stil going to run through the same number of times 2 Either the algorithm has run through thelist XS1ement's ~ 1 times, ort has run ‘through the lis, checking all of the elements, and it has wot made any changes. that moves through the lst repeatedly swapping values in pairs. Nae) Get a set of playing cards. Select 10 random cards and placo them — on the table in a row. Perform a bubble sort to put the cards in ascending numerical order. ‘Tum over the first two cards. If the tts larger than the 2nd, swap them. Otherwise, do nothing. Turn the cards back over. ‘Tum over the 2nd and 3rd cards. Repeat step 2. Repeat tuming over the cards and swapping until you have been through all 10 cards once. Did you make any swaps? If so, start again from step 1. If not, stop because the cards should be in order. A bubble sort can be written as a pseudocode algorithm, There are different versions Of the algorithm. Here are two different versions. Version 1 Stopping only when it has run array length =I times. //loop array length - 1 number of times FOR NumberPasses + 0 to LENGTH(DataArray) - 1 /floop through each element in the array FOR Index = 0 to LENGTH(DataArray) - 1 //check if the data is in the correct order IF DataArray[Index] > DataArray[Index + 1] THEN //if not swap the items ‘Temp + Dataarray (Index) DataArray[Index] © DataArray[Index + 1] DataArray[Index + 1] + Temp ENDIF NEXT Index NEXT NumberPasses Version 2 Stopping when there are no changes or when it has run array length NumberPasses + 0 //continue until one pass has no changes //or it has looped array length - 1 tines WHILE Changes = FALSE or NumberPasses <= = Ltimes, (changes = false) LENGTH (DataArray) - 1 DO ee 7 Algorithm design and problem solving Questions 46 Perform linear search forthe number 6 in the followin wo 5 6 8 1 2 nee 47 Performa linear search for the letter “f” in the follow ing data: bay 1 pees ies een 49 Perform a bubble sort to put the following data into ascending numerical order: ieee ose Ge aE grg et 49 Perform a bubble sort to put the following data into descending numerical order: a2 a oe rahe: 20 Explain the difference in efficiency between the two different bubble sort algorithms, Totalling ‘Totaling is adding a group of values together to give a total totalling: statements ina program that add together a set of date a0 to produce the total For example, a person buys tems at a supermarket, The tems cost: $0.80, $1.00, 1.00, $15.50, $21.30 The total is 0.5-+14+1415.5+21.3 ‘Todo this in a program you need to: ‘Initialise a variable to store the total, 8, al +0 © Add the value to the current contents of the total,eg. Total « Total + Value, Example 1 Totaling the 10 values input by the user qotal - 0 //Initialise the total variable to 0 FOR X “0 709 Total © Total + INPUT("Enter a value‘) //Add the input to the total NEXT x ourpur Total Example 2 “Totaling the vues in an aray named dataarray: qotalvalue + 0 //Initialise the total variable to 0 FOR Count © 0 70 LENGTH (DataArray) - 1 qeraivalue + TotalValue + DataArray Nex? count ourpur Total [count] //Add the eI ‘A program is needed to ask the user to input the pice of products they have bought. Calculate and output the total cost they spent. Getting started I? For example, intialsing the 41. What are the steps required to find the total total 0.0 will be the fist step. PUTER SCIENCE: COURSEBOOK > CAMBRIDGE IGcse™ & 0 LEVEL COM! 2. Youwil need to wok out ho to continue aeing forthe rice of Peoscts vil heya et have yore Hare alesk at ome COS RISNCN aigorthans inthis cht tar perorm inf acons ts Wh they ure? How did thay lt the number tat could De Practice 1 Create a structure diagram for the problem 2. Write an algorithm to ask users to repeatedly input the price of products they have bought until there are no more to enter. 3. Amend the algorithm to total the cost of all the products and output t at the end of the algorithm. this Challenge 11 Amend the algorithm to also count how many items they entered. You can look ahead to the next section or work out how to count them yourself. 2 Now you have the total and the quantity, amend your program to work out the average cost. Counting Counting is working out how many of something there are, For example, counting how many fingers you have or counting how many items you bought when you ‘went shopping, To do this in a program you need to: counting: statene in a program that record how ma something thereat © Initialise a variable to start the count, eg. Countrtems © 0. ‘© Add I to the count variable each time, eg. Count © Count + 1 Example 1 Count the number of items the user enters: Count © 0 //initialise the count variable Number + 0 WHILE Number <> -1 DO // loop until the use Number © INPUT("Enter a nunber. Enter <1 tow “1 to stop" Count Count + 1 //add 1 to co © count each ti yum time a number is in ENDWHILE Example 2 Count how many numbers in an array are below 10 Aare below 10, and how many are more than > CountBelow10 « 0 //initialise both ee eta Countabove20 + 0 ee FOR X + 0 to LENGTH (Nunberarray counters to 9 loop /if the number is less than 10 TF NunberArray(x] < 10 THEN CountBelowl0 + CountZelowl0 + 1 /if the number is greater than 20 IF NumberArray(x] > 20 THEN Countabove20 + Countabove20 + 1 //increment the counter ENDIF NEXT X ‘A program needs to ask the user to input the weight of parcels being posted itneeds to count how many parcels are less than 1 kg, how many are between kg and 2kg, and how many are above 2kg, increment the counter 5 Getting started Recap how to count in an algorithm. What are the diferent pieces of code f you need? For example, initialise the count to start at 0. 2. You will need to use selection to compare the inputs with the weights. Recap the use of selection and the format, including the differences between the operators >, >=, < and <=. Practice 4. Draw a structure diagram for the problem. \Wite an algorithm to read in the weights ofthe parcels until the user has 2 finished. 3. Amend the algorithm to count and output how many parcels are below 1kg, 4. Amend the algorithm to also count and output how many parcels are between 1 and 2kg 5 Amend the algorithm to also count and output how many parcels are more than 2kg, Challenge “The user would like to enter the limits that they are counting themselves when the program starts. For example, counting how many parcels are less than 1.5kg instead of kg. Amend the program to make this chenge: Finding the minimum The minim value isthe smallest value ‘class are entered and the lowest mark is the minimum. smallest item in a set of data minimum: the within a set. For example, the marks for a To do this in a program you need to: + initalse a minimum variable to be a large value, beyond those that will be entered, eg.Minimun + 9999. © Compare each value to the minimum variable, eg. TF Number < Minimum : COURSEBOOK > _CamBrince 1Gcse™ & 0 LEVEL COMPUTER SCIENCE: COURS! Wiis itreplacs the minimum wlueeg.minimun ¢ numbers ‘This means the new value is the minimum, so the next time a value is compared, 's checking it with the new minimum value Example 1 Find the smallest number input by a user: Minimum + 9999 //initialise minimum to large value Number ~ 1 WHILE Nunber >= 1 D0 //loop until the user enters 0 Number = iNEU(*Enter @ munber or 0 to stop") IP Wunber < Minimum THEN // chock if the nunber entered is smaller ep, //the current minimum Minimum + sunber //i¢ true then make minimum Because the nun ExoIF ENDWTLE Example 2 Find the smallest number in an array of data Minimum + 999999 FOR X + 0 70 LENGTH (tunberarray) TF Numberarray(X] < minimum THEN Minimum + Numberarray (x) ding the maximum ‘The maximum value is the largest value within a set, For example, the marks for a class ‘are entered and the highest mark isthe maximum. maximum: the largest iteminase To do this ina program you need to of data Initialise @ maximum variable to be a small value, beyond those that will be entered, eg. Maxcimum = -9999 Compare each value tothe maximum variable,e. 1° swuner > Masciswum, © Hits it replaces the maximum value, eg. Haxinum © tunber ‘This means the new value is the maximum, so the next time it is checking it with the new maximum value ‘Value is compared, Example 1 Find the largest number input bya user Maximum ~ -9999 //initialise maximum Number © 1 WHILE Nunber unt the user ent Number = INPUT(*Enter a nunber IF Numbes to small vaiue rs 0 © 0 to stops > Maximum THEN // check, ee the eu a fe Maximum © Number ENDIF Hig 170 > 7 Algorithm design and problem solving example 2 uth rps ember in an ay of data: vaximin ~ -1 // initialise the naximin value to a onal nuaber FOR X © 0 TO LENGTH (Numberarray) [ieheck Af the mumber enter IF NumberArray[(X] > Maximum THES 3 Maximum © NumberArray (3) if true store the value in maximum END: NEXT X Finding the average ‘The average here is referring to the mean. This is the total of all the values added the mean together, then divided by how many numbers there are, of a set of values, the For example, if the data is 1,3,5,8,4,2,6,9, total divided by the the average = (1+3+5+8+444+6+9)/8=40/8=5 a " To do ths in a program you need to use the count and total from earlier in this section. ‘The average is then calculated with the formulae 20tal / Count. Example 1 Find the average of the numbers input by a user: Count + 0 //initialise the count to 0 qotal + 0 //initialise the total to 0 Munber © 1 WHILE Munber >= 1 DO //loop until the user entera 0 Nunber + INPUT(‘Enter a nunber or 0 to stop’ Total © Total + Number //ad4 the nunber entered to the total Count + Count +1 //add 1 to the count EDWHILE Example 2 Find the average of the numbers in an aray of data count + 0 //initialise the count to 0 Total « 0 //initialise the total to 0 FOR X © 0 10 LENGTH (NunberArray Total - Total + MunberArray[X) //add value to tota Count = Count + 1 //add 1 to count NEXT x Wnennes ‘teacher needs a system to calculate the lowest, highest and average mark their 30 students got in a test out of 100. Getting started 1 Identify the code required to work out the minimum and maximum values ina set of data NCE: COURSEBOOK cre > CAMBRIDGE IGcse™ & 0 LEVEL coMPUTER 5 bers 2 Recap how to calculate an aversg® of aset of num 30 times. 10 loop 3 3, 30 umbers will need entering. Recap How loop Practice - s fo 1 Write an algorithm to allow the teacher t0 center the matt 30 students . smallest (minimum) marl calculate and output he 5 2 Amend the program to calculate and output the ‘Amend the program to gest (maximum) mark tecaleulate and output the average mare 4 Amend the program Challenge Extend the program to count how many go! many got above the average number of marks Extend the program to work out how many students tore = distinction. 0 or more = merit 4 oF more = ‘below the average, and how got each level. 80 oF pass. Below 40 = fall Questions 21° Explain the difference between totalling and counting. 22. A program allows numbers to be ‘entered between 20 and 200, and finds the aor nec and largest entered. Identify appropriate values to initialse the variables Smallest and Largest. 23. Write an algorithm to input 40 numbers and 24 Write an algorithm to input 100 numbers and output the smallest and largest output the total and average, Validation on input ‘Validation is the checking of data that is input to make sure it is reasonable, and/or within set bounds. For example, making sure that a number is entered for an age or limiting the range of numbers that ean be entered validation: the checking of data to make s reasonabl within set bour. oo ACTIVITY 7.7 Have you ever entered data to be told that it si it is invalid? What tenter some data (but stay safe and make sure itis not personel date). sonal data What restrictions do they have? Are there s Fe some spaces that enter data in? Do some of them give you a set stucture tof ty tee adateas__/__/___? Saas re ‘Are these all controlled with validation rules? ample, ‘There are different types of validation, ed 7 Algorithm design and problem solving Range check A range check assesses whether data is within one or rust be between Oand 100. A date must be boone nou ‘Must be before today’s date Range checks can be programmed using selection tha keeps asking you enter a value units vag, nn AY EE OF Within a Loop For example, an age Example 1 Using sletion: ‘This algorithm wil check whether @ numbers higher than 1 and les than 10 Number + INPUT(*Enter a number between IF Number < 1 OR Number > 19 THEN OUTPUT(*Invalia") ELSE ourPur(*Valia*) ENDIF 1 and 10") Example 2 Using loop: ‘This algorithm will check if « number is higher than 1 and ess than 10, It will continually ask for a value to be input until the number is valid Munber = INPUT(*Enter a nunber between 1 and 10") WHILE Number < 1 OR Nunber > 10 DO OUTPUT( "Invalid please try again") Munber « INPUT() ENDWHILE Length check ‘Alegt check will check the numberof character that are preset Thisould ina Sting for example he length of “hello word is 1 te spice to achrace Iau be ina variable, fr example in this xample 8 il be op ‘Thedata = *123 ABC!" (OUTPUT (LENGTH (TheData) ) ‘The length of a piece of data can be found using a varity of commands depending on ‘he language you are using. The following are all valid and there are many more theData.Jength() LENGTH (theData) UBN(theData} theData. len length check canbe programmed using selection or iteration Example 1 Using sleton: ‘Thisalgorithm will check if the data input has 10 or less characters to be invalid, ‘otherwise (10 or more) it is vali, range check: a type of validation that makes sure data is between the minimum and length check: a type of validation that checks the number of characters is within a set limit

You might also like