Problem Solving & Algorithm Notes
Problem Solving & Algorithm Notes
Problem
A problem is a discrepancy between what is required and what exists.
Solution
A procedure consisting of a set of instructions that, if followed in order, achieve the
required results.
Problem solving
The thought process that requires a critical analysis of the situation (the problem) and
careful consideration of possible ways of overcoming the problem.
NB: it is not always easy to understand a complex problem. One way to help us
understand a problem is to break it down into its component parts using a process
known as the top-down stepwise refinement.
Computer-based problem-solving
Breaking down the problem into its significant parts When computers are used for
solving problems, the stages or steps used for general problem-solving have to be
modified as we have to give the instructions to the computer to make it solve the problem
for you. So the revised steps for computer-based problem solving will be:
Now let's look a simple problem that needs to be solved using a computer:
Example: Get two numbers, add them together and display their sum.
First of all, you might wonder if this is a problem statement, as you can solve it easily
once you have a calculator to add the numbers or if you can get a piece of paper to add
them manually. But it is not easy for the computer to solve this problem as it can't work
on its own. You need to give all the instructions for it to perform. This is the reason why
it is good to break down the problem into its parts to make the computer easily solve it
for you.
1
An IPO (Input-Processing-Output) diagram can be used to breakdown the problem. An
IPO diagram is a table with three columns showing the input, output and processing parts
of the problem. Storage is a form of processing because the computer stores data by using
its processing capabilities.
Table 2.1 is an IPO diagram showing the breakdown of problem into its parts.
As you can see, input will be two numbers, processing involves accepting these two
numbers, adding them and storing the results, and output is the sum, the result of adding
these two numbers together.
2
In this stage, run your program using a programming language to see if the program is
producing the correct results.
This involves preparing documentation that will help the user to operate the program and
maintain the program by making changes to the program from time to time, if needed.
Num1 Num2
10 15
Fig. 2.1: Storing values in a memory location
In Fig 2.1 above, Num1 and Num2 are identifiers for two memory locations and they
store the values 10 and 15. Num1 and Num2 are variables as they are identifiers of
storage locations that can store any values.
Please note that when a new value is placed in a variable, the old value is overwritten by
the new value because, as you can see, only one place is there to store the value for each
variable The value stored in a constant cannot be changed.
Literals are constants that are written literally as itself rather than as a value. Examples of
literals include ‘The sum is’ ‘The largest =’ and ‘Enter number’.
NB: They are normally used with the input output instructions that appear as a message
for the user.
Data types
The problem statements that we looked at earlier required data or inputs to be given to the
computer to solve the problem. To do this, data must be given to the computer in a way it
recognises. Data type determines the type of data that a variable can store. A data type
that treats a variable as a single unit is called an elementary data type.
3
DOES IT MEAN?
Data types indicate the type of data that is stored in a variable, e.g. numbers or
characters.
Observe
representative of the program data being stored
are all of a reasonable length
do not contain spaces or begin with a digit
4
When we want instructions to be very clear, we often break them down into smaller parts,
or steps. For example, if your mom wanted you to bake a chicken, she would give you the
instructions in several steps that you could easily follow, like
We do the same when writing instructions for computers. These steps or instructions that
can be used to complete a task are called an algorithm. The word algorithm comes from
the word 'algorism', meaning the process of doing calculations with Arabic numerals.
Later, 'algorism' combined with the word arithmetic to form 'algorithm'.
Bear in mind that these sets of steps or instructions will help us to create instructions that
are understandable to computers. When algorithms are converted into a language that is
understandable to a computer, it becomes a program. Also remember that, you should
create an algorithm before writing a program, not the reverse.
Algorithm Phase
1. Clearly define the problem that you want to solve.
2. Design an algorithm that is precise and well thought out to solve the problem.
3. Test your Algorithm on paper. You must be sure your algorithm works correctly
before u can write a program for it
Implementation Phase
1. Translate your algorithm into a programming language such as Basic, Pascal, C or
C++.
2. Test the program to make sure it produces the correct results.
3. Document the program. (Use comments).
Characteristics of algorithms
A good algorithm should have the following characteristics:
1. The number of steps must be finite
This means that the computer has a definite number of instructions to follow, and when it
comes to the end of those steps, it has completed the task. For example, when telling you
how to bake the chicken, your mom wouldn't leave out any steps, or forget to tell you to
5
take it out of the oven once it was baked. Some algorithms might have steps or
instructions that need to repeated, but there should still be a clear end to the process.
4. The steps must have flow of control from one process to another.
There may be many processes involved in a problem, but each process must be related
and should have a clear flow from one to the other. For example, you mom would tell
you to get the ingredients together for seasoning, then to mix the seasoning, and then
apply it to the chicken.
6
3. The output step -This step is used to display the results.
Let's look at the three steps for the following problem statement:
Example: Get the length and width of a rectangle and calculate and display its area.
In this problem statement, you would notice that inputs are the length and width of the
rectangle, and output is its area. Processing involves accepting the length and width,
calculating the area and storing it. This problem requires you to use the formula for
calculating the area (multiply length by width).
So when a statement of a problem is given, you need to identify these three main steps, as
we did in the previous problem statement. Look at the statement carefully and identify
the input, output and processing that are required. Normally, the input and output will be
expressed in the form of nouns and adjectives. The processing required will be in the
form of verbs or adverbs.
Top-down refinement:
INPUT PROCESSING OUTPUT
7
CONTROL STRUCTURES / FLOW OF CONTROL
The steps that are identified for preparing algorithms can be written using three basic or
program constructs to indicate how instructions will be carried out or how the flow of
control from one statement would take place. They are:
1. Sequence
2. Selection
3. Iteration [Repetition]
Control structures are instructions or statements that determine the flow of control of
steps in an algorithm
Sequence is a control structure where instructions are written in the order they should
take place.
Selection is a control structure where a choice has to be made between two or more
options.
Sequence
The sequence control structure is used when you have instructions to be carried out in a
particular order. In an algorithm these instructions can be written in the order you want it
to happen, as follows:
Instruction l or step 1
Instruction 2 or step 2
Instruction 3 or step 3
Instruction 4 or step 4
Here, the instructions will be completed in the order given. This control structure can be
used for problems algorithm involving accepting inputs, performing calculations and
storing them, and displaying the outputs. The following is a typical example of an
algorithm that uses the sequence control structure where Steps 1 to 5 will be completed in
the order given.
Step 1: Start
Step 2: Get two numbers
Step 3: Add the numbers and store it in Answer
Step 4: Display Answer
Step 5: Stop
Selection
The selection control structure is used in problems with instructions to be carried out if a
certain condition is met. The choice of options will be dependent on whether the
condition is true or false. Selection control structure statements commonly used in
algorithms are normally written as:
8
The following is an example of an algorithm with a selection control structure.
Step 1: Start
Step 2: Accept score
Step 3: If score more than 59 then display 'the student has passed' else display 'student
has failed'
Step 4: Stop
In the above example, if the score of a student is more than 59 it will display 'the student
has passed' and if it is less than 60 it will display 'the student has failed', which means
only one of the two messages can be displayed. If the condition is true [the score is more
than 59), the part after 'then' will be carried out, otherwise the part after 'else' will be
carried out.
Iteration forms the repetitive stage of the processing step. There are times where we have
to repeat a process. Suppose you want to accept 100 numbers from the user and find their
sum, it would be wise to repeat the process of getting the numbers 100 times rather than
writing instructions 100 times to accept the numbers. Repetition of a set of instructions a
fixed number of times is called bounded iteration. Commonly used iteration statements
in algorithms include for-endfor.
There are also situations where the process has to be repeated until a specific condition
becomes false. For example, find the sum of a set of numbers terminated by 0. Here,
getting numbers and finding their sum will be repeated until the user supplies 0 as the
value for the number. Repeating a set of steps a number of times until a particular
condition becomes false is called unbounded iteration. Common unbounded iteration
statements are while-endwhile, and repeat-until.
Problem statement 1
9
Write an algorithm that will accept three numbers, add them together and print their sum.
1. First we gather the user values. In the problem statement, 'three numbers' is the input
and 'sum' is the output required. 'Accept', 'add' and 'print' represent the processing that
needs to be done. Storage will take place when the calculated values of the three numbers
are assigned to sum.
You should also check the problem statement to see if any control structures are needed.
Since there is no need for decision making, the selection control structure is not required.
Also there is no need for repeating processes, so the repetition stage is not required.
2. Now let's break down the problem into steps and write it in the form of single specific
tasks to form the algorithm:
Step 1: Start.
Step 2: Accept three numbers.
Step 3: Add the numbers entered.
Step 4: Display the sum.
Step 5: Stop.
Problem statement 2
In the above problem statement, the processing step only required you to carry out
assignment of the values, so now let's look at one that involves decision.
Prepare an algorithm that will read the price of an item and display its new price after a
discount of 10% if the price is more than $100.
1. In this problem statement, the input is 'price' and output is 'new price'. The processing
involves checking the price, and finding the discount, if required. As the potential
discount depends on what the price is, the decision step will be required. However,
this statement does not involve repeating a process, so there is no need for the
repetition step.
Problem statement 3
10
Create an algorithm that will read three numbers and find the largest among them.
1. For this problem statement you need to understand that the processing involves
checking and comparing three numbers to find the largest. You could approach this
problem in many ways, but let's concentrate on two popular methods. The two versions
of the algorithm are as follows:
2. Method 1
In the first method you could compare the first number with the other two numbers to see
which is larger, and then compare the second and third numbers the same way.
Step 1: Start.
Step 2: Get three numbers.
Step 3: Check if the first number is bigger than the second and third number, if it is
bigger then display first number as the largest.
Step 4: Check if the second number is bigger than the first and third number, if it is
bigger then display second number as the largest.
Step 5: Check if the third number is bigger than the first and second number, if it is
bigger then display third number as the largest.
Step 6: Stop.
3. Method 2
In the second method, comparison is made of the first and second numbers to find the
largest and then the largest of the two is compared with the third number.
Step 1: Start.
Step 2: Get three numbers.
Step 3: Check if the first number is bigger than the second number, then store the value of
first number as the largest. Otherwise store the value of second number as the largest.
Step 4: Check if the largest of the first two numbers is bigger than the third number. If it
is, then store the value of third number as the largest.
Step 5: Display the largest number.
Step 6: Stop.
From this process, you can see that you can have several solutions for a problem solving
statement based on the approach of the programmer.
11
Narrative
Narrative, also called general algorithm, is where each step in the algorithm is written in
clear, simple language. It does not use any computer language or coding. This is similar
to how you have been writing algorithms so far.
For example, if you wanted to write an algorithm to read in three numbers then find and
display their sum, the narrative could be:
Step 1: Start.
Step 2: Get the three numbers.
Step 3: Add the numbers.
Step 4: Store the results in Sum.
Step 5: Display Sum.
Step 6: Stop.
As you can see, each instruction would be clearly understood by any person who speaks
English.
Narrative algorithm 1
Write an algorithm in narrative form to read in three numbers from the keyboard and
calculate and display their product.
Remember that, when given a problem statement, you first need to identify the words that
describe input, output and processing. So, in the above problem statement, the inputs are
the three numbers and their product is the output. The processing involves accepting three
numbers and calculating the product, which is multiplying the numbers.
So the narrative would be:
Step 1: Start.
Step 2: Get the three numbers.
Step 3: Calculate the product by multiplying the numbers.
Step 4: Store the results in Product.
Step 5: Display Product.
Step 6: Stop.
Narrative algorithm 2
Prepare an algorithm in narrative that will accept the length and width of a rectangle and
calculate and display its area.
In the problem statement above, the inputs are the length and the width of the rectangle
and output needed is its area. The processing involves accepting the values for length and
12
width and calculating the area by multiplying the length and width. So the narrative can
be:
Step 1: Start.
Step 2: Get the length and the width.
Step 3: Calculate the area by multiplying the length and width.
Step 4: Store the results Area.
Step 5: Display the area.
Step 6: Stop.
Narrative algorithm 3
Create an algorithm in narrative that will prompt the user to enter the salary of an
employee and calculate the income tax at 15% if the salary is more than $5000. Display
the salary and tax.
Now, in this algorithm, the input is the salary and the processing involves prompting the
user to enter the salary, checking to see if the salary is more than 5000 and calculating the
income tax. The output is displaying the salary and the income tax. So the narrative can
be written as:
Step 1: Start.
Step 2: Prompt the user to enter the salary.
Step 3: Get the salary.
Step 4: Check if the salary is more than 5000, if it is calculate the tax by multiplying the
salary by 15%.
Step 5: Display the salary and tax.
Step 6: Stop.
Pseudocode
As you know, we create algorithms in preparation for giving instructions to the computer.
The instructions have to be in a form that is understandable to computers, so are written
using a programming language.
Narrative steps are very simple and useful for when you start learning about
programming, but when you are comfortable with programming you can create
algorithms using instructions with words and symbols that closely resemble computer
programming language instructions. This form of representation is called pseudocode.
The name 'pseudocode' comes from 'pseudo', meaning 'fake' and 'code' meaning program.
In pseudocode even though the terms used closely resemble programming language
terms, they are used without following the rigid rules of the language.
13
What you want to do Verb to use How to use it
INPUT INPUT INPUT name
In General GET INPUT itemNumber, Price
From the Keyboard READ READ datafile
From a file
OUTPUT PRINT PRINT “End of processing”
In General DISPLAY DISPLAY final Answer
To Screen WRITE WRITE nextRecord
To a file
PROCESSING SET SET age to 0
Initializing variable LET LET age = age + 1
Changing values in
variables
PROGRAM FLOW IF…THEN IF X > 5 THEN PRINT x
CONTROL WHILE..DO WHILE X > 5 DO
Decision REPEAT…UNTIL REPEAT…UNTIL x > 5
Repetition FOR…DO FOR x = 1 to 5 DO
Pseudocode language
The pseudocode can contain variables, constants, operators, and terminology used in
programming languages.
Variables
As you know, variables are used to store values that can change. These values can be a
user input or result of a calculation and are stored in a location in the memory with a
name chosen by the programmer called a variable name. Examples of variable names that
can be used in pseudocode are num1, num2, sum, average, etc.
Constants
Constants are fixed values used when you need to keep a value fixed. For example, when
you have to calculate the area of a triangle using the formula 1/2* base* height, the value
1/2 will be a constant.
Operators
Operators are symbols used for performing calculations or making comparisons.
Commonly used operators in pseudocode are:
14
2. Relational operators -operators used to check for comparisons. The table below
shows commonly used relational operators and their operations.
Relational operator Operation
> greater than or equal
< less than
>= greater than or equal to
<= less than or equal to
<> not equal or equal to
= equal to
Table 2.3
Just as in mathematics, in computing all the operations are carried out in a hierarchical
order. The computer follows the BODMAS rule. So anything in Brackets will be done
first, followed by Orders [such as powers and square roots), then Division and
Multiplication.
Addition and Subtraction will be done last. So when you are writing instructions you
must ensure that you write them in the order in which you want the computer to carry
them out.
Pseudocode terminology
The general programming language terms used in pseudocode are:
• Terms used for the input step: input, read
• Terms used for the output step: output, write, display
• Terms used for the assignment step: set, store
• Terms used for selection: if-else-endif
• Terms used for iteration [bounded): for-endfor
• terms used for iteration (unbounded): while-endwhile. repeat-until
Some programmers use terms in their pseudocode from other programming languages
that they are comfortable with. However, this can create problems for somebody who is
not familiar with that particular programming language. Generally it is wise to use terms
like the ones given above so that any person can follow the logic of the program.
Pseudocode algorithm 1
Write a pseudocode algorithm to find the average of three numbers.
For this example, let's look at the narrative first and then write the corresponding
pseudocode for it.
1. Narrative
15
Step 1: Start.
Step2: Add the
Step 3: Add the three numbers, divide by 3 and store the results.
Step 4: Display the results.
Step 5:Stop.Get
2. Pseudocode
Step 1: start
Step 2: read a [Accept the value for the first number and store it in a.)
Step 3: read b [Accept the value for the second number and store it in b.)
Step 4: read c [Accept the values for the third number and store it in c.)
Step 5: set average (a+b+c)/3 [Add the three numbers and divide it by 3 and store the
results in average. The left arrow represents the assignment and it takes place
from right to left meaning after the calculations the results will be stored in
variable average. Also note that the brackets allow the addition of three numbers
to take place before the division.)
Step 6: write average [Display the results stored in the variable average.)
Step 7: stop
Notice that in pseudocode, instructions are transformed into general programming
language terms with variables, constants and statements.
Pseudocode algorithm 2
Prepare a pseudocode algorithm that will accept the length and width of a rectangle and
calculate and display its area.
Step 1: start
Step 2: input length (Accept length and store it in variable length.)
Step 3: input width (Accept width and store it in variable width.)
Step 4: set area = length * width (Calculate the area by multiplying the values of length
and width and store the results in area.)
Step 5: output area (display the results stored in variable area.)
Step 6: stop
As you can see, the two examples above used the control structure sequence, so each
instruction will be carried out in the order it has been written. Now let's look at examples
of pseudocode where the control structure selection is used.
16
In the example below, the selection construct if-then-else is used. When writing
instructions over several lines, it is a good practise to write them in an indented format as
in Step 6, because it increases the readability of the program and also helps to easily
identify any errors.
Problem: Create a pseudocode algorithm that will prompt the user to input two unequal
numbers and find which is the larger.
Step 1: start
Step 2: write "Enter first number." (Prompt the user to input the value for the first
number.)
Step 3: read a (Accept the value for the first number and store it in variable a.)
Step 4: write "Enter second number." (Prompt the user to input the value for the second
number.)
Step 5: read b (Accept the value for the first number and store it in variable b.)
Step 6: if a>b then
set large a
else
set large b
endif (Check to see if a is bigger than b. If it is, then store the value of a in
variable large otherwise store the value of b in variable large.)
Step 7: write large (Display the value of the variable large.)
Now, let's look at another example that involves multiple selection statements.
Pseudocode algorithm 4
Write a pseudocode that will accept three unequal numbers and find the smallest among
them.
Step 1: start
Step 2: read num1, num2, num3 [Accept three numbers and store them in variables
numl, num2 and num3.)
Step 3: if num1 <num2 then
set sml num1
else
set sml num2
endif [Find the smaller of the first two numbers and store it in the variable sml.)
Step 4: if num3<sml then
sml = num3 [Check if the third number is smaller than the smaller value of the
first two numbers, stored in variable sml. lf it is, store the value of the third
number in variable sml.)
endif
Step 5: write sml [Display the value stored in sml.)
Step 6: stop
17
You will probably have noticed that in Step 2, the three variables are used in the same
line instead of breaking them into three separate steps.
Now let's look at examples where iteration constructs are used. First, we will write some
pseudocode that involves bounded iteration.
Pseudocode algorithm 5
Write a pseudocode algorithm that will accept 20 numbers and find their product.
Step 1: start
Step 2: set product 1 (Start product off with a value of 1.)
Step 3: for i 1 to 20 (This step repeats as the counter counts from 1 to 20.)
write "Enter next number"
read num
set product product * num (Multiply the current value of
product by the latest number entered.)
endfor
Step 4: write" The product is" product
Step 5: stop
The variable i acts as a counter for the iteration that begins at Step 3. A counter must be
an integer. When the algorithm reaches endfor it loops back to the 'for' line and adds 1 to
the value of i. This continues until the last time, in this case, when i has a value of 20.
Now let's look another example with the unbounded iteration construct, using a while-
endwhile loop.
Pseudocode algorithm 6
Write a pseudocode algorithm that will accept a group of numbers and calculate its sum.
The program stops when the user enters 0 as the number.
Step 1: start
Step 2: set sum = 0 (Start sum off with a value of 0.)
Step 3: write Enter first number."
Step 4: read num
Step 5: while num < > 0 do
set sum sum + num (Add the current value of sum to the
latest number entered.)
write "Enter next number. Enter 0 to finish"
read num
endwhile
Step 6: write "The sum is" sum
Step 7: stop
18
Representing an algorithm using a Flowchart
Many of us find it easier to follow steps when they are represented diagrammatically or
graphically. You may have come across in your maths or design classes. They give a
graphical representation of a process. Flowcharts for algorithms use the variables,
constants and operators that are used in pseudocode language, but linked together by
different shapes that represent each type of step. They are shown in Fig 2.2.
Input/output symbol (parallelogram) - used to indicate the input and output of the
problem.
Fig 2.2
Drawing flowcharts
The following steps will guide you in drawing a flowchart.
1. Go through the problem carefully and ensure that all the information needed to solve
the problem is available, such as the inputs, processing that needs to be done and the
outputs required.
19
3. Arrange the steps in a logical order - the order in which the instructions should take
place.
4. Draw the flowchart for each step using the correct symbols or shapes and arrows to
indicate the direction of flow.
Now let's draw some flowchart for examples of algorithms which were done earlier.
Flowchart algorithm 1
Write a pseudocode algorithm and draw a flowchart to find and display the sum of 10 and
20.
PSEUDOCODE FLOWCHART
Write sum
Stop
Fig 2.3
Flowchart algorithm 2
Draw a flowchart that will read three numbers and find the product of three numbers.
Pseudocode Flowchart
Step 1: start
Step 2: read nl, n2, n3 Start
Step 3: set product nl *n2*n3
Step 4: write product Read n1, n2, n3
Step 5: stop
Product nl *n2*n3
Write product
Stop
Fig 2.4
20
Flowchart algorithm 3
Draw a flowchart that will accept three numbers from the user and find and display their
average.
Pseudocode
Step 1: start
Step 2: read nl, n2, n3
Step 3: set average (nl +n2+n3)/3
Step 4: write average
Step 5: stop
Flowchart algorithm 4
Draw a flowchart that will prompt the user to enter two unequal numbers and find the
largest between them.
Pseudocode
Step 1: start
Step 2: write "Enter two unequal
numbers."
Step 3: read nl,n2
Step 4: if nl>n2 then
set large nl
else
set large n2
Step 5: Write large
Step: Stop
21
Flowchart algorithm 5
Draw a flowchart that will prompt the user to enter three unequal numbers and find the
smallest among them.
Pseudocode
Step 1: start
Step 2: write “Enter three unequal
numbers."
Step 3: read nl,n2,n3
Step 4: if nl <n2 then
set sml nl
else
set sml n2
endif
Step 5: if n3<sml then
set sml n3
endif
Step 6: write sml
Step 7: stop
22
Flowcharts with unbounded iteration
The flowcharts that we have looked at so far were based on sequencing and selection.
The following are flowcharts with repetition or iteration construct.
Flowchart algorithm 6
Draw a flowchart for a program that will accept a group of numbers and find their sum.
The program stops when the user enters a 0 for number.
Pseudocode
Step 1: start
Step 2: set sum 0
Step 2: write "Enter number."
Step 3: read num
Step 4: while num<>O do
set sum sum + num
write "Enter number.
Enter 0 to finish"
read num
endwhile
Step 5: write "The sum is" sum
Step 6: stop
23
Flowchart algorithm 7
Draw a flowchart for a program that will accept a group of numbers and find the largest
among them. The program stops when the user enters the value 999 for number.
Pseudocode
Step 1: start
Step 2: lgst 1(A value has been set as
we are going to compare the rest of the
numbers with it.)
Step 3: read num
Step 4: while num<>999
if num>lgst then
set lgst num
endif
read num
endwhile
Step 5: write lgst
Step 6: stop
24
Flowcharts with bounded iteration
Flowchart algorithm 8
Draw a flowchart for a program that will accept 20 scores of students and find their
average mark.
Pseudocode
Step 1: start
Step 2: totscore 0 [Set a value at the
beginning so that the value could be
accumulated.)
Step 3: for x 1 to 20
read score
set totscore totscore +
score
endfor
Step 4: set avgscore totscore/20
Step 5: write avgscore
Step 6: stop
25
Flowchart algorithm 9
Draw a flowchart for a program that will accept 30 integers and print the number of
positive and negative numbers.
Pseudocode
Step 1: start
Step 2: set poscount 0
Step 3: set negcount 0
Step 4: for n 1 to 30
read num
if num>O then
set poscount
poscount+ 1
else
negcount
negcount+ 1
endif
endfor
Step 5: write poscount, negcount
Step 6: stop
26
TESTING ALGORITHMS
Once the algorithm for a problem is determined, it is important that you test it to see if it works properly and
it can be implemented using a programming language.
TRACE TABLES
A trace table is a table that tests an algorithm for logical errors by calculating each of the variables in your
algorithm one statement at a time.
One good way of testing an algorithm is to use a trace table. A trace table is a table into
which you write the values of the variables in your algorithm, one statement at a time, using
appropriate values, just as a computer would, to see if it is producing the correct results.
This prevents going back to the analysis stage of problem-solving as the trace will help to
identify and solve the logical errors. If an error is detected after the trace, you know the
problem lies in the way the program is written, not the logic of the algorithm
Trace tables contain a column for each of the variables and a row for each pass [line) of
the algorithm.
Now let's look at some trace tables for the algorithms that involve sequencing, selection
and iteration [repetition) constructs.
Step x y z k
Step 1 5
Step 2 10
Step 3 15
Step 4 5
Step 5 15
Step 6 5
Step 7 5
Table 2.5
In Step 1, the value 5 is read and assigned to x, so the value 5 is placed in the first row of the
column with variable x.
In Steps 2 and 3, the values of y and z are read, so the value 10 is placed in the second row of the
column with variable y and the value 15 is placed in the third row of the second row of the column
with variable z.
In Step 4, the value of x is assigned to k, so k has the value of x which is 5. So the value 5 is
placed in the fourth row of column k.
In Step 5, value of z is assigned to y. The current value of z is 15, so the new value of y is 15.
In Step 6, value of k is assigned to z, since k is 5 the new value of z will be 5.
In Step7, the value of z is assigned to y which is 5, so the new value of y will be 5. [When a
new value comes, the old value is replaced with the new value.)
Therefore, the final values of x, y, z and k are 5, 5, 5 and 5 respectively, so the output of the
algorithm will be 5 5 5 5.
27
Trace table with selection construct
1. What is printed by the following algorithm?
Step 1: set m 5
Step 2: set n 4
Step 3: set p m+n
Step 4: set q m*n
Step 5: if p > q then
q O
else
p 0
endif
Step 6: display p, q
Step M N P Q
Step 1 5
Step 2 - 4
Step 3 - 9
Step 4 - - - 20
Step 5 - - 0
Table 2.6
In Steps 1 and 2 of the algorithm, the values 5 and 4 are assigned to m and n.
In Step 3, the value of m+n [5+4) is assigned to p,
In Step 4, the value of m*n [5 * 4) is assigned to q,
In Step 5, the values of p and q are compared to see if p is bigger than q. Since 9 is smaller than
20 the condition is false and so the else statement is implemented, and p is changed to O.
Step 6 is the output and the algorithm's output will be 0, 20.
28
7. In Step 3v, the control will be passed back to Step 3i and the process will be repeated until
the condition becomes false. So Steps 3ii to 3iv will be carried out five times. Each time the
value of m will be increased by 5 and c will be increased by 1.
Therefore, the trace table for the algorithm will look like this:
Step C M Calculation
Step 1 1
Step 2 5
Step 3i c<5 so repeat 3(ii)-(v]
Step 3ii - 10 m +- m+5 = 5+5 = 10
Step 3iii - - Display c,m
Step 3iv 2 - c+-c+1=1+1=2
Step 3v
Step 3i - c<5 so repeat 3(ii)-(v)
Step 3ii - 15 m +- m+5 = 10+5 = 15
Step 3iii - - Display c,m
Step 3iv 3 - c+-c+1=2+1=3
Step 3v
Step 3i - - c<5 so repeat 3(ii)-(v)
Step 3ii - 20 m+-m+5=15+5=20
Step 3iii Display c,m
Step 3iv 4 - c+-c+1=3+1=4
Step 3v
Step 3i - - c<5 so repeat 3(ii)-(v)
Step 3ii - 25 m +- m+5 = 20+5 = 25
Step 3iii - Display c,m
Step 3iv 5 - c=c+1=4+1=5
Step 3v
Step 3i - c=5 so repeat 3(ii)-(v)
Step 3ii 30 m +- m+5 = 25+5 = 30
Step 3iii - - Display c,m
Step 3iv 6 - c+-c+1=6
Step 3v - c > 5 so stop loop
Step 4 Display m
Table 2.7
The blank lines where no calculations take place are included here just for your reference, but
you can omit them when you create your own trace tables.
29
Step 2: set j 3
Step 3: i. for m 1 to 5
ii. set j j+x
iii. display j
iv. endfor
Step 1
Step 2
Step 3i
Step 3ii
Step 3iii
Step 3 iv
Step 3i
Step 3ii
Step 3iii
Step 3iv
Step 3i
Step 3ii
Step 3iii
Step 3iv
3i
j = j+x = 18+5 =
3ii - - 23
23
3iii - - - Display j
3iv
3i - 5
j = j+x = 23+5 =
3ii - - 28
28
...•. :: - Displa~ j
J
iv
Table 2.8
In the algorithm above, you should have noted that Steps 2 to 5 will be repeated five
Times as the variable m changes its value from 1 through to 5. The column with variable x
has a Key value and is not involved in any calculation inside the loop. In Step 3, j is assigned
to j + x.
30
8
3
18
23
28
Most of the problems for which we created algorithms so far have been relatively
simple. They have generally included only on task, such as calculate the
average, find the largest, or find the area of a square. But complex problems can
involve more than one task.
To tackle complex problems, we apply what is known as a TOP-DOWN DESIGN APPROACH or
stepwise refinement to problem-solving. This involves breaking down a problem into smaller,
manageable parts.
In top-down design a generalised solution to the problem is created at the beginning. This is broken
down further and further into smaller manageable tasks or steps until all the details have been
completed. The algorithms are developed for major tasks first and the rest of the tasks are considered
only after major tasks are finished.
For example, if you were carrying out the registration of students at school, you might have to break
down this problem into smaller simpler tasks like:
1. Entering student information (data entry).
2. Modification of student information.
3. Searching student information.
Fig 2.12 shows an example of a top-down design for the registration of students at a school.
Top-down design or step wise refinement is converting a bigger problem into main tasks and sub-tasks.
The major task completed first and the sub-tasks are completed after.
Fig 2.12
As you can see in the example above, the idea is to identify the main problem that is involved and
then divide it into simpler tasks. You then look at these individual tasks and see if there are any further
sub-tasks. Some tasks may have more sub-tasks than others.
By doing this, the problem will become more manageable, simpler and organised and the
algorithm produced will have fewer errors.
Using a top-down design approach to find the solution to a problem has the following
advantages:
31
1 Reusability - sections of algorithm can be used again in other algorithms that require a
similar solution, which saves time in future development of algorithms.
2 Easy to follow - as each task or sub-task performs only one function.
3 Easy to maintain - as each task is by itself, if there is a need for change in one task
you need to concentrate on that task only.
.,. 1 Explain why a top-down design approach is sometimes used to solve problems.
~ 2 A hotel wants to have a room booking system. When a guest arrives the receptionist would be
_ able to see which rooms are free and allocate one to the guest. When the guest leaves, the
I; room would be marked as free again. Each day the cleaners would be given a list of the rooms
III that are in use. At any time the receptionist would be able to use the room number to find the
8 name and home address of a guest, or could search the room system for a named guest. Draw a top-
down design diagram to show how the room booking system could be developed.
B 10 and 25 D -5 and 10
Multiple-choice questions
The following are problem-solving stages I analyse the
problem
II suggest possible solutions III implement
and review
IV define the problem
V select the best solution
The correct order of stages is:
A I, IV, II, III, V B IV, I, II, V, III
C IV, II, I, V, III D I, II, IV, III, V
Which one of the following is a variable?
Ax B "x"
C5 D "5"
To store fractional values, use the data type:
A integer B floating point
C character D string
Which of the following is not a characteristic of a good algorithm?
A precise B finite number of steps
C ambiguous D logical flow of control
Diagrammatic representation of an algorithm is a:
32
A flowchart B data flow diagram
C algorithm design D pseudocode
Which ofthe following are control structures?
A selection B sequencing
C repetition D all of the above
An example of a bounded iteration statement used in algorithm is:
A while-endwhile B while-wend
C for-endfor D repeat-until
Which one of the following is a selection construct used in algorithms?
A while-endwhile B if-then-else
C for-endfor D repeat-until
Which one of the following involves a logical operation?
A x>y B x>=y
C x>y and x=y D x< >y
Consider the following algorithm segment: x •.. x+y
y •.. x-y
write y,x
Suppose x = 10 and y = 15, after the completion of the above statements, the values ofx and y will be:
A 25 and 10 C 10 and -5
33