AS computing


Published on

This slideshow is intended to support year 12 students studying A level Computing. It explains algorithms; what they are and how they are used and constructed

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

AS computing

  1. 1. AS Computing C.Cardew April 2005 1
  2. 2. WJEC AS Computing• C1.2 Algorithms• C1.4 Sorting• C2.7 File Organisation 2
  3. 3. C1.2 Algorithms• Algorithm constructs – Explain the use of selection, iteration, counts, rogue values, standard functions, subprograms (procedures, subroutines and user-defined functions) as each appears in algorithms. – Explain and analyse segments of code involving sequence, selection, repetition and subprograms• Scope of variables – Identify the scope of variables and distinguish between local and global identifiers – Explain the need for, and use of, parameters• Logical operations – Recognise logical operations AND, OR, NOT and XOR and apply them to programming and package use.• Algorithm Testing – Use given data to dry run an algorithm – Select and use algorithm data to dry run an algorithm 3
  4. 4. C1.4 Sorting and Searching• Sorting and Searching – Explain the need for searching – Understand non-recursive sorting algorithms – Explain the binary search (binary chop) and linear search, and be able to apply the respective formulae – Describe appropriate circumstances for the use of each technique – (Candidates will not be expected to reproduce detailed algorithms) 4
  5. 5. C2.7 File Organisation• File Organisation – Explain the purpose of files in data processing and distinguish between master and transaction files. – Define a file in terms of records and fields. – Explain the use of fixed and variable length fields and records – Describe how files may be created, organised, updated and processed by programs – Describe serial and sequential file access methods and their use. – Understand algorithms for sequential file access. (Candidates will not be expected to reproduce detailed algorithms) – Select and justify the appropriate form of file access for a particular application 5
  6. 6. C1.2 Algorithms• What is an algorithm?• A well ordered collection of unambiguous and effectively computable operations that, when executed, produces a result and halts in a finite amount of time.• A sequence of instructions used to solve a problem. (Sequence implies an order to the instructions) 6
  7. 7. Algorithms• Many different ways of expressing Algorithms: – Pseudo code – Structured English – Flow Charts – Annotated code 7
  8. 8. Algorithm example• ‘…a well ordered collection…of operations…that produces a result…and stops’• Consider the following algorithm taken from the back of a shampoo bottle: – Step 1 Wet Hair – Step 2 Lather – Step 3 Rinse – Step 4 Repeat• Not so well ordered – In step 4 what should be repeated? Wet hair again? Rinse again? These are ambiguous statements – Also the algorithm never stops! 8
  9. 9. Algorithm example• A better way to write the algorithm to solve the shampooing problem: – 1. Wet your hair – 2. Lather your hair – 3. Rinse your hair – 4. Lather your hair – 5. Rinse your hair – 6. Stop, you have finished shampooing your hair• The operations are well ordered, unambiguous, produce a result and then stops• But is this an elegant way of writing an algorithm? 9
  10. 10. Algorithm example• A even better way to write the algorithm to solve the shampooing problem: – 1. Wet your hair – 2. Set the value of WashCount to 0 {this is a count} – 3. Repeat steps 4 to 6 until the value of WashCount equals 2. {this is called a loop} – 4. Lather your hair – 5. Rinse your hair – 6. Add 1 to the value of WashCount – 7. Stop, you have finished shampooing your hair• There are a number of ‘algorithm constructs’ that are now being used that warrant further explanation 10
  11. 11. The algorithm language• Psuedocode• The final algorithm example to shampoo your hair has introduced English statements that look very much like the statements used in most programming languages• The name of this notation is called Pseudocode and is used to design and represent algorithms.• Why not just write the algorithm as a formal language such as Pascal, C++ or Java?• Because this forces us to deal immediately with such low level language issues as punctuation, grammar and syntax 11
  12. 12. Flow Charts StartFlow chart to Wet Hairexplain howto wash your Set WashCount To 0hair Lather Hair Rinse Hair Add 1 to value of WashCount WashCount No =2? Yes Stop 12
  13. 13. Pseudocode example• Making an apple and blackberry pie• Step 1 Make the pastry• Step 2 Make the filling• Step 3 Pour the filling into the pastry• Step 4 Bake at 350ºC for 45 minutes• OK for a baker, but for you an me?• A little ambiguous…how do you make pastry? Shouldn’t you put the pastry into a dish first? 13
  14. 14. Pseudocode example• Making an apple and blackberry pie• Step 1 Make the pastry – 1.1 measure one and a third cups of flour – 1.2 sift the flour – 1.3 mix the sifted flour with one and a half cups of water – 1.4 roll into 2 rectangles• Step 2 Make the filling – 2.1 Peel apples – 2.2 De-core the apples – 2.3 Slice the apples – Etc• Now write an algorithm for making a cup14 tea of
  15. 15. Algorithm constructs• Making a cup of tea • Pour one and half cups of water into a kettle • Switch the kettle on • Put one teabag into a cup • When the kettle has boiled the water pour water into cup • Wait for about 2 minutes • Remove teabag • Pour some milk into the cup of tea • Put one teaspoon of sugar into the cup • Stir the tea in the cup with a teaspoon • Taste the tea to check if its sweet enough • If yes then enjoy tea • If no then add another teaspoon of sugar • Stir the tea in the cup with a teaspoon • Taste the tea to check if its sweet enough • If yes then enjoy tea 15
  16. 16. Algorithm constructs• Making a cup of tea • Pour one and half cups of water into a kettle • Switch the kettle on • Put one teabag into a cup • When the kettle has boiled the water pour water into cup • Wait for about 2 minutes • Remove teabag • Pour some milk into the cup of tea • Is sugar needed • Repeat • Put one teaspoon of sugar into the cup • Stir the tea in the cup with a teaspoon • Taste the tea to check if its sweet enough • If yes then enjoy tea • Until tea is sweet enough • End 16
  17. 17. Algorithm constructs• The basic ‘constructs’ of an algorithm – The ‘collection of operations’ also known as a ‘sequence of instructions’. Sequence • A number of instructions processed one after the other • E.g. – statement 1; – statement 2; – statement 3; Pseudocode example Pascal code write(‘Please enter your name’); input(name) readln(name); input(age) write(‘Please enter your age’); output(message) readln(age); writeln(‘How young you are’,name) 17
  18. 18. Algorithm constructs• Selection – The next instruction or operation to be executed depends on a ‘condition’ . – This introduces the if…then…else format. – The if..then structure is also a simple ‘branch’ – E.g. If (condition is true) then statement 1; else statement 2; end if {If the condition is true then statement 1 is performed, if it is not true then statement 2 is performed}18
  19. 19. Algorithm ConstructsPseudocode example Pascal code write(‘Please enter your name’);input(name) readln(name);input(age) write(‘Please enter your age’);if age <18 then readln(age); output(young message) if age<18 thenelse begin output(old message) writeln(name);end if writeln(‘How young you are.’) end else begin writeln(name) writeln(‘You’re getting old now!’) End 19
  20. 20. Algorithm constructs• Iteration• A number of instructions is repeated• This introduces the idea of a loop• A loop is used whenever the same operations or instructions are repeated over and over again – each time using different items of data• An example we saw earlier was with the shampooing problem where the ‘repeat…until loop’ was introduced. 20
  21. 21. Algorithm ConstructsIteration:(a)…a fixed number of times: For 20 times do statement 1; statement 2; Repeats the loop to draw end do the line 20 timesPseudocode example Pascal code for i: = 1 to 20 dofor 20 times do begin draw a line for j := 1 to 40 do write (‘-’);end do writeln end Draws one line by drawing 40 ‘dashes’ Note in the program that a loop is used to draw the line. This is an example of a ‘nested loop’ – a loop inside another loop 21
  22. 22. Algorithm ConstructsIteration:(a)…until a condition is met: repeat while(condition is true) do statement 1; statement 1; statement 2; statement 2; until(condition is met) endwhilePseudocode example Pascal coderepeat repeat input (mark) writeln(‘Enter mark (0 to end)’); add mark to total readln(mark);until mark = 0 total := total + mark until (mark = 0); 22
  23. 23. Algorithm constructs• Variables and Constants:• Data used by a program is stored in variables or constants.• Variables are used to hold data which can be changed or varied by a program• Constants are used to hold data which are never changed• Variables and constants are, in reality, locations in the computer’s memory• The programmer does not have to keep track of these locations• Variables and constants are given names by the programmer, who can refer to them by using these names• Pascal contains several built in or standard data types for variables e.g. integer and real• Integer variable: used to store whole numbers from –32768 to +32767• Real variable: used to store numbers with or without decimal fraction parts. E.g. 34.678, 0.0123• Constants are simply declared to have a certain value 23
  24. 24. Algorithm constructs• Counts• A variable (integer) is used to count values which satisfy a certain condition. (it must be an integer as a loop can only be executed and integral number of times)• Counting always starts from 0, so the value of the variable must be initialised to 0• The following example: 20 exam marks are to be input, how many of them are over 50?.• We will use a variable called ‘counter’ to store the number of marks over 50. – counter:=0 – for x=1 to 20 do – input (mark) – if the mark is over 50 then add 1 to the counter – end if – end do – output (counter) 24
  25. 25. Algorithm constructs• Rogue Values (Sentinel)• A sequence of inputs may continue until a specific value is input• This value is called a rogue value• It must be a value that would not normally arise• For example• If you were entering a list of % marks into a computer• You may need to enter the rogue value ‘-1’ to exit• Useful if you do not wish to specify the number of inputs 25
  26. 26. Algorithm constructs• Rogue Value – A number of marks is to be input (terminated by a rogue value of –1). – How many of the marks are over 50? – Note that –1 is a value which would not arise counter := 0 repeat The general ‘shape’ of an algorithm input (mark) which uses a rogue value will be: if mark > 50 then add 1 to counter counter := 0 end if repeat until mark = -1 input (item) output (counter) if item is not the rogue value then process item end if You need to be careful that you do not until item = rogue value ‘process’ the rogue value! output (counter) 26
  27. 27. Algorithm constructs• Subroutines:• A subroutine is a small section of program which can be ‘called’ (run) from anywhere else in the program, and a s many times as necessary• There are two types of subroutine (in Pascal)• 1. Procedures – which perform a specific task. E.g. draw a box• 2. Functions – which return an answer. E.g. a mathematical calculation• Every subroutine has a name. The subroutine can be called by using its name 27
  28. 28. program Product;Example: var Num1, Num2, Answer : integer; {GLOBAL variables} procedure DrawLine; {PROCEDURE}Two numbers are input var i : integer; {LOCAL variables}and their product is begincalculated. for i = 1 to 20 do write(‘-’); writeln; end;This program uses asubroutine (procedure) beginwhich draws a line of write(‘Please enter first number ’);20 dashes. readln(Num1);The subroutine is write(‘Please enter second number ‘);called twice in the readln(Num2);main program. writeln(Num1:20); {formatted to a width of 20} writeln(Num2:20); DrawLine; {Call procedure} Answer := Num1*Num2; {Calculate answer} writeln(Answer : 20); DrawLine; {Call procedure again} end 28
  29. 29. Algorithm constructs• Scope of Variables• When a variable (or constant) declaration is made, the computer reserves space in memory for storing its value.• The scope of a variable (or constant) is the section of program when a variables value may be accessed.• GLOBAL variables exist throughout the run of a program. They are declared at the start and values may be accessed at any time during the run of the program.• LOCAL variables are declared in a subroutine. They are created when the subroutine is started and only exist for the time the subroutine is run. When the subroutine is completed the memory space reserved for the local variables is released for other use.• It is important that variables and constants should be declared locally if possible. This saves memory space when programs are run 29
  30. 30. Algorithm constructs• Parameters – In the previous example there was a Pascal procedure which drew a line of 20 dashes: • procedure DrawLine; • var i : integer; • begin • for i = 1 to 20 do write(‘-’); • writeln; • end; – But what if wanted line with 10 dashes or 40 dashes etc? – The way to do this is to pass a parameter to the procedure • procedure DrawLine(NumDashes : integer); • var i : integer; • begin • for i = 1 to NumDashes do write(‘-’); • writeln; • end; – Now when we call the procedure we put in brackets the value of the parameter we would like to pass… • DrawLine(40) for a line of 40 dashes • DrawLine(10) for a line of 10 dashes 30
  31. 31. Algorithm constructs• Recursion• This involves calling a function from within itself.• Basically a circular but there must always be an escape route• An example is that of the factorial sequence1! = 12! = 2*1 or 2*1! {because 1! =1)3! = 3*2*1 or 3*2! {because 2! =2*1 = 2)4! = 4*3*2*1 or 4*3! {because 3! =3*2*1 = 6)• You can work out any factorial by multiplying the number by the factorial of the next lower number 31
  32. 32. Algorithm constructs• In Pseudocode (In English but structured code)If the number is 1, then the factorial is 1Else the factorial is the number multiplied by the factorial of the next lower number• From here we go to proper codeIf n = 1 then factorial := 1Else factorial := n*factorial (n-1)• If you call the function with the expression factorial(3), it produces the expression 3*factorial(2) – calling itself.• On the next time round it generates 2*factorial(1), calling itself again• This time it finds the answer 1 and returns the value to the previous call.• This uses the 1 to calculate the value 2, returning that to the top level• Finally the function does 3*2, the answer being 6• This is passed back to the program….pretty neat. HOME 32
  33. 33. Algorithm constructs• Logical OperationsThere are four main logical operators which may be used in algorithms(programs)…• NOT, AND, OR, XORExamples• If NOT (x=100) then output (message)This means that the message will be output if the value of x is not equal to 100• If (x > 19) AND (x < 50) then output (message)This means that the message will be output if both conditions (x > 19) and (x < 50) are true…ie x lies in the range 20…49 (inclusive• If (x > 20) OR (y < 30) then output (message)This means that the message will be output if one or other (or both) of the conditions (x < 20) or (y > 30) are true• If (x < 20) XOR (y < 30) then output (message)This means that the message will be output if one or other (but not both) of the conditions (x < 20) or (y < 30) are true 33
  34. 34. Algorithm constructs Input Input Output Input Input Output X Y X YAND 1 1 1 1 1 1 OR 1 0 0 1 0 1 0 1 0 0 1 1 0 0 0 0 0 0 Input Input Output X Y 1 1 0 Input OutputXOR X 1 0 1 NOT 0 1 1 1 0 0 0 0 0 1 34
  35. 35. Algorithm constructsA is the statement ‘x is less than 50’B is the statement ‘y is greater than 20’For the values of x and y decided of the following statements aretrue or false x y Statement T/F 10 40 NOT B F 30 30 A or B T 30 30 A xor B F 40 10 A and not B T 40 60 not (A xor B) T 35
  36. 36. Algorithm constructs• Logical operators• These logical operators are useful in SQL (Structured Query Language) statements which are used for searching databases• Example• Suppose you wanted to find all the people called Smith who live in Cardiff but do not have either a dog or a cat… your query may be something like• (name = ‘Smith’) and (town = Cardiff) and not ((pet = ‘dog’) or (pet = ‘cat’)) 36
  37. 37. Algorithm constructs• Algorithm testing• How to test your algorithm?• Do a dry run• You write down a table of the instructions which are executed.• You then note the values of all the constants and variables as each instruction is executed 37
  38. 38. Algorithm constructsExample: procedure Frenzy (Num : integer) Instruction Num i fred Output var i, fred :integer; Start up 3 begin fred := 5 3 5 fred := 5; for i := 1 to Num 3 1 5 for i := 1 to Num do fred := fred – i 3 1 4 begin fred := fred – i; writeln(fred) 3 1 4 4 writeln (fred); for i := 1 to Num do 3 2 4 end; fred := fred – i 3 2 2 writeln(‘Done’); writeln(fred) 3 2 2 2 end; for i:= 1 to Num do 3 3 2 fred := fred – i 3 3 -1 writeln(fred) 3 3 -1 -1The trace table for the procedure writeln(‘Done’) 3 3 -1 DoneFrenzy(3) would be 38
  39. 39. Algorithm constructs• Begins and ends are ignored – they do not affect the values• Each time the loop instruction (for i:= 1 to Num) is executed the value of i is incremented• The parameter value is immediately entered at the beginning• Even if the procedure does nothing sensible, it is a good procedure because it does not use values or results from other procedures.• i.e we can test it on its own 39
  40. 40. Algorithm constructs• Selection of Test Data• When testing an algorithm, you need to run a sequence of tests.• If it works once, that does not mean it will work every time!• Select… • Data which is normal • Data which is extreme • Data which is incompatible i.e data of the wrong type • Data which is non existent or null data• Example• If you are testing a procedure which calculates the VAT on the price of a purchased item, choose • Sensible prices e.g.£12.50 • Very large or very small prices e.g.£0.01 or £12,000,000,000,000,000.00 • Try giving it a string e.g ‘Hello’ • Try £0.00 40
  41. 41. Algorithm constructsprogram repeatadd An algorithm for repeated addition.var num : integer Do a dry run for the total : integer values of num 1 to 4 and then 0 to finishbegin repeat Which equals? writeln(‘Enter number or 0 to end: ’); Note the difference readln(num); total := total + num; When assigning a value writeln(‘Total = ‘, total); (make it equal to), add a until num = 0; colon before the sign (:=)end When testing a value (is it equal to?), use a plain = sign 41
  42. 42. Sorting – Bubble Sort• If you had to find a name in a very long list…is it quicker if the list is jumbled up or sorted into alphabetical order?• The answer is pretty obvious• To SORT data is to place the data in order (numerical or alphabetic)• If the amount of data is small enough to be held in memory then an internal sort may be used.• We need to consider three internal sorts: – 1. Bubble sort – 2. Insertion sort – 3. Quicksort 42
  43. 43. Sorting – Bubble Sort• Bubble Sort• If we consider a list of numbers they can be sorted in ascending or descending order• E.g –9, 2, 3, 3, 5, 21, 56 values are in ascending order• 56, 21, 5, 3, 3, 2, -9 values are in descending order• The numbers to be sorted are stored in array• An array is a variable data type capable of holding a group of values.• Starting at the beginning of the array each pair of consecutive numbers is examined.• If they are in correct order they are left alone but if they in incorrect order they are swapped around.• That is the two numbers in the array are swapped around• To illustrate this consider the set of numbers given above: 43
  44. 44. Sorting – Bubble Sort• Bubble Sort in ascending order• The set of numbers are now jumbled 21, 3, 56, 2, -9, 5, 3• First 21 and 3 are examined and found to be in the wrong order• So they swap positions 3, 21, 56, 2, -9, 5, 3• 21 and 56 are compared; they do not need to be swapped around• 56 and 2 are now examined; they need to be swapped around• The new list becomes: 3, 21, 2, 56, -9, 5, 3• 56 and –9 are now examined; they need to be swapped around• The new list becomes: 3, 21, 2, -9, 56, 5, 3• 56 and 5 are now examined; they need to be swapped around• The new list becomes: 3, 21, 2, -9, 5, 56, 3• 56 and 3 are now examined; they need to be swapped around• The new list becomes: 3, 21, 2, -9, 5, 3, 56 44
  45. 45. Sorting – Bubble Sort• Bubble Sort• The entire list of numbers has now been examined but the numbers are still not in order 3, 21, 2, -9, 5, 3, 56• The above process must be repeated again and again until the numbers are in order.• Each traversal of the list is called a pass• Try the method yourself on paper to determine how many more passes will be required to sort the list completely.• The process seems slow and long winded but a computer can carry out the task much faster 45
  46. 46. Sorting – Bubble Sort• Bubble Sort• The first problem is how to program the computer to decide whether or not another pass is required• Or more simply how to decide whether or not the numbers are completely sorted• We can do this by using a Boolean variable called NoSwaps• At the start of each pass we will set the variable NoSwaps to be true• If at any time during the pass two values have to be swapped around, because they are in the wrong order, NoSwaps will be set to false.• A further pass will take place only if NoSwaps is false.• If, at the end of a pass, NoSwaps is found to be true, then during that pass, the numbers must have all been in the correct order and hence fully sorted. 46
  47. 47. Sorting – Bubble Sort• Bubble Sort• Only one detail remains and that is how to swap two values around.• We will use a loop control variable x to keep track of where we are in the array (which we will call list).• So the current value in the array will be list[x] and next value in the array following list[x] must be list[x+1].• So, when we start examining the numbers in a list and x = 1 then list[x] and list[x+1] actually refer to list[1] and list[2] and so on. 3, 21, 2, -9, 5, 3, 56• To swap two values around now amounts to making sure that list[x] contains the value that was in list[x+1] and that list[x+1] contains the value that was in list[x] 47
  48. 48. Sorting – Bubble Sort• Bubble Sort• At the first sight the following statements seem to be sufficient to carry out the the swapping operation list[x] := list[x+1] list[x+1] := list[x]• But careful consideration reveals that after these instructions have been carried out, both list[x] and list[x+1] contain whatever value was originally in list[x+1].• Whatever was in list[x] is lost because of the first statement• list[x] := list[x+1], copies whatever was in list[x+1] into list[x].• Therefore the contents of list[x] must be stored temporarily in another variable, prior to being set to the value in list[x+1]• We will call this extra variable, temp. 48
  49. 49. Sorting – Bubble Sort• Bubble Sort• The statements required to carry out a swap like this are: temp := list[x] {make a copy of list[x] in temp} list[x] := list[x+1] {copy list[x+1] into list[x]} list[x+1] := temp {copy the original contents of list[x]} {(which are now in temp) into list[x+1]• The complete sorting program, called BubbleSort, is now given: program BubbleSort (input, output); var list : array[1..10] of real; x : integer; NoSwaps : boolean 49
  50. 50. begin Sorting - BubbleSort for x:= 1 to 10 do {Enter the data} begin writeln(‘enter number ‘,x); readln(list[x]); end repeat {Sort the data} NoSwaps := true; for x:= 1 to 9 {Only 9 comparisons required for 10 numbers} begin if list[x] > list[x+1] then begin {Do a swap} temp := list[x]; list[x] := list[x+1]; list[x+1] := temp; NoSwaps := false; {Indicate that a swap has been made.} end; end; until NoSwaps; {If NoSwaps is false go back and do another pass} 50
  51. 51. Sorting - BubbleSort• Note the condition until NoSwaps• This means ‘until NoSwaps is true’ in the repeat..until loop• It is in effect saying:• ‘repeat the loop until a pass has been made during which there were no swaps’. 51
  52. 52. Sorting Insertion Sort• Suppose we need to sort the list:• 21, 12, 32, 17, 19, 25, 26• The sort works by inserting each number in the correct position• It is easier to consider what happens in one pass of the insertion sort:• Suppose we are at the following position• 12, 17, 21, 32, 19, 25, 26• (Three passes have already been done and the numbers 21, 12, 32 and 17 have been ‘inserted’ in the list)• The next number to be inserted is 19…remove it from the list and store it in a temporary position:• 19, 12, 17, 21, 32, , 25, 26• Work back from the blank position.• If the number is bigger than 19 then move it to the right... 52
  53. 53. Sorting Insertion Sort• If the number is bigger than 19 then move it to the right…• 19, 12, 17, 21, , 32, 25, 26• 19, 12, 17, , 21, 32, 25, 26• and then insert the number 19 into the blank position• , 12, 17, 19, 21, 32, 25, 26• The nest number to be inserted is 25…and so on• What would the list look like after the next pass?• ,12, 17, 19, 21, 25, 32, 26• Notes: The insertion sort is a fast sort - faster than the bubble sort for ‘jumbled’ files, but not as fast as the Quicksort! 53
  54. 54. • Pseudocode: Sorting - Insertion Sort• Assume the n records are held in an array Key[0…n], with Key[0] being used to hold the current key being looked at. Key[0] Key[1] Key[2] CurrentKey:= key[counter] , 12, 17, 19, 21, 32, 25, 26 ptr - 1 ptrfor counter = 2 to n {start from the second key} CurrentKey := key[counter]; key[0] := CurrentKey; {move key being looked at to position 0} ptr := counter -1 {set the pointer to the left of blank position} while key[ptr] > CurrentKey do move key[ptr] to key[ptr + 1] {move key one position to the right} ptr = ptr - 1 {get ready to look at the next key to the left} endwhile key[ptr + 1] := CurrentKey {insert CurrentKey into blank position}endfor 54
  55. 55. Sorting - Quicksort• This is a very fast sort.• It works by splitting a list into two sublists• Each sublist is then quicksorted by splitting them into sublists• Which are then quicksorted by splitting them…etc• This internal sort method will be discussed in CP4.• It uses recursion (subroutine calls 55 itself)