C1 01 Algorithm
C1 01 Algorithm
C1 01 Algorithm
1 Algorithms
• A solution to a problem with the following characteristics is called an
algorithm
• Unambiguous
• A sequence of steps
• Can be used again and will always provide the same result
• Provide a solution to a problem
• Most problems have more than one solution, so different algorithms
can be created for the same problem
Successful Algorithm
• Three points to consider when deciding whether an algorithm is
successful or not:
• Accuracy – lead to expected output
• Consistency – must produce the same result each time it is run
• Efficiency – must solve the problem in the shortest possible time, using as few
computer resources as possible
Algorithm vs. Program
• They are related but not the same
OR (X = 1) OR (Y = 5) X is equal to 1 or Y is equal to 5.
Fee = 20
No
Paul’s solution
Mary’s solution
Age > 60
Pretest loop
Posttest loop
Creating Algorithm - Iteration
• For loop
• Repeats the statements written in the
loop-body a specific number of times.
• Can be implemented as an increment or a
decrement loop.
WHILE {condition} DO
{loop-body}
END WHILE
Creating Algorithm - Iteration
• Iteration
• REPEAT…UNTIL-loop
• When a program comes to a REPEAT…UNTIL loop, the loop-body will continue
to run until a condition called the ‘exit condition’ is met.
• A posttest loop
REPEAT
{loop-body}
UNTIL {condition}
A Mark > 90
B 80 < Mark ≤ 90
C 65 < Mark ≤ 80
D 50 < Mark ≤ 65
F Mark ≤ 50
Example - Tracing and Testing Algorithms
Test Expected Test for Test for Test for
data result extreme value boundary case invalid data
0 F ✓
• Determining the
50 F
expected results ✓
and reasons for 65
using the chosen
80
test data
• Write down the 90
expected output
and determine 100
the reasons of
105
using such test
data. −20
def bubbleSort(arr):
n = len(arr)
• E.g. when programmers write the ‘print’ command they do not have
to bother about all the details of how this will be accomplished
• E.g. a driver turning the ignition key to start a car does not have to
understand how the engine works or how the spark to ignite the
petrol is generated
Abstraction – Example – Noughts and Crosses
Question
• What is the purpose of the algorithm?
• Explain how the algorithm calculates the total amount
that should be paid?
• Give two variables that are used in the algorithm.
• Two of the constructs are labelled A and B. State the
type of each construct.
• The Wong family is visiting the park. The family
consists of two children, one ages 10 and one aged 5,
their two parents, an aunt and their grandfather, who is
aged 78. Use the algorithm to calculate how much the
family should have to pay for entry.