Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
33 views

Algorithms in Programming and Pseudo Code Practice Readings

The document discusses algorithms and pseudo code. It covers algorithm design techniques like stepwise refinement, sequence, selection, and iteration. It also provides examples of each technique and discusses the components of pseudo code like variables, assignment, input/output, selection, and repetition.

Uploaded by

carlynn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Algorithms in Programming and Pseudo Code Practice Readings

The document discusses algorithms and pseudo code. It covers algorithm design techniques like stepwise refinement, sequence, selection, and iteration. It also provides examples of each technique and discusses the components of pseudo code like variables, assignment, input/output, selection, and repetition.

Uploaded by

carlynn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Algorithms in Programming and Pseudo Code Practice

1. Algorithms in Programming
An algorithm is a description of how a specific problem should be solved. The following
algorithmic constructs will be discussed:
1. Stepwise refinement.
2. Sequence.
3. Selection.
4. Iteration.
1.1. Algorithmic Design: Stepwise refinement of algorithms
Stepwise refinements are variation of the divide and conquer where the processes to be
carried out are broken down into a number of steps, each of which can be described by
an algorithm that is smaller and simpler.

The sub-algorithms can be broken into smaller pieces which are simpler; and can be
expressed in a more detailed manner.

Refinement of the algorithm continues until each of its steps is sufficiently detailed and
precise to allow execution by the computer processor.
Example 1:
Design an algorithm for a domestic servant robot to make a cup of instant coffee.
(1) boil water
(2) put coffee in cup
(3) add water to cup

The steps in this algorithm are not detailed enough for the robot to be able to execute
them. Each step must therefore be refined into a sequence of simpler steps, each
specified in more detail than the original. Thus the step:

(1) boil water

Might be refined into


(1.1) fill boiler with water
(1.2) switch on boiler
(1.3) wait until the water boils
(1.4) wait for the boiler to switch off

Similarly,

1
(2) put coffee in cup

Might be refined into


(2.1) open coffee jar
(2.2) dip spoon and fill with coffee
(2.3) drop spoonful into cup
(2.4) close coffee jar

And
(3) add water to cup

Might be refined into


(3.1) pour water from boiler into cup until cup is full
The last refinement does not actually increase the number steps in the algorithm, but
simply re-expresses an existing step in more detail.

In a nutshell, after a number of refinements, every step of the algorithm will be


understood and executed by the robot. At this stage the algorithm is complete. The
overall refinement is shown in the table below:

2
1.2. Algorithmic Design: Sequence
The coffee-making algorithm of the previous section involves simple steps to be
executed sequentially:
 Steps are executed one at a time and not in parallel,
 Each step is executed only once,
 Execution order is the order in which steps are written,
 Execution of the last step terminates the algorithm.

Such an algorithm is not flexible as it cannot be adapted to respond to different


circumstances. For example think about the unavoidable situation that at some point the
coffee jar is empty or the situation when the robot needs to handle several requests for
coffee or custom requests for milk or sugar.

The conclusion is that an algorithm which is merely a combination of steps in a


sequence will not get us far and more flexible structures are needed in order to design
algorithms capable of realistically depicting real life situations.

1.3. Algorithmic Design: Selection


This is a more advanced structure which provides flexibility is the selection. Using the
selection, we can refine step 2.1 of the previous coffee-maker algorithm example as
follows:
(2.1.1) take coffee jar off the shelf
(2.1.2) if jar is empty
then get new jar from cupboard
(2.1.3) remove lid from jar

We see the introduction of a condition in step 2.1.2. The condition is “jar is empty”. If
the condition is met, then a conditional instruction applies which is “get new jar from
cupboard”.
This is the general form in which the selection structure is expressed:

If condition
then step

The condition can be used to specify any kind of circumstance which when true needs
the execution of a certain step.

3
Usually, in real life there are alternatives in case a particular circumstance emerges. To
cope with such situations, the selection structure can be extended so as to provide
alternative steps to be executed.

Example 2:
Design algorithm for driving with a car to work which needs to cater for the occasion that
the car needs fuel:
(1) start car
(1.1) if fuel indicator on
then drive to the nearest gas station
else drive to work

In this case we can select between two alternative steps in which case the condition
(fuel indicator on or off) dictates which step is to be executed based on the situation we
are faced with.
Example 3:
More flexibility can be introduced to algorithms by taking advantage of nested selection.
Consider the following algorithm for a pedestrian crossing a street at the zebra crossing.
if light is green
then proceed
else stop

This example contains one selection and can be further improved as:
if no light or light is blinking green
then proceed with caution
else if light is red
then stop
else proceed

This later example contains two selections. The second selection is nested inside the
first and is executed only if the light is red.

1.4. Algorithmic Design: Iteration


Iteration is the repetition of a process in a computer program. Iterations of functions are
common in computer programming, since they allow multiple blocks of data to be
processed in sequence. This is typically done using a "while loop" or "for loop". These
loops will repeat a process until a certain number or case is reached. In a nutshell,
iteration means repeating the same step several times.

1.4.1. Iterative algorithms should obey three important principles, namely:


a) An iterative process repeats (iterates) a certain sub-process;

4
b) Each iteration should change at least one value;
c) There should be some condition under which the iteration terminates. And the
iteration should reach that state.

Example 4:
Design algorithm for eating breakfast cereal might consist of these steps:

(1) put cereal in bowl


(2) add milk to cereal
(3) spoon cereal and milk into mouth
(3.1) repeat step 3 until all cereal and milk is eaten
(4) rinse bowl and spoon

What we see in step 3.1 is the introduction of a condition which is a situation that is
checked every time iteration occurs. The condition is introduced with the words repeat
and until. Without the condition, the algorithm would not know when to stop. The
condition, in this case, will be to check if all the milk and cereal are eaten. If that
condition is False (there is still milk and cereals in the bowl), then another iteration
occurs. If the condition is True (there is no more milk and cereal in the bowl), then no
more iterations occur.

The general form is:


repeat
part of the algorithm
until condition

This means that the part of the algorithm between repeat and until is executed
repeatedly until the condition specified after until holds true. The condition which comes
after until is called a terminating condition.

1.5. Summary of the algorithmic constructs


Stepwise refinement: This approach uses divide and conquer principle. It breaks the
algorithm into smaller pieces which are easily executable.
Sequence: A series of steps that are carried out sequentially in the order which they are
written. Each step is carried out only once
Selection: One of two or more alternatives should be chosen.

5
Iteration: Part of the algorithm should be capable for repetition, either a defined number
of times or until a certain condition has been met.

2. Pseudo Code Practice


The listed below is a brief explanation of Pseudo code as well as a list of examples and
solutions. Pseudo code can be broken down into five components, namely:
 Variables.
 Assignment.
 Input/output.
 Selection.
 Repetition.

A variable has a name, a data type, and a value. There is a location in memory associated
with each variable. A variable can be called anything or be given any name. It is considered
good practice to use variable names that are relevant to the task at hand.

Assignment is the physical act of placing a value into a variable. Assignment can be shown
using the following:
set = 5;
set = num + set;

The left side is the variable a value is being stored in and the right side is where the variable
is being accessed. When a variable is assigned a value, the old value is written over with
the new value, so the old value is gone. x = 5 does not mean that x is equal to 5; it means
set the variable x to have the value 5. Give x the value 5, make x equal to 5.

Both Input and output deal with an outside source (can be a user or another program)
receiving or giving information. An example would be assuming a fast food restaurant is a
program. A driver (user) would submit their order for a burger and fries (input), they would
then drive to the side window and pick up their ordered meal (output.)
 Output – Write / display / print
 Input – Read / get / input
Selection construct allows for a choice between performing an action and skipping it. It is
our conditional statements. Selection statements are written as such:

6
if (conditional statement)
statement list
else
statement list
Repetition is a construct that allows instructions to be executed multiple times (IE repeated).
In a repetition problem count is:

– initialized
– Tested
– incremented

Repetition problems are shown as:

while (condition statement)


statement list

2.1. Pseudo Code Examples


Example 1: Write pseudo code that reads two numbers and multiplies them together
and print out their product.
Example 2: Write pseudo code that tells a user that the number they entered is not a 5
or a 6.
Example 3: Write pseudo code that performs the following: Ask a user to enter a
number. If the number is between 0 and 10, write the word blue. If the number is
between 10 and 20, write the word red. if the number is between 20 and 30, write the
word green. If it is any other number, write that it is not a correct colour option.
Example 4: Write pseudo code to print all multiples of 5 between 1 and 100 (including
both 1 and 100).
Example 5: Write pseudo code that will count all the even numbers up to a user defined
stopping point.
Example 6: Write pseudo code that reads in three numbers and writes them all in sorted
order.

7
Solutions
Example 1: Write pseudo code that reads two numbers and multiplies them together and print
out their product.

Pseudo code:
Read num1 , num2
Set multi to num1*num2
Write multi

Example 2: Write pseudo code that tells a user that the number they entered is not a 5 or a 6.
Example 2 Solution 1:

Pseudo Code:
Read isfive
If (isfive = 5)
Write "your number is 5"
Else if (isfive = 6)
Write "your number is 6"
Else
Write "your number is not 5 or 6"

Example 2 Solution 2:
Pseudo Code:
Read isfive
If (isfive = 5 or isfive = 6)
Write "your number is a 5 or 6"
Else
Write "your number is not 5 or 6"

Example 2 Solution 3:
Pseudo Code:
Read isfive
If (isfive is not 5 and isfive is not 6)
Write "your number is not 5 or 6"

8
Example 3: Write pseudo code that performs the following: Ask a user to enter a number. If the
number is between 0 and 10, write the word blue. If the number is between 10 and 20, write the
word red. if the number is between 20 and 30, write the word green. If it is any other number,
write that it is not a correct colour option.
Pseudo Code:
Write "Please enter a number"
Read colornum
If (colornum >0 and colornum <= 10)
Write blue
else If (colornum >10 and colornum <= 20)
Write red
else If (colornum >20 and colornum <= 30)
Write green
else
Write "not a correct color option"

Example 4: Write pseudo code to print all multiples of 5 between 1 and 100 (including both 1
and 100).
Pseudo Code:
Set x to 1
While (x < 20)
write x
x = x*5

Example 5: Write pseudo code that will count all the even numbers up to a user defined
stopping point.
For example, say we want to see the first 5 even numbers starting from 0.
well, we know that evens numbers are 0, 2, 4, etc.
The first 5 even numbers are 0, 2, 4, 6, 8.
The first 8 even numbers are 0, 2, 4, 6, 8 ,10 ,12, 16

9
Example 5 solution 1:
Pseudo Code:
Read count
Set x to 0;
While (x < count)
Set even to even + 2
x=x+1
write even

Example 5 solution 2:

Pseudo Code:
Read count
Set x to 0;
While (x < count)
Set even to even + 2
x=x+1
write even

Example 6: Write pseudo code that reads in three numbers and writes them all in sorted order.
Example 6: Solution 2:

Pseudo Code:
Read num1, num2, num3
If (num1 < num2 < num3)
Write num1 , num2, num3
else If (num1 < num3 < num2)
Write num1 , num2, num3
else If (num2 < num1 < num3)
Write num2, num1, num3
else If (num2 < num3 < num1)
Write num2, num3, num1
else If (num3 < num1 < num2)
Write num3, num1, num2
else If (num3 < num2< num1)
Write num3, num2, num1

10
Example 6: Solution 2:
Pseudo Code:
Read num1, num2, num3
If (num1 < num2)
If (num2 < num3)
Write num1, num2, num3
Else
If (num3 < num1)
Write num3, num1, num2
Else
Write num1, num3, num2
else
If (num1 < num3)
Write num2, num1, num3
Else
If (num3 < num2)
Write num3, num2, num1
Else
Write num2, num3, num1

Pseudo Code Exercise-1: Write pseudo code that will perform the following.

a) Read in 5 separate numbers.


b) Calculate the average of the five numbers.
c) Find the smallest (minimum) and largest (maximum) of the five entered numbers.
d) Write out the results found from steps b and c with a message describing what they are
e) Write pseudo code that will calculate a running sum. A user will enter numbers that will
be added to the sum and when a negative number is encountered, stop adding numbers
and write out the final result.

11

You might also like