Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Topic  Algorithm

2
LEARNING OUTCOMES
By the end of this topic, you should be able to:
1. Solve problems by using two algorithm representative techniques;
2. Test the algorithm execution process with step-by-step detailing; and
3. Build an algorithm.

 INTRODUCTION
Topic 1 introduced two main phases in developing a program. One of which was
the problem-solving phase, which involves the use of algorithms. In this topic,
we will focus entirely on algorithms, from the aspect of representation up to its
implementation. (From a historical point of view, it was the famous
mathematician Alkhwarizmi (Algorithm) who first introduced the concept of
algorithms.)

In programming, algorithm is a very important process.

Algorithm is a step-by-step problem-solving method in a limited time.

This means that the steps will lead to an end or stop. At every step, the
subsequent action should uniquely be determined by the instructions and data
obtained at that time.

Copyright © Open University Malaysia (OUM)


8  TOPIC 2 ALGORITHM

2.1 ALGORITHMS REPRESENTATION


Algorithms can be conceptual or abstract. Therefore, we need a way to represent
it so that it can be presented to humans and computers. There are two algorithm
representations that will be discussed here, which are the flow chart
representation and the pseudo-code representation.

2.1.1 Flow Chart Representation


Let us have a look at the first algorithm representation, the flow chart. Activities
in the algorithm representation are represented by geometry nodes. Each node
represents a different activity. These nodes will be connected to one another
using arrows that demonstrate the flow or a sequential activity. Below are some
symbols that are used in a flow chart representation.

Figure 2.1: Symbols in a flow chart representation

In order to represent algorithms by using flow charts, we can use the following
as a guide:

(a) Identify the symbol used, according to its function.


(b) Get the right formula.
(c) Make sure that appropriate data is used.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  9

(d) Test the flow chart by tracing each symbol, comparing it with the expected
output.

Based on the guide given above, let us examine the flow chart on starting a car
engine, as shown in Figure 2.2.

Figure 2.2: Flow chart on the process of starting a car engine

ACTIVITY 2.1

Sketch a flow chart for the process of going for a tutorial session.

Copyright © Open University Malaysia (OUM)


10  TOPIC 2 ALGORITHM

2.1.2 Pseudo-code Representation


Pseudo-code is another technique of representing algorithms.

Pseudo-code or false codes are instructions that mimic the program code
(actual program instructions).

Whilst flow charts use diagrams, pseudo-codes are written using phrases or
words. To represent algorithms by using pseudo-codes, we need to follow the
rules of writing pseudo-codes as follows:

(a) Every step in an algorithm should not have more than two actions.

(b) Steps in an algorithm are executed in sequence.

(c) The word End or Stop is used to show that the process has ended.

(d) The action that is allowed includes declaring variable names to identify the
set of variables that have a corresponding data type. Types of data might be
in the form of integer, real, character or others.

(e) To give an initial value to a variable (if applicable).

(f) To use arithmetic symbols to state the addition, subtraction, multiplication


and division operations, as well as brackets to show operation priority.

(g) A <--- B represents assigning the value of variable B to A.

(h) The relational operators below are used to state the relationship between
two values:
(i) < Less than
(ii) <= Less than or equals to
(iii) > More than
(iv) >= More than or equals to
(v) ! = Not equal
(vi) == Equal

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  11

(i) The use of sentences is allowed, if it states the meaning accurately.

(j) Read/Input/Get shows the data given to the algorithm as input.

(k) Print/Report/Write/Output/Display shows the result obtained by the


algorithm.

Example 2.1
Change lb unit to kg.

The pseudo-code is:


1.0 Start.
2.0 Read lb_weight
3.0 kg_weight = lb_weight * 2.5
4.0 Print kg_weight
5.0 End

To test your understanding of the concept, work on the following activity:

SELF-CHECK 2.1

1. Write a pseudo-code to calculate your total savings, after getting a


dividend of 12%.

2. You have been introduced to two techniques of algorithm


representation. Which do you think is more effective? Why?

2.2 ALGORITHM DEVELOPMENT METHOD


In order to build an algorithm, we need to first develop our skills through lots of
practice. There are several general strategies in the process of problem-solving
that can help us build algorithms. The divide and conquer method is one of the
most useful approaches. By using this method, the original problem can be
broken into several sub-problems (divide). Each sub-problem can then be solved
(conquered).

Copyright © Open University Malaysia (OUM)


12  TOPIC 2 ALGORITHM

Below is a guide that we can follow when building algorithms:

(a) Identify the input and output of a problem.

(b) Identify and list the sub-problems. Each problem must be solved, in order
to get the results needed.
(c) For every sub-problem, identify and list the steps that must be taken to
solve it.

Next, we will see how each step is executed.

2.2.1 Identify Input and Output of Problems


To solve a problem, we must first understand it. We would need to identify the
input and output of the problem. The process of problem-solving is usually made
up of three levels, which are: to get input, to do processing on the input and to
display the output or the results obtained. This process is shown in Figure 2.3.

Figure 2.3: Problem-solving process

Input is all the information that is relevant or needed, to execute a process.


Usually the information of the input is inserted in the problem statement given.

Output is the result that is needed. The format of how the output is to be
displayed, has also to be identified, during the construction of the algorithm. One
of the most common format used for displaying output information are tables.
Below is the input and output that have been identified in some problems.

Example 2.2
Determine whether a given year is a leap year or not.

Input: A year
Output: Message „Leap Year‰ or „Not Leap Year‰

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  13

Example 2.3
Calculate the average marks for the course TM 20200.

Input: Marks of every student


Output: Average marks

Example 2.4
Given the buying and selling price of an item, determine whether the
company made a profit, broke even or made a loss.

Input: (i) Buying price (in ringgit)


(ii) Selling price (in ringgit)

Output: Message „Profit‰ or „Break Even‰ or „Loss‰

When the input and output are known, we will need to build a list of formulae
that will relate one to the other. Based on Example 2.4, the general formula
obtained is:

Difference = Selling price ă Buying price


If Difference > 0, Output = „Profit‰
If Difference = 0, Output = „Break Even‰
If Difference < 0, Output = „Loss‰

Notice that we have been introduced to a variable, which is „Difference‰. It is


used to identify the relationship between the input and output. In some cases, a
few assumptions have to be made to form a relationship. The problem modelling
process, which is used by identifying variables and the relationships between
them, is called abstraction.

To test your understanding of input and output, answer the following question.

SELF-CHECK 2.2

Write a formula for Example 2.3.

Before proceeding further, take a short break, as the next section will need your
full attention.

Copyright © Open University Malaysia (OUM)


14  TOPIC 2 ALGORITHM

2.2.2 Identifying Sub-problems


Often, the problems that we get are not problems that can be solved easily. To
solve complex problems, we have to break them into smaller sub-problems first.
Each sub-problem then has to be solved, to get the results needed. Notice how
this process is done by looking at the next example.

Example 2.5
Given the name of a student, calculate the number of ÂaÊs in the name.

Solution:
The name of a student can be made up of more than one word. To count the
number of ÂaÊs in it, we need to get each letter and compare them. We need to
have a variable to act as a counter, to track the number of ÂaÊs that exist. The
letter ÂaÊ can exist in upper case or lower case. For example, in the name
„Najwa Amani‰ there are four ÂaÊs.

Initial Algorithm (Main Steps)


1. Start.
2. Input studentÊs name: studName.
3. Count the number of ÂaÊs in studName.
4. Report result.
5. End.

Step 2 and 4 can be done easily. However step 3 requires refinement. Step 3 looks
like a sub-problem that is easily solved, but if it is to be solved using a computer;
we will need to have detailed steps on how this will be done. Notice how the
refinement is done, by using the guide given next.

2.2.3 Solving Sub-problems


For every sub-problem, we need to identify and list the steps that can be taken to
solve it. This method is called refining step-by-step.

(a) Refining Step-by-step Method


We have identified five main steps in sub-topic 2.2.2. Step 3 however, needs
a detailed explanation. Refer to Figure 2.4 for an explanation of this
method.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  15

Figure 2.4: Step-by-step refinement concept

Now that you understand the refinement concept, here is the complete
explanation on algorithm, re-written for Example 2.5.

1. Start.
2. Input studentÊs name: studName.
3. Count the number of ÂaÊs in studName.
3.1 Set n = 1 and totalA = 0
3.2 Until there are characters to be read, execute the following steps.
After which, continue to step 4.
3.2.1 Read n-character
3.2.2 If n-character is the same as ÂAÊ or ÂaÊ, add 1 to totalA.
3.2.3 Increase n by 1.
4 Report „Number of ÂaÊs is totalA‰.
5. End.

Copyright © Open University Malaysia (OUM)


16  TOPIC 2 ALGORITHM

In this easy example, the number of levels refined is only up to two levels. One of
the main steps which is step 3, is refined to be step 3.1 and 3.2. Then 3.2 is further
refined into steps 3.2.1, 3.2.2 and 3.2.3. For more complex problems, the level of
refinement may increase, with each step being detailed and executable. Below are
a few guidelines in summarising the solution:

(a) At every level of refinement, the sub-problem must be understood


properly. Input/Output analysis must be done for every sub-problem, just
as it is done for the entire problem as a whole.

(b) Sub-problems that have similar processes must be looked at together. This
will prevent overlapping and arrangements can be made for modules or
sub-problems to provide an overall solution.

(c) All sub-problems can be represented in the same way. Therefore, when all
the solutions to sub-problems are combined to create the original problem,
the result from the combination is easier to understand.

2.3 SELECTION STRUCTURE


Selection structure is a structure design that gives a few choices during
execution. The choices made are dependent on the conditions that are given.
There are three types of general selection structures, which are:

(a) Single Selection;


(b) Dual Selection; and
(c) Multi-selection.

2.3.1 Single Selection


Single selection involves testing one condition only. The choice that is given
depends on whether the condition is met or not met. Below is the syntax for the
single selection algorithm.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  17

step a
If <Condition true>
Start_If
step 1
step 2
:
step k
End_If
Step k+1

If the condition is met, step 1 till step k will be executed. Then, step k + 1 is
executed. Alternatively, if the condition is not met, step k + 1 will be executed
without executing step 1 to step k.

Step 1 to step k is also known as the start_if and end_if block. Here we will see
that step k+1 will always be executed whether the condition is met or not met.
Step a which is put before the start_if and end_if block will always be executed
because the testing of the condition is after step a.

Note: Notice the indentations for steps in the block start_if ă end_if are indented
a little bit. This is to show that the steps are dependent on the results that are
obtained from the testing of the condition that is done.

Syntax that is given above can be pictured as a flow chart, as shown in Figure 2.5:

Figure 2.5: Single selection structure flow chart

Copyright © Open University Malaysia (OUM)


18  TOPIC 2 ALGORITHM

Let us now have a look at Example 2.6.

Example 2.6
Determine if the customers deserve to get a discount of RM10.00 from the
total payment charged. Customers will be categorised as deserving if the
total payment is RM60.00.

The algorithm is:


1.0 Start.
2.0 Input total_payment value
3.0 If (total_payment > 60)
4.0 Start_If
4.1 Minus 10 from the total_payment
5.0 End_If
6.0 Report actual total_payment
7.0 End

Note: Words that are written in italics like total_payment are variable names that
are recommended. Variables are words that can receive any type of value. You
are also free to use any other name as a variable. But it is good if the variable
name can reflect the task. As given above, total_payment refers to the total
payment that is charged to the customer.

Let us now trace the algorithm. Let us say the total_payment is RM80.00. Testing
done in step 3.0 is true because 80 > 60. Therefore, the control of the program will
enter the start_if-end_if block. This means that the total_payment will see a
deduction of 10. Then, the control of the program will exit from the block and
execute step 6.0. Therefore, the value of total_payment reported is RM70.00.

ACTIVITY 2.2

What if the total payment is RM48.00? Use the algorithm in Example 2.6
as a reference.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  19

The flow chart is:

Figure 2.6: Flow chart for Example 2.6, single selection structure

Now let us look at the second example.

Example 2.7
Determine the requirement of a student to sit for the examination based on
the number of lab sessions attended. The percentage of attendance at the lab
must be 80%. If it is less than that value, the student is categorised as not
qualified.

The algorithm is given as:


1.0 Start.
2.0 Set value no_of_labs = 10
3.0 Input value total_attended
4.0 Percentage_attended  (total_attended / no_of_labs ) * 100
5.0 If ( Percentage_attended >= 80)
6.0 Start_If
6.1 Requirement  „Qualified‰
7.0 End_If
8.0 Report Requirement
9.0 End

Copyright © Open University Malaysia (OUM)


20  TOPIC 2 ALGORITHM

Try to consider the algorithm above. Assume total_attended input is 8. Therefore


in step 4.0, percentage_attended will be 80 because of (8/10)*100. Testing step 5.0
is also executed, and the result is true that is percentage_attended >= 80. The
program control will enter the start_if-end_if block. After coming out of the
block, the required value is reported as „Qualified‰. Trace for total_attended at
the value of 7.

ACTIVITY 2.3

Draw a flow chart of the pseudo-code in Example 2.7.

SELF-CHECK 2.3

Re-write similar statements as those in step 4.1 in Example 2.6.

2.3.2 Dual Selection


The dual selection structure involves testing for two conditions. Choices that are
given are the same as single selection, that is, whether the condition is met or not
met. The difference is, if the condition is not met, there are some steps to be
executed. To understand it further, let us look at the general algorithm below:

If <true condition>
Start
step 1
step 2
:
step k
End_If
If_Not
Start
step k+1
step k+2
:
step n
End_If_Not
step n+1

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  21

The If < true condition > steps in, the start_if - end_if block will be executed.
Then, step n+1 will be executed ignoring the steps in the start_if_not - end_if_not
block.

However if the condition is not true or not met, the start_if_not - end_if_not
would be executed without executing the steps in the start_if - end_if. Step n+1
will still be executed whether the condition is met or not. This case is the same as
in the single selection.

A general form of a flow chart for the dual selection is shown in Figure 2.7 below.

Figure 2.7: Dual selection structure flow chart

Let us take a look at the example for a dual selection structure below:

Copyright © Open University Malaysia (OUM)


22  TOPIC 2 ALGORITHM

Example 2.8
Determine the payment that will be charged to a customer for parking their
car in a car park. The payment rate charges are, if total time parked is 2
hours or less, the payment charged is RM2.00; but if the total time parked is
more than 2 hours, then RM6.00 is charged.

The Algorithm is given as:


1.0 Start.
2.0 Input in_time
3.0 Input out_time
4.0 Total_time out_time ă in_time
5.0 If (Total_time< 2)
6.0 Start
6.1 Set total_payment = 2
7.0 End_If
8.0 If_Not
9.0 Start
9.1 Set total_payment = 6
10.0 End_If_Not
11.0 Report results of total_payment
12.0 End

Assume:
in_time = 9.00
out_time = 13.00
total_time = 13.00-9.00 = 4

Testing at step 5.0 will be false because 4 is larger than 2. This will cause the
control of the program to execute the start_if_not - end_if_not block. At the last
step, total_payment will be reported as 6. See Figure 2.8 for the example above.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  23

Figure 2.8: Flow chart for Example 2.8: Dual selection structure

ACTIVITY 2.4

Now, can you try to solve the problem by using in_time 8.00 and out_time
17.00? Use Example 2.8 as a reference.

Copyright © Open University Malaysia (OUM)


24  TOPIC 2 ALGORITHM

Another example of the dual selection instruction is shown here.

Example 2.9
Determine the payment that is charged to the customers who parked their
cars in the parking lot. The payment rates charged are RM2.00 for the first
hour and RM1.00 for each subsequent hour.

The algorithm is given as:


1.0 Start.
2.0 Input in_time
3.0 Input out_time
4.0 Total_time = out_time ă in_time
5.0 If (total_time<= 1)
6.0 Start_If
6.1 Set total_payment = 2
7.0 End_If
8.0 If_Not
9.0 Start
9.1 Set total_time = total_time -1
9.2 Set payment = total_time * 1
9.3 Set total_payment = payment + 2
10.0 End_If_Not
11.0 Report results of total_payment
12.0 End

In the algorithm above, if total_time > 1, and let us say the total_time is 2, then,
the start_if-end_if block (step 6.0 to 7.0) will not be executed. However, the
start_if_not-end_if_not block (step 9.0 to 10.0) will be executed.

In step 9.1, total_time will be 1 because 2 minus 1 is 1. Total_time is reduced by 1


because the payment for the first hour is different from the subsequent hours.

In step 9.2, payment will also be 1 because total_time is multiplied by 1 and is 1,


hence in the second hour and so on, the payment is 1 for every hour.

In step 9.3, total_time now becomes 3; because 1 plus 2 is 3. Here the value 2 is
for the payment rate for the first hour. You need to remember that the payment
for the first hour is different from the subsequent hours. Total payment reported
in step 11.0 is 3.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  25

ACTIVITY 2.5

Now try with the previous data which has the in_time 9:30 and out_time
4.30. Use the algorithm given in Example 2.9 as a reference.

SELF-CHECK 2.4

The pseudo-code in Example 2.9 above can be re-written using the


single-selection structure. Write the new pseudo-code.

2.3.3 Multi-selection
This is the last selection structure. In multi-selection we are allowed to choose
only one statement block from a number of blocks that exist. The number of
statement blocks depends on the number of conditions. If there are n conditions,
then there are n+1 statement blocks, because we have a last statement block that
is not tied to any of the conditions. In the general form below, the statement
blocks are from step q till r.

If <true condition1>
Start
step 1
step 2

step k
End_If1
If_Not
If<true condition2>
Start
step k+1
step k+2

step m
End_If2


If_Not
If<true condition h>

Copyright © Open University Malaysia (OUM)


26  TOPIC 2 ALGORITHM

Start
step n + 1
step n + 2

step p
End_Ifh
If_Not
step q
step q+1

step r
End_If_Not

Figure 2.9 shows the flow chart for the general structure of multi-selection.

Figure 2.9: Multi-selection structure flow chart


Copyright © Open University Malaysia (OUM)
TOPIC 2 ALGORITHM  27

Let us consider the examples given.

Example 2.10
Input an integer number and determine whether that number is negative,
positive or zero. Print the results.

The algorithm for the example given above is:


1.0 Start.
2.0 Read integer N
3.0 If (N < 0)
4.0 Start.
4.1 Print „N is negative‰
5.0 End_If1
6.0 If_Not
7.0 If (N > 0)
8.0 Start.
8.1 Print „N is positive‰
9.0 End_If2
10.0 If_Not
11.0 Start.
11.1 Print „N is zero‰
12.0 End_If_Not
13.0 End

Let us trace the example above. Suppose that the value of N is 7. Testing at step
3.0 will be false because 7 is larger than 0. Step 4.0 till step 5.0 are ignored. When
testing at step 7.0 is executed, the result is true. Therefore, it will print „N is
positive‰.

ACTIVITY 2.6

Trace the value of 10 based on the algorithm above. What is the printed
result?

Copyright © Open University Malaysia (OUM)


28  TOPIC 2 ALGORITHM

Example 2.11
Input bus passengerÊs age to determine the price of the tickets. If the age of
the passenger is 55 and above or between 6 to 12 years, then the ticket price is
50% of the normal ticket price. If the passengerÊs age is between 12 and 18
years, then the ticket price is only 75% of the normal ticket price. It is free for
passengers less than 6 years old.

From the question given, we can conclude that there are five groups of
passengers, as shown in Table 2.1 below:

Table 2.1: Summary of Example 2.11

Passenger Groups Ticket Price


Aged less than 6 (Age < 6) Free
Aged between 6 and 12 50% of the normal ticket price
( 6 <= Age <12 )
Aged between 12 and 18 75% of the normal ticket price
( 12 <= Age <18 )
Aged between 18 and 55 Normal ticket price
( 18 <= Age <55 )
Aged more than 55 50% of normal ticket price
( Age >= 55 )

Figure 2.10 is a flow chart that shows a multi-selection structure. Trace Figure
2.10 and compare it with the conditions stated in Example 2.11. The flow chart is
as follows:

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  29

Figure 2.10: Flow chart Example 2.11, multi-selection structure

2.4 REPETITION STRUCTURE


Repetition Structure is a structure where one block of statements is executed
repeatedly. This repetition concept has already been used in the algorithm
examples earlier by using English words such as until, repeat and others. In a
more formal algorithm, the concept of repetition is stated in a structure called a
loop. There are three main types of loops as shown in Figure 2.11.

Figure 2.11: Types of loops

Copyright © Open University Malaysia (OUM)


30  TOPIC 2 ALGORITHM

2.4.1 Counter Controlled Loop


The counter controlled loop is managed by a loop controller variable or
otherwise known as a counter. The counter holds a value that represents a count.
This counter can be divided into three components:

(a) Initial value for counter;


(b) Condition to repeat the loop; and
(c) Updating the counter value.

For a loop controlling counter, the three components are put in special places,
such as:

for (counter=initial_value; test counter; update counter)


start_for
step 1
step 2
Loop Body

step n
End_for

At the beginning of the execution, the counter will be assigned an initial_value.


Then the condition for repetition is tested. For an incrementing loop, the value of
the counter will always increase until the condition is false. Therefore normally,
the condition for repetition is the counter value which is always lesser than, or
the same as, the last value that wants to be achieved.

If the counter value is still less than the last value, the step in the start_for-
end_for block, which is steps 1 till n will be executed. This block is also known as
the loop body.

After the last step in the loop is executed, the value of the counter is updated
according to the increment that is stated. Notice however that the increment is
not necessarily done by adding 1 to the counter. The increment can be 2 or 3 and
so on. After the counter has been updated, the test is done again and the
execution of the loop body repeats until the condition that is set on the counter is
no longer fulfilled.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  31

The loop ends and the control will get out of the loop. The step after the end_for
will be executed. Figure 2.12 shows the general flow chart for the counter
controlled loop.

Figure 2.12: Flow chart for counter controlled loop

There are two types of counter controlled loops:

(a) Loop with increasing counter; and


(b) Loop with decreasing counter.

Let us look at each of these counters.

(a) Loop with Increasing Counter Control


The loop with increasing counter control is the commonly found loop.
Usually the initial_value is a smaller value than the last value. The update
is made on the value by increasing the value of initial_value until the value
is the same as the end value and the test becomes false. Look at Example
2.12.

Copyright © Open University Malaysia (OUM)


32  TOPIC 2 ALGORITHM

Example 2.12

The algorithm is given as:


1.0 Start.
2.0 Set total = 0.
3.0 for (i = 1; i < 10; increase i by 2)
4.0 start_for
4.1 total  total + i
5.0 end_for
6.0 Report total value.
7.0 End

In Example 2.12, the start_for - end_for block will be executed five times.
Therefore, we need to trace the algorithm above while looking at Table 2.2.

Table 2.2: Tracing Incrementing Loop

i i < 10 Total
0
1 True 1  (0+1)
3  (1+2) True 4  (1+3)
5  (3+2) True 9  (4+5)
7  (5+2) True 16  (9+7)
9  (7+2) True 25  (16+9)
11  (9+2) False 25

The loop will stop when the counter i is more than 10, that is, when the
value i is 11. At this stage, the value of total will be 25.

(b) Loop with Decreasing Counter Control


Loop with decreasing counter control, is generally the same as the loop
with increasing counter control. The differences are:

(i) The counter starts at a larger value and will decrease to a smaller
value according to the decrement rate stated.

(ii) The condition for repetition is > or >= with the last value.

(iii) The initial_value must be a large number.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  33

You need to remember that the initial_value must be a large value. After
the last step is executed, the value of the counter will be decreased
according to the rate specified. Just as in the increasing counter control
loop, the rate is not necessarily 1. Look at Example 2.13:

Example 2.13

The algorithm is:


1.0 Start.
2.0 Set total = 0
3.0 For (i = 9; i >= 1; i decrement 2) start_for
3.1 total total + i
4.0 End_for
5.0 Report total
6.0 End

Notice that in step 3.0, the initial_value is a large number that will be
decreased by 2 to its initial_value. Next, we look at Table 2.3 to trace the
loop:

Table 2.3: Tracing Decreasing

i>=1 Total
0
9 True 9  (0+9)
7  (9-2) True 16  (9+7)
5  (7-2) True 21  (16+5)
3  (5-2) True 24  (21+3)
1  (3-2) True 25  (24+1)
-1  (1-2) False 25

The loop will stop when the condition is not fulfilled, that is when the
value of i is -1. At that instant, the total is 25. The end result of total in the
example with the increasing counter and the total in the example with the
decreasing counter is the same.

Copyright © Open University Malaysia (OUM)


34  TOPIC 2 ALGORITHM

ACTIVITY 2.7

What is the effect if i decrement 2 is replaced by i plus 2 in the Example


2.13 algorithm in step 3.0? Why does that happen?

2.4.2 Condition Controlled Loop


Loops like these are controlled by true conditions. There are two types of general
loops controlled by conditions, which are:

 Loops with conditions tested first; and

 Loops with conditions tested later.

(a) Loop with Condition Tested First


Where the condition is tested first, and if it is true, the step in
start_until_end_until (step 1 until step n) will be executed. After the last
step in the block is executed, usually updates are done and the condition is
tested again.

True  Repetition statements in the loop body


Until condition
False  Out of loop and execute step after end_until

The general form of a condition loop tested first is as follows:

Figure 2.13: General Form and Flow Chart of Loop Structure with condition tested first

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  35

Let us now look at Example 2.14.

Example 2.14

Consider the example:


1.0 Start.
2.0 Set total and counter to 0
3.0 Until counter < 5
4.0 Start.
4.1 counter  counter + 1
4.2 total  total + counter
5.0 End
6.0 Report total value
7.0 End

In Example 2.14, the block start_until-end_until will be executed five times


until the condition counter < 5 is false and the value of counter is 5. The last
value of total is 15. Consider the tracing of the loop below:

Table 2.4: Tracing of Loop with Condition Control

Counter < 5 Loop Counter Total


0 0
True (0<5) 1 1  (0+1) 1  (0+1)
True (1<5) 2 2  (1+1) 3  (1+2)
True (2<5) 3 3  (2+1) 6  (3+3)
True (3<5) 4 4  (3+1) 10  (6+4)
True (4<5) 5 5  (4+1) 15  (10+5)
False (5<5) 5 15

(b) Condition Tested Later


For this loop, the steps in the loop will be executed first and the condition
will be tested later, that is when the statement until is reached. This means
the steps in start ă end loop will be executed at least once. The following
Figure 2.14 shows the flow chart for the condition controlled loop with the
condition tested later.

Copyright © Open University Malaysia (OUM)


36  TOPIC 2 ALGORITHM

Figure 2.14: General form and flow chart of loop structure with condition tested later

Example 2.15

Consider the example for loops of this type:


1.0 Start.
2.0 Set total and counter to 0.
3.0 Start.
3.1 counter  counter + 1.
3.2 total  total + i.
4.0 End.
5.0 Until (counter less than 5).
6.0 Report total value
7.0 End.

In Example 2.15, the end result of total is the same as the loop before this,
which is 15. Notice in the tracing below, the number of tests for the
condition in the condition controlled loop for this form is one less than the
condition in the condition controlled loop in the form before this.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  37

Table 2.5: Tracing of Loop with Condition Control Tested Later

Counter < 5 Loop Counter Total


0 0
1 1  (0+1) 1  (0+1)
True (1<5) 2 2  (1+1) 3  (1+2)
True (2<5) 3 3  (2+1) 6  (3+3)
True (3<5) 4 4  (3+1) 10  (6+4)
True (4<5) 5 5  (4+1) 15  (10+5)
False (5<5) 5 15

2.4.3 Sentry Controlled Loop


Loops of this type are actually subset loops controlled by condition. Sentry value
is a signal to stop the loop. Loops like these are also called uncertain loops
because the number of loop executions are not known before the execution starts.
The sentry value chosen must not be an input data that is valid. Consider the
sentry controlled loop in Example 2.16.

Example 2.16
Read one set of studentsÊ marks where if the marks are negative then the
input ends. Calculate the average marks.

Algorithm 2.16 (A):


1.0 Start
2.0 Set i to 1 and Total to 0
3.0 Read first mark, mi
4.0 Until mi > = 0
5.0 Start
5.1 Total  total + mi
5.2 i  i +1
5.3 Read i-th mark, mi
6.0 End
7.0 Average  Total/(i - 1)
8.0 Print Average
9.0 End

Copyright © Open University Malaysia (OUM)


38  TOPIC 2 ALGORITHM

In example 2.16, a negative mark input will end the loop because the test
condition (step 4.0) becomes false. In the example above, the number 999 can be a
sentry value because the maximum mark is 100. To make the number 999 as a
sentry value, step 4.0 in the algorithm has to be changed to Until mi = 999, that is,
when the mark mi is 999, then the statement becomes false and automatically
exits the loop.

ACTIVITY 2.8

For the algorithm in Example 2.16, what if the negative value is a valid
data?

Sentry value can also be of a type character. We can change the example above
and use the character „t‰ as a sentry value. Consider the changes made in
algorithm 2.16(B) below.

Algorithm 2.16 (B):


1.0 Start
2.0 Set i to 1 and Total to 0
3.0 Set continue as ÂyÊ
4.0 Until continue == ÂyÊ
5.0 Start
5.1 Read i-th mark, mi
5.2 Total  Total + mi
5.3 i  i + 1
5.4 input ÂyÊ to continue the operation or ÂnÊ to stop the operation
6.0 End
7.0 Average  Total/(i - 1)
8.0 Print Average
9.0 End

You have now learnt three types of control structures. Take a short break before
moving on to the next section.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  39

2.4.4 Structuring
This method is used to solve problems by designing structure charts. The
benefits of using the structure chart are as follows:

(a) Able to identify the number of modules or sub-problems that are created
by breaking up the problem;

(b) Able to give input that is needed by a module or sub-problem that can be
shown in the chart; and

(c) Able to determine the output that is obtained from one module that can be
used in other modules.

As an example, consider the problem statement given below:

(a) Problem
Solve the problem of calculating the gross pay and net pay for workers that
is made up of basic pay and overtime pay. The normal working hours are
40 hours. The rate for working overtime is twice the normal rate. If the
workerÊs pay exceeds RM500 per week, a tax of RM50 is deducted.

(b) Analysis
To calculate the pay, the information needed are the hours worked and the
hourly rate. The net pay of a worker can be obtained by deducting tax from
the pay if the pay exceeds RM500.

(c) Data Requirements


Permanent Information (Constant):

Taxable_Pay = 500.00
Tax = 50.00
Maximum_Hours = 40.0
Overtime_Rate = 2.0

Input:
Hours_Worked (float type)
Hourly_Rate (float type)

Output:
Gross_Pay (float type)
Net_Pay (float type)

Copyright © Open University Malaysia (OUM)


40  TOPIC 2 ALGORITHM

Relevant Formula:
Normal_Pay = Work_Hours x Hourly_Rate
Overtime_Pay = Overtime_Hours x Overtime_Rate x Hourly_Rate
Gross_Pay = Normal_Pay + Overtime_Pay
Net_Pay = Gross_Pay - Tax

(d) Design
Initial Algorithm:

1.0 Start
2.0 Read Hours_Worked and Hourly_Rate.
3.0 Calculate Gross_Pay.
4.0 Calculate Net_Pay.
5.0 Print Gross_Pay and Net_Pay.
6.0 End

The following Figure 2.15 shows a structure chart of the problem.

Figure 2.15: Structure Chart to find net pay problem

Step 3.0 and step 4.0 can be refined. Normally, our operation uses
refinement to get the calculated gross pay and net pay.

(e) Step 3 Refinement:

3.1 IF (Hours_Worked <= Maximum_Hours)


3.1.1 Gross_Pay = Hours_Worked x Hourly_Rate
3.2 End_IF
3.3 IF_Not
3.3.1 Gross_Pay = (Maximum_Hours x Hourly_Rate) +
3.3.2 (Hours_Worked ă Maximum_Hours) x Overtime_Rate x
Hourly_Rate)
3.4 End_IF_Not

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  41

(f) Step 4 Refinement:

4.1 IF (Gross_Pay > Taxable_Pay)


4.1.1 Net_Pay = Gross_Pay - Tax
4.2 IF_Not
4.2.1 Net_Pay = Gross_Pay
4.3 End_IF_Not

2.5 CASE STUDY 1


PROBLEM
You are required to do surveying jobs and deal with maps that give distances in
either km or miles. However, you prefer to use metric measurements. When you
have to deal with values in miles, you will need to convert them. So, it will be
great if you can have a conversion program to convert the measurement from
miles to km. Let us first analyse this problem.

ANALYSIS
The first step in solving a problem is to determine what you are asked to do. Are
you supposed to convert measurement from km to miles, or vice versa? The
problem states clearly that you need to convert miles to km. Therefore, the
problem input is distance in miles and the problem output is distance in km.
Then, you will need to know the relationship between miles and km. Based on
the metric table, one mile is equal to 1.609km.

Write down on a piece of paper, the following data requirements:

(a) Problem Input:


miles /* the distance in miles */

(b) Problem Output:


kms /* the distance in km */

(c) Relevant Formula:


1 mile = 1.609km

Copyright © Open University Malaysia (OUM)


42  TOPIC 2 ALGORITHM

DESIGN
Next step, formulate an algorithm to represent this problem. Think logically of
the three major steps in a proper sequence.

Algorithm

1. Get the distance in miles.

2. Convert the distance to km.

3. Display the distance in km.

Now you will need to decide if this algorithm can be refined further. Step 1
(getting data) and step 3 (displaying value) are basic steps and cannot be refined
anymore. Step 2 however, can be refined with additional detail. You can add the
information as step 2.1, indented under step 2.

Algorithm with Refinements


1. Get the distance in miles.
2. Convert the distance to km.
2.1. The distance in km is 1.609 times the distance in miles.
3. Display the distance in km.

The above steps are known as pseudo-code. You might be interested in drawing
a flowchart to represent the same algorithm. Take a look at the following
flowchart to get an idea of designing algorithms for programming tasks.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  43

Figure 2.16: Flow chart of the conversion program

After finishing with this algorithm, you may want to do a desk checking before
proceeding with its implementation. How is that done? Let us say, step 1 gets a
distance of 10.0 miles and step 2.1 should convert the measurement to 1.609 X
10.0. You should then get 16.09 km as the result to be displayed in step 3.
Remember these values as you are going to use them in the implementation
phase later on.

2.6 CASE STUDY 2


PROBLEM
Many programs require input from users. Based on this input, the program will
then display an appropriate message. This message will give the users an
indication about the type or choice of input needed by the program.

Copyright © Open University Malaysia (OUM)


44  TOPIC 2 ALGORITHM

One technique of interaction between a program and its user is, using the menu.
The menu is a list of items that can be selected by the user. Once the menu is
displayed, the program will wait for the user to input his or her choice. After the
user has chosen the item, the program will continue processing based on that
item.

In this section, we will develop a program that is able to perform these


conversions:

(a) Convert time from minutes to hours;


(b) Convert distance from feet to metres; and
(c) Convert temperature from Fahrenheit to Celsius.

The program will display a menu to get the type of conversion required. Once
that is done, it will ask the user for the input to be converted, do the calculation
and then display the result. After that, the program will display the menu again
and the process will continue until the user decides to stop the program.

ANALYSIS
The following formula is used to do the conversions:

1 hour = 60 minutes
1 feet = 0.3048 metres
1 Celsius = (5/9) * (Fahrenheit ă 32)

DESIGN
The menu to be displayed by the program is based on the selection listed in Table
2.6:
Table 2.6: Menu

Choice Code Conversion Type


1 Minutes to hours
2 Feet to metres
3 Fahrenheit to Celsius
0 Program ends

Users choose the type of conversion by entering the corresponding code. If the
user enters a 0, the program ends. If the user enters any value other than the
above, it will be ignored. This means, the program will re-display the menu and
the user has to choose again.

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  45

Table 2.7. shows all the variables to be used in the pseudo-code.

Table 2.7: Variables

Variable Explanation
choice Users choice from the menu
minutes Value of minutes input by the user
hours Keeps the converted value from minutes to hours
feet Value of feet input by the user
metres Keeps the converted value from feet to metres
fahrenheit Value of Fahrenheit input by the user
celsius Keeps converted value from Fahrenheit to Celsius

The following is the initial pseudo-code for our problem:

1.0 Start
2.0 Do
2.1 Display the menu
2.2 Input the choice from the user
2.2.1 IF (1 <= choice and choice <= 3)
Start_IF
Do the conversion and display the result
End_IF
3.0 Until (choice NOT 0)
4.0 End

Step 2.2.1 involves calculation that will perform the conversion and then display
the results. The calculation that is carried out depends on the type of choice
specified by the user in Step 2.2. Thus, Step 2.2.1 needs to be refined further, to
reflect the userÊs choice. The following is the refined and complete pseudo-code
after refining Step 2.2.1 above:

Copyright © Open University Malaysia (OUM)


46  TOPIC 2 ALGORITHM

1.0 Start
2.0 Do
2.1 Display the menu
2.2 Input the choice from the user
2.2.1a IF (choice==1)
Start_IF
Input minutes from the user
Calculate hours
Display hours and minutes
End_IF
2.2.1b IF (choice==2)
Start_IF
Refined
Input feet from the user
steps
Calculate metres
Display feet and metres
End_IF
2.2.1c IF (choice==3)
Start_IF
Input fahrenheit from the user
Calculate celsius
Display fahrenheit and celsius
End_IF
3.0 Until (choice NOT 0)
4.0 End

The flow chart for the above pseudo-code is given below in Figure 2.17:

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  47

Figure 2.17: Flow chart for the pseudo-code

Copyright © Open University Malaysia (OUM)


48  TOPIC 2 ALGORITHM

SELF-CHECK 2.5

1. Based on the problem given below, construct a flow chart:

(a) By inputting an integer number, generate a multiplication-


table (1 to 12) for that number. As an example, if the number
input is 4, then display the 4 times table; and

(b) Input the values of length and width for a residential area in
feet measurement. Also enter the values of length and width
for the building of a house in feet measurement. Assume the
difference of a grassy area between them. Calculate the time
needed to cut grass at the rate of 2 square feet per second.

2. Based on the problem given below, construct a pseudo-code.

(a) Given the radius, determine the area and circumference of a


circle.

(b) You have been asked to input your name and then print it
five times.

(c) Construct a flow chart to determine your weight category.


The category determination is based on Body Mass Index
(BMI). BMI is the ratio of height in metres to body weight
in kilos. The formula is given as:

Weight category is as follows:

CATEGORY BMI
Underweight less than 18.5
Normal 18.5 ă 24.9
Overweight class 1 25.0 ă 29.9
Obesity class 2a 30.0 ă 34.9
Obesity class 2b 35.0 ă 39.9
Obesity class 3 40.0 and above

Copyright © Open University Malaysia (OUM)


TOPIC 2 ALGORITHM  49

(d) Create a pseudo-code for this problem. Accept two integer values as
input, for example, 3 and 7. Print all the integer numbers between
them, including those two numbers. If the first number is smaller
than the second number, then print the numbers in ascending order.
If otherwise, print the numbers in descending order.

For example:
Input: 3 7
Output: 3 4 5 6 7

Input: 7 3
Output: 7 6 5 4 3

 Algorithm is a step-by-step problem-solving method in a limited time.

 Activities in the algorithm representation are represented by geometry


nodes. Each node represents different activities. These nodes will be joined
using arrows that show the flow or a sequential activity.

 Pseudo-code or false codes are instructions that mimic the program code
(actual program instructions).

 Input is all the information that is relevant and needed to execute a process.

 Output is the result that is needed.

 Selection structure is a structure design that gives a few choices during


execution.

 Single selection involves testing one condition only. The choice given
depends on whether the condition is met or not.

 The dual selection structure involves testing for two conditions. Choices that
are given are the same as single-selection, that is, whether the condition is
met or not.

Copyright © Open University Malaysia (OUM)


50  TOPIC 2 ALGORITHM

 In multi-selection we are allowed to choose only one statement block from a


number of blocks that exist. The number of statement blocks depends on the
number of conditions.

 Repetition Structure is a structure where one block of statements is executed


repeatedly.

Algorithm Semantic
Flow chart Syntax
Pseudo-code

Copyright © Open University Malaysia (OUM)

You might also like