Download - AS computing
1
AS Computing
C.Cardew
April 2005
2
WJEC AS Computing
• C1.2 Algorithms
• C1.4 Sorting
• C2.7 File Organisation
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
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)
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
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)
7
Algorithms
• Many different ways of expressing Algorithms:
– Pseudo code– Structured English– Flow Charts– Annotated code
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!
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?
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
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
12
Flow ChartsStart
Wet Hair
Set WashCountTo 0
Add 1 to value of WashCount
Rinse Hair
Lather Hair
WashCount=2?
Stop
Yes
No
Flow chart to explain how to wash your hair
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?
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 cup of tea
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
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
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
input(name)
input(age)
output(message)
write(‘Please enter your name’);
readln(name);
write(‘Please enter your age’);
readln(age);
writeln(‘How young you are’,name)
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}
19
Algorithm ConstructsPseudocode example Pascal code
input(name)
input(age)
if age <18 then
output(young message)
else
output(old message)
end if
write(‘Please enter your name’);
readln(name);
write(‘Please enter your age’);
readln(age);
if age<18 then
begin
writeln(name);
writeln(‘How young you are.’)
end
else
begin
writeln(name)
writeln(‘You’re getting old now!’)
End
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.
21
Algorithm Constructs
Pseudocode example Pascal code
for 20 times do
draw a line
end do
for i: = 1 to 20 do
begin
for j := 1 to 40 do write (‘-’);
writeln
end
For 20 times do statement 1; statement 2;
end do
Iteration:(a)…a fixed number of times:
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
Repeats the loop to draw the line 20 times
Draws one line by drawing 40 ‘dashes’
22
Algorithm Constructs
Pseudocode example Pascal code
repeat
input (mark)
add mark to total
until mark = 0
repeat
writeln(‘Enter mark (0 to end)’);
readln(mark);
total := total + mark
until (mark = 0);
repeat statement 1; statement 2; until(condition is met)
Iteration:(a)…until a condition is met:while(condition is true) do
statement 1; statement 2;
endwhile
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
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)
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
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
input (mark)
if mark > 50 then add 1 to counter
end if
until mark = -1
output (counter)
You need to be careful that you do not ‘process’ the rogue value!
counter := 0
repeat
input (item)
if item is not the rogue value then process item
end if
until item = rogue value
output (counter)
The general ‘shape’ of an algorithm which uses a rogue value will be:
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
28
program Product;
var Num1, Num2, Answer : integer; {GLOBAL variables}
procedure DrawLine; {PROCEDURE}
var i : integer; {LOCAL variables}
begin
for i = 1 to 20 do write(‘-’);
writeln;
end;
begin
write(‘Please enter first number ’);
readln(Num1);
write(‘Please enter second number ‘);
readln(Num2);
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
Example:
Two numbers are input and their product is calculated.
This program uses a subroutine (procedure) which draws a line of 20 dashes.
The subroutine is called twice in the main program.
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
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
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! = 1
2! = 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
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
33
Algorithm constructs• Logical OperationsThere are four main logical operators which may be used in algorithms(programs)…
• NOT, AND, OR, XOR
Examples
• 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
34
Algorithm constructs
Input X
Input Y
Output
1 1 0
1 0 1
0 1 1
0 0 0
Input X
Input Y
Output
1 1 1
1 0 0
0 1 0
0 0 0
Input X
Output
1 0
0 1
Input X
Input Y
Output
1 1 1
1 0 1
0 1 1
0 0 0
AND
XOR
OR
NOT
35
Algorithm constructs
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
A 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 are true or false
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’))
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
38
Algorithm constructs
procedure Frenzy (Num : integer)
var i, fred :integer;
begin
fred := 5;
for i := 1 to Num do
begin
fred := fred – i;
writeln (fred);
end;
writeln(‘Done’);
end;
Instruction Num i fred Output
Start up 3
fred := 5 3 5
for i := 1 to Num 3 1 5
fred := fred – i 3 1 4
writeln(fred) 3 1 4 4
for i := 1 to Num do 3 2 4
fred := fred – i 3 2 2
writeln(fred) 3 2 2 2
for i:= 1 to Num do 3 3 2
fred := fred – i 3 3 -1
writeln(fred) 3 3 -1 -1
writeln(‘Done’) 3 3 -1 Done The trace table for the procedure
Frenzy(3) would be
Example:
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
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 i.e.zero 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
41
Algorithm constructs program repeatadd
var
num : integer
total : integer
begin
repeat
writeln(‘Enter number or 0 to end: ’);
readln(num);
total := total + num;
writeln(‘Total = ‘, total);
until num = 0;
end
An algorithm for repeated addition.
Do a dry run for the values of num 1 to 4 and then 0 to finish
Which equals?
Note the difference
When assigning a value (make it equal to), add a colon before the sign (:=)
When testing a value (is it equal to?), use a plain = sign
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
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:
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
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
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.
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]
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.
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
50
Sorting - BubbleSortbegin
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}
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’.
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...
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!
54
Sorting - Insertion Sort• Pseudocode:• 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 ptr
for 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
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 itself)