2 DefinitionAn algorithm is a series of actions placed in the order they are to be executed in order to solve a particular problem.So getting ready for work in the morning might be:Get out of bedTake showerGet dressedEat breakfastGo to workYou may have the actions correct but the order might be wrong.Go to work ………… Wet!
3 In the practical exercises for Topic One (Data Representation and Manipulation) we followed step-by-step instructions to convert decimal numbers to binaryThe step-by-step instructions were an example of analgorithmIn the practical exercises for Topic Two we developed anumber of short Pascal programs based on algorithmsWe will now begin to consider how to develop longer,more sophisticated algorithms as a means of designingcomputer programs
4 Algorithms involve combination of SequenceEnglish imperative sentences, doing one thing afteranotherProcedurea mini-algorithm, that is a part of a bigger algorithmSelectionchoice of action depending on a comparison or test.This uses the IF..THEN..ELSE statementRepetitionDoing the same thing over and over again. There aretwo statements to use here - While..Do andFor...Do
5 Algorithm involving Selection get upif it is a weekdayand you don’t cultivate a beardand you have stubble on your chinthenfind a razorshaveendif
6 Calculating Pension Rights - Algorithm involving Selection If age > 60 thencalculate pension payableendifTo make this algorithm easy to understandwe use a procedure with a clear name.The logic of this procedureis described in another (mini) algorithm
7 A Mini Algorithm (or Procedure) Calculate Pension Payableif gender is female thencalculate woman’s pensionelsecheck for man’s pensionendifMore Procedures!
8 Another Procedure if age > 65 then pay man’s pension endif Check for Man’s Pensionif age > 65 thenpay man’s pensionendifAnd so on…
9 Procedures in PascalThe following is the main body of a Pascal program that uses procedures to do something simple!
10 The Two ProceduresWe will look at this again in the tutorial and practical sessions
11 Procedures help us to write readable programs We can break complex programs up into simple proceduresIdeally procedures should be functionally cohesivei.e. they should do just one thing and it should be clear what that thing is from their nameIf a procedure has to do anything complex it can be broken down into other proceduresSo we might create a program that has a main body that looks like a high-level algorithm.For example:
12 Using indentsUsing indents in pseudocode helps to show the program structure and can be useful in checking for programming errors. In the example shown here you can see where one structure has been nested within another and where the control is passed back to the original structureIf DrinkType = Coffee thenIf CoffeeType = “Latte” thenCost = £2.15ElseCost = £1.75EndIfCost = £0.75If DrinkType = Coffee thenIf CoffeeType = “Latte” thenCost = £2.15ElseCost = “£1.75EndIfCost = £0.75
13 An algorithm that finds the average of two numbers Input: Two numbersAdd the two numbersDivide the result by 2Return the resultEndEasier to read than Pascal.Easy to translate into Pascal.
14 An algorithm to change a numeric exam result to a pass/no pass grade. Input: One numberif the number is greater than or equal to 40 thenSet the grade to “pass”elseSet the grade to “fail”End ifReturn the gradeEnd
15 An algorithm to change a numeric exam result to a letter grade. Input: One numberif the number is between 70 and 100 thenSet the grade to “A”if the number is between 50 and 69 thenSet the grade to “B”if the number is between 40 and 59 thenSet the grade to “C”Return GradeEnd
16 An algorithm to find the largest of a set of numbers when you do not know the number of numbers. Input: A list of positive integersSet Largest to 0while (more integers) if (the integer is greater than Largest) then Set largest to the value of the integer End ifEnd whileReturn LargestEnd
17 An algorithm to find the largest of 1000 numbers. Input: 1000 positive integersSet Largest to 0Set Counter to 0while (Counter less than 1000) if the integer is greater than Largest then Set Largest to the value of the integer End if Increment Counter End whileReturn LargestEnd
18 Find largest number using a procedure Input: A list of positive integersSet Largest to 0while (more integers) FindLarger End whileReturn LargestEnd
19 Procedure: Find larger Input: Largest and current integer if (the integer is greater than Largest) then Set Largest to the value of the integer End ifEnd
20 How to use PseudocodeBefore you start typing your program on the computer, sit down and think about what you want to do.Run through in your head the steps you think you need and then write them down.THIS is what your pseudocode is.
21 Control loops The For/Next/Step Loop Probably the simplest form of looping.You specify a start and end number and the size of the step. For example if we start at two and move towards the end number of eight in steps of two we will have:Four stages.ExampleWe want to print four number 7sFor Times = 2 to 8 step 2Print “7”Next
22 A Problem in Need of a For Loop Find the first 20 Fibonacci numbers. The Fibonacci sequence starts with two numbers:1 1Each subsequent number is formed by adding the two numbers before it. 1+1=2, 1+2=3, 2+3=5, etc. This forms the following sequence:
23 Algorithm FibonacciNum1 := 0; FibonacciNum2 := 1; For count := 1 to 20 doDisplay Fibonacci2temp := Fibonacci2;Fibonacci2 := Fibonacci1 + Fibonacci2;Fibonacci1 := TempEnd ForThis algorithm seems to solve the problem.To test it I need to translate it into Pascal
24 Pascal Code First I need to declare the variables: Then I can code up the solution:
26 Output from the Program If we enter this program into Free Pascal then Compile and Run it – we see the following outputIt works!
27 While loopsThis loop repeats as long as (While) a stated condition is met.In the next example, the variable Counter has to be less than or equal to 10 in order for the looping to continue.Note a While/Loop structure will not execute even once if the While condition is violated (False) the first time through.
28 While loops While/Loop Example: Counter = 1 While Counter <= 10 Print CounterCounter = Counter + 1LoopWhat this does is print the value Counter over and over for values starting at 1 and ending at 9.
29 A Problem in Need of a While Loop Display all powers of 2 that are less thanDisplay the list in a properly formatted manner, with commas between the numbers.Display five numbers per line. The output should look like this:1, 2, 4, 8, 16,32, 64, 128, 256, 512,1024, 2048, 4096, 8192, 16384
30 Pascal Code for this Problem while number <= doBeginlinecount := linecount + 1;(* Print a comma and space unless this is the firstnumber on the line *)if linecount > 1 then write (', ');(* Display the number *)write (number);(* Print a comma and go to the next line if this isthe last number on the line UNLESS it is thelast number of the series *)if (linecount = numperline) and not (number * 2 > 20000) thenbeginwriteln (',');linecount := 0end;(* Increment number *)number := number * 2;end; (* while *)writeln;Note how helpful the comments are!
32 Repeat Until/Loop Example: This loop repeats Until the Counter variable exceeds 10. Note a Do Until/Loop structure will not be entered if the Until condition is already True on the first encounter.Counter = 1RepeatPrint CounterCounter = Counter + 1Loop Until Counter > 10
33 WARNING!! If you fail to provide: a condition in a While structure which fails to become False ora condition in an Until structure which fails to become TrueThenThe structure will never terminate and will result inan error called an “Infinite Loop”
34 GuidelinesNote that although the pseudocode does not use exact programming language syntax, it does use loops or If/Then/Else statements, where needed.You should not use exact syntax in your pseudocode, because someone should be able to look at your pseudocode and from that write a program in ANY language.
35 Guidelines It should be specific enough, though, to give an idea of what type of program-flow you are thinking of.Note also that comments can help explain parts.In general, your pseudocode shouldn't need comments toexplain it, but sometimes it helps!
36 Practicals and Tutorial Questions Time to develop some algorithms and translate them into codeHave a look at the tutorial and practical questions for this topic before moving on to the review questions
37 Review QuestionsWhat is conditional looping? How does it differ from unconditional looping?What is the maximum number of times a While-Do structure will be executed?What is the maximum number of times a Repeat-Until structure will be executed?What is the maximum number of times a For-To structure will be executed?Do we need three different types of loop structure in a programming language?Can one type of control structure be nested inside another?