 Pseudocode and Algorithms

Presentation on theme: "Pseudocode and Algorithms"— Presentation transcript:

Pseudocode and Algorithms

Definition An 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 bed Take shower Get dressed Eat breakfast Go to work You may have the actions correct but the order might be wrong. Go to work ………… Wet!

In the practical exercises for Topic One (Data
Representation and Manipulation) we followed step-by- step instructions to convert decimal numbers to binary The step-by-step instructions were an example of an algorithm In the practical exercises for Topic Two we developed a number of short Pascal programs based on algorithms We will now begin to consider how to develop longer, more sophisticated algorithms as a means of designing computer programs

Algorithms involve combination of
Sequence English imperative sentences, doing one thing after another Procedure a mini-algorithm, that is a part of a bigger algorithm Selection choice of action depending on a comparison or test. This uses the IF..THEN..ELSE statement Repetition Doing the same thing over and over again. There are two statements to use here - While..Do and For...Do

Algorithm involving Selection
get up if it is a weekday and you don’t cultivate a beard and you have stubble on your chin then find a razor shave endif

Calculating Pension Rights - Algorithm involving Selection
If age > 60 then calculate pension payable endif To make this algorithm easy to understand we use a procedure with a clear name. The logic of this procedure is described in another (mini) algorithm

A Mini Algorithm (or Procedure)
Calculate Pension Payable if gender is female then calculate woman’s pension else check for man’s pension endif More Procedures!

Another Procedure if age > 65 then pay man’s pension endif
Check for Man’s Pension if age > 65 then pay man’s pension endif And so on…

Procedures in Pascal The following is the main body of a Pascal program that uses procedures to do something simple!

The Two Procedures We will look at this again in the tutorial and practical sessions

Procedures help us to write readable programs
We can break complex programs up into simple procedures Ideally procedures should be functionally cohesive i.e. they should do just one thing and it should be clear what that thing is from their name If a procedure has to do anything complex it can be broken down into other procedures So we might create a program that has a main body that looks like a high-level algorithm. For example:

Using indents Using 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 structure If DrinkType = Coffee then If CoffeeType = “Latte” then Cost = £2.15 Else Cost = £1.75 EndIf Cost = £0.75 If DrinkType = Coffee then If CoffeeType = “Latte” then Cost = £2.15 Else Cost = “£1.75 EndIf Cost = £0.75

An algorithm that finds the average of two numbers
Input: Two numbers Add the two numbers Divide the result by 2 Return the result End Easier to read than Pascal. Easy to translate into Pascal.

An algorithm to change a numeric exam result to a pass/no pass grade.
Input: One number if the number is greater than or equal to 40 then Set the grade to “pass” else Set the grade to “fail” End if Return the grade End

An algorithm to change a numeric exam result to a letter grade.
Input: One number if the number is between 70 and 100 then Set the grade to “A” if the number is between 50 and 69 then Set the grade to “B” if the number is between 40 and 59 then Set the grade to “C” Return Grade End

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 integers Set Largest to 0 while (more integers) if (the integer is greater than Largest) then Set largest to the value of the integer End if End while Return Largest End

An algorithm to find the largest of 1000 numbers.
Input: 1000 positive integers Set Largest to 0 Set Counter to 0 while (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 while Return Largest End

Find largest number using a procedure
Input: A list of positive integers Set Largest to 0 while (more integers) FindLarger End while Return Largest End

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 if End

How to use Pseudocode Before 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.

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. Example We want to print four number 7s For Times = 2 to 8 step 2 Print “7” Next

A Problem in Need of a For Loop
Find the first 20 Fibonacci numbers. The Fibonacci sequence starts with two numbers: 1 1 Each 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:

Algorithm FibonacciNum1 := 0; FibonacciNum2 := 1;
For count := 1 to 20 do Display Fibonacci2 temp := Fibonacci2; Fibonacci2 := Fibonacci1 + Fibonacci2; Fibonacci1 := Temp End For This algorithm seems to solve the problem. To test it I need to translate it into Pascal

Pascal Code First I need to declare the variables:
Then I can code up the solution:

Pascal Code

Output from the Program
If we enter this program into Free Pascal then Compile and Run it – we see the following output It works!

While loops This 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.

While loops While/Loop Example: Counter = 1 While Counter <= 10
Print Counter Counter = Counter + 1 Loop What this does is print the value Counter over and over for values starting at 1 and ending at 9.

A Problem in Need of a While Loop
Display all powers of 2 that are less than Display 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

Pascal Code for this Problem
while number <= do Begin linecount := linecount + 1; (* Print a comma and space unless this is the first number on the line *) if linecount > 1 then write (', '); (* Display the number *) write (number); (* Print a comma and go to the next line if this is the last number on the line UNLESS it is the last number of the series *) if (linecount = numperline) and not (number * 2 > 20000) then begin writeln (','); linecount := 0 end; (* Increment number *) number := number * 2; end; (* while *) writeln; Note how helpful the comments are!

Output from this Program

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 = 1 Repeat Print Counter Counter = Counter + 1 Loop Until Counter > 10

WARNING!! If you fail to provide:
a condition in a While structure which fails to become False or a condition in an Until structure which fails to become True Then The structure will never terminate and will result in an error called an “Infinite Loop”

Guidelines Note 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.

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 to explain it, but sometimes it helps!

Practicals and Tutorial Questions
Time to develop some algorithms and translate them into code Have a look at the tutorial and practical questions for this topic before moving on to the review questions

Review Questions What 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?