You are on page 1of 67

CAPE

Information Technology –
UNIT 1
Module 03 – Objective 07 - 10
• Explain the concept of an algorithm;
• Identify the necessary properties of ‘well designed’ algorithms;
• Identify ways of representing algorithms;
• Develop algorithms to represent problem solution;
Introducing Algorithms
 One main type of problem-solving is algorithmic, i.e. working out all
possible alternative steps towards the problem solution.
 An algorithm is a problem-solving strategy that guarantees
that you will arrive at a solution - a precise systematic
method for producing a specified result.
 It involves systematically exploring and evaluating all possible solutions
until the correct one if found.
 Though time-consuming, an algorithm is a method that always
produces a solution to a problem sooner or later.
Introducing Algorithms
 Algorithms generate a correct solution, if you are aware of all the
possibilities - but in real life, that is a big "IF". Often algorithms simply
require too much effort.
 This strategy originated in the field of mathematics, where its
application can produce guaranteed solutions. They are, therefore,
well-suited to computers.
 Computers can rapidly sort through hundreds, thousands, and
even millions of possible solutions without growing tired or suffering
from boredom.
But algorithms aren’t restricted to computers…
 If you've ever baked a cake or followed a recipe of any kind, then you've
used an algorithm. In fact, we use them in every day life:
 Some algorithms are learned—arithmetic.
 Some we figure out ourselves—looking up a phone number.
 Others require written instructions—recipe, assembly
instructions, driving directions.
 Here’s an example:
“Suppose that you want to determine your car’s mileage. You probably would
do this by filling the tank and noting your mileage. The next time you get gas,
you note the mileage again, determine the number of miles you drove, and then
divide the miles driven by the amount of gas you put in. The result tells you your
car’s gas mileage, which you generated by using a simple algorithm.”
Importance of Algorithms in Problem-Solving
 The algorithm is used in every area of computer science:
 It is used to make robots move on Mars, assemble cars and assist with operations.

 Algorithms are at the heart of how your browser is able to display


web pages and provide buttons and menus for you to use.

 They are what make it possible for antilock brakes in your car to work
by reacting to your foot on the brake pedal and regulating the automatic pumping of
your brakes to maintain control of the vehicle.

 Many algorithms are used in your favourite video games to add realism, make your
characters move, and react to your cat-like movements!

All of this and more is a result of the algorithm concept.


Importance of Algorithms in Problem-Solving
In order that a task be carried out on a
computer, a method or technique for the task
must be described very precisely in terms of the
different steps.
An algorithm is a description of the steps of a
task, using a particular technique.
Writing an algorithm is one of the first steps
taken in preparing a task to be done by a
computer.
Importance of Algorithms in Problem-Solving
All hardware components, including the CPU,
memory devices, and storage devices, operate
based on algorithms.
Software is written using a computer
programming language. These programming
languages are developed to implement
algorithms.
Therefore, all software programs are essentially
composed of several algorithms.
Necessary Properties of a
“Well-Designed” Algorithm
Six Essential Properties of ‘Well-Designed’ Algorithms

1. Input specified
 Data to be transformed during the computation to
produce the output.
 Must specify type, amount, and form of data.

2. Output specified
 Data resulting from the computation—intended result
 It is possible to have no output.
Six Essential Properties of ‘Well-Designed’ Algorithms
3. Definiteness
Specify the sequence of events
Details of each step, including how to handle
errors.

4. Effectiveness
The operations are doable.
Six Essential Properties of ‘Well-Designed’ Algorithms
5. Finiteness
Must eventually stop.

6. Clear & Unambiguous


Each step (or phase), and their input/outputs
should be clear and must lead to only one meaning.
Components of Algorithms
In the systematic development of well-structured algorithms, it is
appropriate for the logic component (i.e. what the algorithm does) to be
specified before the control component (i.e. how the algorithm
does it).
 The logic component expresses (determined by the programmer) the
domain-specific part of an algorithm. It both determines the
meaning of the algorithm and influences the way it behaves.
 The control component (determined by the computer) determines the
general-purpose problem-solving strategy. It affects only the
efficiency of the algorithm, without affecting its meaning.
Ways of Representing Algorithms

Algorithms can be expressed in various formats that are independent of


a programming language or hardware device. Three (3) ways of
representing algorithms are:

 Narrative expressed in a natural language (e.g. English).

 Pseudocode is a mixture of natural language and


mathematical notation.

 Flowcharts are diagrams that use particular symbols and


arrows to represent algorithms.
Representing Algorithms as
NARRATIVES
Algorithms Represented as Narratives
 The algorithm is expressed in words forming complete
sentences using natural language; describing the concept
of the algorithm, and the story defines the transition over
time.
 A natural language or ordinary language is any language
that develops naturally in humans through use and repetition
(typically, in their first few years of life) without any conscious
planning or premeditation of their own.
Algorithms Represented as Narratives
Narrative Example 1:

Cut each carrot crosswise in half. In a 3-quart saucepan,


over medium hear, heat carrots to boiling. Cover and simmer
for about 20 minutes or until carrots are tender crisp. Add
butter, brown sugar and lemon juice. Cook until sugar is
completely dissolved.
Algorithms Represented as Narratives
Narrative Example 2:
Ask the user for the mass of an object. The input is a number that
represents the number of kilograms for the object.
Convert the kilograms to pounds using the formula
Force = Mass * Acceleration, where force is the weight, and the
acceleration is the gravitational constant of 9.8m/s-2.
If the object weights more than 2000, give the output that the object
weighs at least a ton, or else output that the object weighs less than a ton.
Algorithms Represented as Narratives
 It is well known that people comprehend and remember
information presented in a context of a story better than as
a simple listing of facts. Reason being that a story is
more appealing to the reader.

 However, drawbacks to Narratives include:


 It is difficult to write a complex algorithm, this way.
 It is not clear how to create a computer language description
of an algorithm from a natural language description of it.
Representing Algorithms as
PSEUDOCODE
Algorithms Represented as Pseudocode
 Pseudocode is used by programmers to develop algorithmic
solutions. It is universal for programmers because it does not
depend on a particular programming language.

 It essentially is English with some defined rules of structure


and some keywords that make it appear a bit like program code.
Algorithms Represented as Pseudocode

 Some of the keywords used in pseudocode include:

 for start and finish


BEGIN, END or START, STOP

 for selection  for repetition (pre-test)


IF, THEN, ELSE, ENDIF WHILE, DO, ENDWHILE

 for repetition (post-test)


REPEAT, UNTIL
Algorithms Represented as Pseudocode
 Guidelines for pseudocode:
 Keywords are written in capitals.

 Structural elements come in pairs, e.g. for every


BEGIN there must be an END, for every IF there must be
an ENDIF, and for every WHILE there must be an
ENDWHILE, etc.

 Indenting is used to show structure in the algorithm.

 Often times, each line of the algorithm is numbered for ease


of reference.
Algorithms Represented as Pseudocode
Pseudocode Example:
1. START
2. OUTPUT "Enter the object's mass (in kilograms):"
3. INPUT mass
4. Object weight = mass * 9.8
5. IF Object weight > 2000
6. THEN
7. OUTPUT "The object weighs at least a ton"
8. ELSE
9. OUTPUT "The object weighs less than a ton"
10. STOP.
Representing Algorithms as
FLOWCHARTS
Algorithms Represented as Flowcharts
 Flowcharts are a great complement to describing algorithms in
pseudocode.
 Flowcharts are a diagrammatic method of representing entire
algorithms.
 They use an intuitive scheme of showing operations in boxes
connected by lines and arrows that graphically show the flow of control
in an algorithm.
 It is sometimes more useful to have a visual representation of an algorithm
than just a pseudocode representation.
Algorithms Represented as Flowcharts
 Flowcharts are made up of the following box types connected by lines
with arrowheads indicating the flow.
Algorithms Represented as Flowcharts
 Just as ordinary characters must be put together in certain ways to
produce well-formed words, and words must be put together in
certain ways to produce well-structured sentences…
 These flowchart elements must be connected in certain ways to
form accepted structures, and the structures connected in certain
ways to form well-structured algorithms.
 The flowcharting structures for sequence, selection and repetition are
discussed later on.
Algorithms Represented as Flowcharts
Pseudocode: Flowchart:
1. START
2. OUTPUT "Enter the object's mass (in kilograms):"
3. INPUT mass
4. Object weight = mass * 9.8
5. IF Object weight > 2000
6. THEN
7. OUTPUT "The object weighs at least a ton"
8. ELSE
9. OUTPUT "The object weighs less than a ton"
10. STOP.

Flowcharts can represent entire algorithms just like pseudocode.


Developing Algorithms - Input,
Output, Arithmetic Operations
Algorithm Development – INPUT Operations
 The INPUT command is how the algorithm gets the data it needs to
perform its computation.
 For example, if the algorithm is computing the average grade for
an exam given to a class, the algorithm needs to get all the test
scores. This is the job of the INPUT command.
 An input statement starts with the INPUT command and is followed by
the variables that represent values provided by the user of the algorithm.
 Examples of input statements:
 INPUT student name, student numeric grade
 INPUT length and width
Algorithm Development – OUTPUT Operations
 Output statements display information for the user.

 For example, the algorithm may need to display a prompt to


ask the user to input the test grades; and at the end, it
needs to display the average.

 An output statement is used for these tasks.

 An output statement begins with the OUTPUT command that


is followed by what should be displayed.
Algorithm Development – OUTPUT Operations
 Examples of output statements:
 OUTPUT "Enter Name:"
 OUTPUT final grade
 OUTPUT "The area is", TheArea, "and the circumference is ",
TheCircumference

 Output statements can display quoted information or non-quoted


information.
 Quoted information such "Enter Name:" will display the information
verbatim. However, non-quoted information such as final grade,
TheArea, and TheCircumference are variables that represent values.
Algorithm Development – Arithmetic Assignments
 Arithmetic assignment statements save the result of a computation
inside a variable.

 It is one of the most heavily used statements in algorithms.

 The arithmetic assignment statement uses the equal sign, = ,


just like in math.

 On the left side of the equal sign is the variable, and on the right
side is the expression that performs the computation using
standard mathematical notation.
Algorithm Development – Arithmetic Assignments

 Examples of arithmetic assignment statements:


 PriceAverage = (price1 + price2 + price3) / 3
 TheArea = Pi * Radius2
 TheSlope = (Y2 - Y1) / (X2 - X1)
 On the right side of the statement is the arithmetic expression
using standard mathematical notation.

 The left side is where the result of the computation is held for
further processing.
Developing Algorithms –
Control Structures
Control Structures
The flow of control of an algorithm conforms to one of three control
structures:
 Sequence – Sequential statements are executed in order,
one after the other. You don't have to make decisions.
 Selection – Selection statements (aka conditional statements) are decision-
making statements that alter the flow of execution in the algorithm,
depending on the conditions that control their execution.
 Looping and Iteration – (aka repetitive statements) these statements enable
an algorithm to repeat until a certain condition is met or a count is
reached.
Control Structures
The flow of control of an algorithm conforms to one of three control
structures:

NOTE: In all cases there is only one entry point to the


structure and one exit point as indicated by the dashed Looping & Iteration
boxes.
Algorithm Control Structures -
Sequential
Control Structures - Sequential
Example: consider the following recipe:
 1. Preheat the over to 350 degrees.
 2. Combine the cake mix, milk, and eggs in a bowl.
 3. Beat the mixture for 3 minutes on medium speed.
 4. Pour the batter into a cake pan.
 5. Bake the cake in the oven for 45 minutes.
Control Structures - Sequential
 In the example, the recipe is composed of sequential
statements.

 You are to follow each statement one after the other


with no deviation.

 You do not perform a later step until you've completed the


previous ones.

 These statements usually perform input, output, and


arithmetic assignment operations.
Control Structures - Sequential
 In pseudocode, sequence is  In a flowchart,
expressed as in the following sequence is
illustration: expressed as
1. process 1 in the
2. process 2 following
3. ... illustration:
4. ...
5. process n
Control Structures - Sequential
 Example of sequence in  Example of
pseudocode: sequence in a
1. START flowchart:
2. Fill a kettle with water
3. Boil the water in the kettle
4. Put the tea leaves in the pot
5. Pour boiling water in the pot
6. STOP
Control Structures - Sequential
 Example of sequence in  Example of
pseudocode: sequence in a
1. START flowchart:
2. OUTPUT “Enter Score:”
3. INPUT Score
4. Sum = Sum + Score
5. OUTPUT “Score = “, Sum
6. STOP
Algorithm Control Structures -
Selection
Control Structures – Selection
 Unlike sequential statements, selection or conditional statements may execute
differently, depending on the conditions that control their execution.

 A selection statement can be used to choose a specific path in the


algorithm, dependent on a condition.

 Recall the narrative example:


Cut each carrot crosswise in half. In a 3-quart saucepan, over medium hear, heat
carrots to boiling. Cover and simmer for about 20 minutes or until carrots are
tender crisp. Add butter, brown sugar and lemon juice. Cook until sugar is
completely dissolved.

 This recipe has two instances of conditional statements.


Control Structures – Selection
 The first one refers to simmering for 20 minutes or until the carrots
have become tender crisp.
 This means that the simmering process may take 20
minutes, give or take a few minutes.

 This can be rewritten as follows:

IF carrots are tender crisp and they have been simmering for close to
20 minutes, THEN stop simmering; otherwise keep simmering.
Control Structures – Selection
 The second example is where you are to cook the final mixture until the sugar
is dissolved.

 This could be rewritten as follows:

IF sugar is dissolved, THEN stop cooking; otherwise, continue


to cook.

 Now you can see that there are options in both cases to either continue the
cooking process or stop it.

 These are not sequential statements because there are two possible
actions based on an observed condition.
Control Structures – Selection
 In pseudocode, there will be two types of conditional statements:
 the IF-THEN statement and
 the IF-THEN-ELSE statement
which are responsible to selecting the next action to control
the flow of the algorithm, based on the satisfaction of a condition.
Control Structures – Selection
 In pseudocode, sequence is  In flowcharts, sequence is
expressed as in the following expressed as in the following
illustration: illustration:
IF condition
THEN
process 1
ENDIF
Control Structures – Selection
 In pseudocode, sequence can  In flowcharts, sequence can
also be expressed as in the also be expressed as in the
following illustration: following illustration:
IF condition
THEN
process 1
ELSE
process 2
ENDIF
Control Structures – Selection
 In a flowchart it is most important to indicate which path is to be followed
when the condition is true, and which path to follow when the
condition is false. Without these indications the flowchart is open
to more than one interpretation.
 There are two acceptable ways to represent a decision in all of the
structures:
 The condition is expressed as a statement and the
two possible outcomes are indicated by True, False.
 The condition is expressed as a question and the two
possible outcomes are indicated by Yes, No.
BRAIN CHALLENGE #1

1) Write a set of instructions to describe when to answer the


phone.
a. Present the set of instructions as Pseudocode.
b. Represent the set of instructions as a flowchart.

2) Write a set of instructions to follow when approaching a set


of traffic control lights.
a. Present the set of instructions as Pseudocode.
b. Represent the set of instructions as a flowchart.
Control Structures – Selection
 The IF-THEN-ELSE example shows that the else part of the statement
does not have a condition like the IF-THEN portion does.
 The condition for the ELSE is implicitly the opposite of the
IF-THEN condition.
 You can combine these IF-THEN and IF-THEN-ELSE statements in
various ways, allowing great flexibility in creating algorithms for
complex problems.
For example…
Control Structures – Selection
 Example 1:  Example 1 is where the
1. IF Number > 0 first ELSE has a
2. THEN condition, and the last
3. Output "Number is positive" ELSE actually goes with
4. ELSE the second IF; it is the
5. IF Number = 0
opposite of a number not
6. THEN
7. Output "Number is 0" equal to 0.
8. ELSE  This is called a
9. Output "Number is negative" cascading
10. ENDIF IF-THEN-ELSE
statement.
This allows flexibility in creating algorithms to solve problems.
Control Structures – Selection
 Example 2:  Example 2 demonstrates
nested IF statements. In
1. IF Choice = True
this case, an
2. THEN IF-THEN-ELSE is nested
3. IF Found = True within an IF-THEN
4. THEN statement.
5. Output "The name was found"  There is no limit to the
6. ELSE degree of nesting, and
7. Output "The name was not found" you can have
8. ENDIF IF-THEN statements
9. ENDIF nested within
IF-THEN-ELSE
statements.
This allows flexibility in creating algorithms to solve problems.
BRAIN CHALLENGE #2

1) Explain the Selection Examples 1 & 2.


2) Draw the flowchart for the Selection Examples 1 & 2.
Algorithm Control Structures –
Looping & Iteration
Control Structures – Looping & Iteration
Example: consider the following recipe:
 With the mixer running at the lowest speed, add the eggs,
one at a time, making sure each egg is fully incorporated
before adding the next.
 Whisk egg with molasses, salt, pepper, celery salt, mustard,
Worcestershire sauce, 1/4 cup of the evaporated milk, and 1/2 the
glaze mixture until combined.
Control Structures – Looping & Iteration
 These statements convey a repeated activity.
 In the example, the statement, "Whisk egg with molasses, salt... until
combined" implies that you have to repeatedly whisk the mixture
until an objective is achieved.

 In this case, the objective is met when you observe the


mixture is completely combined.

 This is where looping statements come in handy.


Control Structures – Looping & Iteration
 In pseudocode, WHILE-DO and REPEAT-WHILE
statements provide the repetition and looping capability
to algorithms.

 Both rely on conditional expressions. As long as the


conditional expression is true, the loop continues, but
when it is false, the loop ends.
Control Structures – Looping & Iteration
 In pseudocode, pre-test  In flowcharts, pre-test repetition is
repetition is expressed as in expressed as in the following example:

the following example:


WHILE condition is True
process 1
process 2
...
...
process n
ENDWHILE

Each time a loop executes, it is called an iteration.


Control Structures – Looping & Iteration
 In pseudocode, post-test  In flowcharts, post-test repetition
repetition can also be can also be expressed as in the
expressed as in the following following example:
example:
REPEAT
process 1
process 2
...
...
process n
UNTIL condition id True

Each time a loop executes, it is called an iteration.


Control Structures – Looping & Iteration
 Consider Example 1:  This first example is of
WHILE-DO loop which continues
1. WHILE Number < Max to execute the three
2. DO
statements inside it until the
3. OUTPUT “Enter Score:”
max number of scores are
4. INPUT Score
entered.
5. Sum = Sum + Score
6. ENDWHILE  This is considered the
pre-test loop because it tests
the condition BEFORE executing
any of the statements in its body.

Each time a loop executes, it is called an iteration.


Control Structures – Looping & Iteration
 Consider Example 2:  This second example is
a REPEAT-WHILE loop
1. REPEAT
that reads in grocery
2. OUTPUT “Enter grocery item:”
items from the user.
3. INPUT storeItem
4. Count = Count + 1  This is considered the
5. WHILE Count < Num post-test loop that
executes once, THEN it
tests the condition.

Each time a loop executes, it is called an iteration.


CASE STUDY EXAMPLE

PROBLEM:
An algorithm to express the
A lift remains positioned at the ground logic of controlling a lift:
floor level of a building with the doors
shut whenever it is not in use. When a call START
button is pressed on any floor, the lift REPEAT
Check all buttons
moves to the required floor and the lift UNTIL a button is pressed
doors open. Move to the required floor
Open the doors
STOP
Write an algorithm to express the logic of
controlling the lift.
BRAIN CHALLENGE #3

1) Identify the type of loop used in the algorithm provided


for the Case Study.

2) Draw the flowchart for the algorithm provided for the


Case Study.

3) Develop another algorithm for the case study as


Pseudocode, using the next type of loop.

4) Draw the flowchart for the algorithm provided for the


Case Study.
BRAIN CHALLENGE 4

 Consider the following flowchart


to represent the algorithm for
solving the problem of who
serves in a tennis match.

 Represent the algorithm as:


1. Pseudocode.
2. A Narrative.

You might also like