Computer Programming Fundamentals Algorithms
Agenda What is an algorithm? How do we record an algorithm? An example The basic building blocks How do we record an algorithm? Flow charts Pseudocode An example Sieve of Eratosthenes 1
Basic building blocks Four principal programming structures Sequence Selection (if … else …) Iteration (loops) Sub-programs (functions) Can construct any algorithm from these basics
What is an algorithm? A ‘recipe’ you use to complete a task Use combinations of the basic building blocks For many common tasks algorithms are already known Eratosthenes 276 – 194 BC Many still to be discovered Factorisation of large numbers
Recording algorithms Flowcharts Pseudocode We have already seen how to describe each of the basic building blocks as a flowchart Graphical They can get cumbersome for more complex algorithms Pseudocode An alternative to flowcharts A generic form of the basic code building blocks Text-based No special software required
Pseudocode Like writing code but…. No predefined format No formal syntax Although it should be unambiguous Allows you to defer decisions about details No compiler or interpreter !! Relatively easy to convert into ‘real’ code In most target languages
Building blocks Sequence Selection Iteration IF - THEN - ELSE SELECT - ENDSELECT Iteration FOR - NEXT WHILE - ENDWHILE REPEAT - UNTIL
Building blocks - sequence Variables A and B each have a value How do we exchange the two? Exchange A and B: Exchange the values in variables A and B: temp = A A = B B = temp Start Finish temp = A A = B B = temp
Building blocks - selection IF-THEN-ELSE Set MAX equal to the larger value in variables A and B: IF A > B THEN MAX = A ELSE MAX = B ENDIF # Set MAX equal to the larger value # in variables A and B: if A > B: MAX = A else: MAX = B 8
Building blocks - selection # Process direction variable: # SELECT CASE direction OF # north: move up if direction == 'NORTH': move("UP") # south: move down elif direction == 'SOUTH': move("DOWN") # east: move right elif direction == 'EAST': move("RIGHT") # west: move left elif direction == 'WEST': move("LEFT") # OTHERWISE error else: bad_move(direction) SELECT Process direction variable: SELECT CASE direction OF north: move up south: move down east: move right west: move left OTHERWISE error ENDSELECT 9
Building blocks - iteration FOR - NEXT A = [1,…] # Process each element # in an Array ‘A’: #FOR k = 0 TO (size_of_A - 1) # process A(k) for k in range(len(A)): process_item(A[k]) Process each element in an Array ‘A’: FOR k = 0 TO (size_of_A - 1) process A(k) NEXT k 10
Building blocks - iteration WHILE - ENDWHILE # Print Fibonacci numbers # less than MAX : A = 0 B = 1 #WHILE B less than MAX while B < MAX : print (B) temp = A+B A = B B = temp Print Fibonacci numbers less than MAX : A = 0, B = 1 WHILE B less than MAX print B temp =A+B A = B B = temp ENDWHILE 11
Building blocks - iteration REPEAT - UNTIL #Calculate average of entered values: count = 0 total = 0 #REPEAT while True: # INPUT x x = int(input("Enter integer:")) count += 1 total += x # INPUT more more = (input("Any more? [Y or N]")).upper() # UNTIL more is not 'yes' if more[0] != 'Y': break #Calculate average print ("Average is ",total/count) Calculate average of entered values: count = 0, total = 0 REPEAT INPUT in count = count + 1 total = total + in INPUT more UNTIL more is not ‘yes’ Calculate average 12
Example Finding prime numbers Sieve of Eratosthenes Finds all primes less than a particular value 13
Sieve of Eratosthenes 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 29 40 41 42 43 44 45 46 47 48 49
The sieve in pseudocode Generate primes using sieve method: INPUT maxprime Create integer array called primes with maxprime elements Initialise primes so that for all x primes[x] = x (…primes[3] = 3, primes[4] = 4, … etc.) Show 1 is not prime by setting primes[1] =0 Initialise current_prime = 2 WHILE current_prime is less than length of primes IF primes[current_prime] indicates a prime (it is not 0) THEN Initialise counter to square of current_prime WHILE counter less than length of primes mark primes[counter] as not prime by setting to 0 increment counter by current_prime END WHILE END IF increment current_prime by 1 ENDWHILE Now print the results: FOR k = 0 TO size of primes IF primes[k] is not 0 THEN k must be a prime so print it NEXT k
Exercises Implement some algorithms defined in pseudocode Implement the ‘Sieve of Eratosthenes’ algorithm