Problem Solving and Algorithms
Problem Solving and Algorithms
Learning Objectives
• To understand what it means to be a “problem solver” and a “creative thinker”.
• To understand what an algorithm is and what rules apply when developing one.
• To be able to write pseudocode and draw IPO diagrams to solve simple problems.
1.1 Introduction
Problems are a part of life. You have already faced many problems in your life and you
undoubtedly face some right now. You will become more effective, and therefore, happier, if you
become a better problem solver.
Not having any problems would essentially leave you with no choices in life, which would be dull
and uninteresting. In fact, life consists of a constant stream of problems, some of which are not
really undesirable. Sometimes we even create problems for the enjoyment of the challenge of
solving them. Athletic contests, puzzles and many games present problems that have been created
for the purpose of trying to overcome obstacles and "win".
Becoming an effective problem solver does not merely involve applying a problem solving method
in a mechanical fashion any more than becoming a mature critical thinker involves mastering a set
of thinking skills. Rather, solving problems, like thinking critically, reflects a total approach to
making sense of experience. When we think like problem solvers, we approach the world in a
distinctive way. Instead of avoiding difficult problems, we have the courage to meet them head-on
and the determination to work through them. Instead of acting impulsively or relying exclusively
on the advice of others, we are able to make sense of complex problems in an organized way and
develop practical solutions and initiatives.
Everyone can do creative thinking and problem solving. We can all learn to use the abilities of our
right brain more fully. We can learn to perceive characteristics and relationships that otherwise
would go unnoticed by others. Creative thinking is not just a magic bursting of ideas in the minds
of especially gifted individuals. Even though some people have more natural creative talent than
others, we can all be creative in some ways.
Although creative thinking is not as structured as traditional problem solving, creative people have
demonstrated that they have several characteristics in common. If we want to become more
creative, it may help to try and develop the characteristics shown in the figure below:
Questioning
attitude
Ability to
Flexibility
concentrate
Characteristics
of a creative
thinker
Self-
Persistence
confidence
1.2.1 Brainstorming
Creative thinking can also be done by a group. One type of group creative thinking has been made
popular by Alex Osborn and is called brainstorming. When brainstorming:
1. Criticism is not allowed. This will come later when the ideas are evaluated.
2. The wilder the idea, the better. It is easier to discard or modify ideas than to think of new
ones.
3. Quantity is more important than quality - the more ideas, the better.
4. Combinations and variation of ideas are welcome. One idea leads to another.
1.2.3 Exercises
1. Connect all of the following nine dots by using only four straight lines and without lifting
your pen from the paper or going back along the same path.
1, 3, 4, 7, 11, 18, ??
4. You have 14 black socks, 10 red socks and 6 white socks mixed up in a drawer. What is the
smallest number of socks you need to take out of the drawer without looking to be sure of
having a matching pair (i.e. at least two of the same colour)?
5. Siya needs to send a secret message in a box to John at the other side of town.
They both have a padlock, but for security reasons, they only have keys for
their own padlocks. How can Siya send the message to John in such a way
that John can open the box, but nobody else can intercept the box and read the
message?
6. Three travellers register at a hotel and are told that their rooms will cost R100 each so they
pay R300. Later the clerk realizes that he made a mistake and should have only charged
them R250. He gives a bellboy R50 to return to them but the bellboy is dishonest and gives
them each only R10, keeping R20 for himself. So, the men actually spent R270 and the
bellboy kept R20. What happened to the other R10 of the original R300?
7. Professor Random can only take one of his assistants Alex and Tandi to the science
conference. To determine who will go, he proposes a game, and puts 21 sticks on the table.
Taking turns, Alex and Tandi may pick up one, two or three sticks. Whoever picks up the
final stick must stay at home and look after the laboratory.
They toss a coin to see who goes first, and Tandi is first to pick. Alex smiles, as he knows
he is going to the conference. How does Alex make sure he wins?
8. The "Towers of Hanoi" is an ancient problem involving three pegs. On the first peg sits a
series of n concentric disks, each of which is smaller in diameter than the disk directly
below it. The second and third pegs are initially empty. The object is to transfer all the
disks to peg 3, one disk at a time, but at no time may a larger disk rest on a smaller one.
Solve this problem for three disks (shown below), listing all the steps to be followed.
1 2 3
9. You have a fox, a chicken and a sack of grain. You must cross a river with only one of
them at a time. If you leave the fox with the chicken, the fox will eat the chicken. If you
leave the chicken with the grain, the chicken will eat the grain. How can you get all three
across the river safely? List your steps.
10. A programmer was dispatched to a remote town to get a program up and running. As is
often the case with programming assignments, he did not know how long the job would take
him. In any event, it was necessary for him to return to his home office in one week.
Upon his arrival at the hotel where he was to stay, he discovered that his wallet had been
stolen. All that he had with him of value was a small gold chain containing seven links.
After he discussed the problem with the hotel manager, they agreed that payment of one
link of the chain per day would be exchanged for meals and lodging. The hotel manager set
one condition, though: only one link of the chain could be cut. The programmer determined
a way to stay at the hotel from one to seven days and to comply with the hotel manager's
request. How? List all your steps.
1. Boil water
2. Put coffee into cup
3. Pour water into cup
However, the steps are not in sufficient detail so they need to be refined. Step 1 can be refined as
follows:
1. Boil water
1.1 Fill kettle with water
1.2 Switch kettle on
1.3 Wait until kettle has boiled
1.4 Switch kettle off
Eventually after a number of refinements, the robot will be able to make a cup of coffee. The final
solution is shown below:
1. Boil water
1.1 Fill kettle with water
1.1.1. Place kettle under tap
1.1.2. Open tap
1.1.3. Wait until kettle full
1.1.4. Close tap
1.2 Switch kettle on
Notice that the steps are done in sequence, from first to last.
1.3.2 Exercise
Imagine that you have given someone a set of 20 cards each showing a different number. Write
down the steps you would use to explain to the person how to sort the cards into ascending order.
3. Information concerning the necessary transformations for going from the initial situation to
the final situation.
Think of the transformations as the set of ordered steps needed to change what is given to what is
required. Consider a recipe in a cookery book. We initially have a number of ingredients and wish
to transform them into a pizza. The recipe is an example of a problem solution divided into simpler
parts or steps describing how to transform the ingredients into the pizza.
The three parts of a problem can be summarized using a simple diagram as shown below:
For the problem of making the pizza we can use the following diagram:
4. Write in the Transformations column the set of ordered steps that describe exactly and
unambiguously the transformation of what is given into what is required.
1.3.4 Examples
1. Express the temperature 85 degrees Fahrenheit (F) in degrees centigrade (C).
5 (°F - 32)
9
Transformations in algebraic notation
2. Imagine a stack of cards with a number written on each. The problem is to find the largest
of these numbers. The solution is easy if there are only five cards because one can tell at a
glance which number of largest. However, if there are 1000 cards a quick solution is not
possible. A systematic process that works for any number of cards is needed. One such
process is shown below:
6. Go to step 2.
Finding the largest number in a stack of cards
1.3.5 Exercises
1. Construct diagrams that describe the solutions to the following problems:
2. Construct a diagram that describes the solution to the following problem: Mr Math E.
Mattox has just purchased a plot in the city. The plot is square, each side measures 300m
and the entire plot is bordered by streets. His problem is to divide the plot into rectangular
sections, each with 100m frontage.
2. It must be unambiguous so that anyone can perform the transformations correctly every
time.
3. It must always give the same results for the same initial situation.
When the solution to a problem is to be implemented on a computer the solution must be stated in
terms of the set of operations that the computer can perform. One must therefore become familiar
with the few operations that computers can perform. Five of these operations are:
2. Compare two pieces of information (including numbers) and, depending upon the outcome
of the comparison, select one of two alternate actions.
3. Receive and output information (e.g. numbers, characters such as letters, a graphical image,
or even information about a button on the screen being clicked by the mouse).
Any algorithm to be used on a computer must be stated in terms of the five well-known computer
operations.
1.4.1 Examples
1. Suppose we have a stack of computer cards with a number punched on each. The problem
is to find the largest number. A blank card will be placed at bottom of the stack so that the
computer can determine when the stack is empty. The solution is essentially the same as the
one examined earlier. The algorithm is shown below:
2. Euclid's algorithm for finding the greatest common divisor of two numbers is stated as
follows:
Divide the smaller number into the larger. If the remainder is not zero, replace the
original two numbers with the remainder and the smaller of the two numbers, and
repeat the division. Eventually the remainder will be zero, in which case the
smaller number is the greatest common divisor.
For example, the greatest common divisor of 8 and 12 is 4; 4 is the largest number that can
be divided into both 8 and 12 with a remainder of 0. Euclid’s algorithm can be applied to 8
and 12 as follows:
2. If the remainder is not 0 (it is 4), replace the two original numbers with the remainder
and the smaller of the two numbers. The two numbers are 4 (the remainder) and 8 (the
smaller of the two original numbers).
3. Repeat the division (divide the smaller number into the larger.)
8 / 4 = 2 remainder 0
4. Eventually the remainder will be 0 (it is). The smaller number is then the greatest
common divisor. 4 is therefore the greatest common divisor.
The computer algorithm that uses this algorithm to find the greatest common divisor is
shown below. Note that it is assumed that the two numbers will be given in ascending
order.
The simplest way to do a trace is to make a table (called a trace table) and keep a step-by-step
record of what information is recorded. When a step or group of steps are repeated, each repetition
is called a pass. Therefore, when a group of steps are performed the first time, it is known as the
first pass. The second execution of the group is the second pass, and so on.
1.5.1 Examples
1. A trace of Euclid's algorithm for the numbers 36 and 88 is shown below:
2. A trace of the algorithm for finding the largest of the numbers 7, 5, 8, 12, 4, and 2 is shown
below.
1.5.2 Exercises
1. Construct a computer solution diagram for finding the smallest number of a set of numbers,
each of which appears on one computer card.
2. Perform a trace on the algorithm in exercise 1 for the numbers 7, 5, 8, 12, 4, and 2.
3. Construct a computer solution diagram for an algorithm that finds both the smallest and
largest numbers of a set of numbers, each of which appears on a computer card.
4. Perform a trace on the algorithm in exercise 3 for the numbers 7, 5, 8, 12, 4, and 2.
5. Perform a trace on Euclid's algorithm (computer solution) for the numbers 45 and 235.
6. Perform a trace on Euclid's algorithm (computer solution) for the numbers 416 and 822.
7. Construct a computer solution diagram for printing a list of all odd numbers contained in a
set of numbers, each of which appears on a computer card.
8. Perform a trace on the algorithm in exercise 7 for the numbers 12, 7, 8, 2, 9, and 1.
9. Suppose that Mr. Rich deposits R10,000 into a savings account that earns 5% interest
annually and that Mr. Thrift deposits R5,000 into a savings account that earns 15% interest
annually. Construct a computer solution diagram that finds and prints the annual balances
until Mr. Thrift's balance exceeds Mr. Rich's. Assume no other deposits are made.
10. Construct a computer solution diagram for the following problem: Given a list of names and
ages, prepare a list of names of people aged 65 and over.
11. Construct a computer solution diagram for the following problem: Given a list of names
with ages and cities of residence, prepare a list of names of people aged 65 and over who
live in East London.
Remember that computers are able to perform a number of operations. Five of these are:
• Compare two pieces of information (including numbers) and, depending upon the outcome
of the comparison, select one of two alternate actions.
This section takes a closer look at the pseudocode applicable to each of the operations. However, it
is necessary to first examine how a computer stores information.
When writing pseudocode we use unique names to identify storage locations, instead of using
addresses. Each name corresponds with an address and describes the information stored at that
address.
For example, a storage location that is used to store an employee's hourly wage might be called
WAGE. The amount of a sale could be called AMOUNT or SALE AMOUNT. A student
identification number might be STUDENT ID or STUDID. It is important that the names be short,
natural, clear, descriptive and unambiguous. From this point on a reference to a name such as
AMOUNT will imply a reference to the information at the address identified by the name.
Both of the above take the employee number and place it in the memory location named
EMPNUM.
Each of the above stores zero in the memory location named COUNTER.
Set X to Y.
The statement above saves the contents of the storage location named Y into the storage location
named X.
The statement above stores the result of LENGTH x HEIGHT in the memory location AREA.
SUM = A + B
This statement uses algebraic notation to instruct the computer to add what is stored at A to what is
stored at B and to save the sum in the storage location named SUM. Notice that the equal sign does
not mean equality, but means “store” or “save”.
COUNTER = COUNTER + 1
This statement instructs the computer to take what is in the storage location named COUNTER,
add 1 to it, and store the result in COUNTER.
Input in pseudocode is usually indicated by the keywords read and get. Output in pseudocode is
usually indicated by the keywords print, write, and put. The following are examples:
This instructs the computer to use an input device to receive two numbers. The first is to be stored
in memory location SMALLER and the second in memory location LARGER.
Print SMALLER.
This instructs the computer to take the number stored in the location named SMALLER and, using
an output device, move it "outside" in some readable form.
Often one needs to print a series of characters to label output. Such a series of characters is called a
label, a character string or a literal and is enclosed in quotes. Anything placed between the
quotation marks will be printed as it appears. The following is an example:
Print "Name"
Print "X"
Print X
This prints the information in the memory location named X, for example the number 5.
This prints X = 5, assuming that the memory location named X contains the number 5.
Add 1 to COUNTER.
This adds 1 to the number stored in the memory location named COUNTER.
This multiplies PRICE with TAX RATE and stores the result in SALES TAX.
This compares NUMBER with LARGEST and if NUMBER is larger, NUMBER is assigned to
LARGEST.
This compares SEX with the literal M and if SEX contains an M then the literal Male is printed
otherwise the literal Female is printed.
Note that End if is placed at the end of the If operation and the operations in the then and else
segments are indented so that each stands out clearly from the other.
COUNTER = 1
Loop while COUNTER <= 5
Print "*"
COUNTER = COUNTER + 1
End Loop
*
*
*
*
*
NUMBER = 1
Loop while NUMBER <= 100
Print NUMBER
NUMBER = NUMBER + 2
End Loop
Let’s examine the problem of converting degrees Fahrenheit to degrees centigrade again. The
problem is stated as follows:
Construct a computer program that will convert any temperature expressed in degrees
Fahrenheit to degrees centigrade.
1.7.1 Examples
1. Earlier we looked at an algorithm for determining the largest number in a set of numbers.
The following is an IPO diagram for this problem:
5. Stop.
IPO diagram for finding the largest number
2. The following is an IPO diagram finding the greatest common divisor using Euclid’s
algorithm:
6. Stop.
IPO diagram for finding the greatest common divisor (Euclid’s algorithm)
3. Construct an IPO diagram for the problem of finding all of the even numbers in a set of 10
numbers.
4. Construct an IPO diagram for the problem of finding and printing all two-digit odd numbers
that are not divisible by 3 in a set of 100 numbers.
5. Construct an IPO diagram for the problem of separating lists of names of males and females
from a list containing names and sexes.
So, a computer program can be defined as a series of instructions that are obeyed by a computer to
carry out a task, such as calculating a salary, playing a game or sending an e-mail (Bell & Parr,
2009). Programming is the process of designing/writing algorithms and coding the algorithms into
Take note of the following characteristics of a program as given by Bell & Parr (2009):
• The steps are done in sequence, from the first step to the last.
• Some steps can be carried out only if a condition is met (called selection).
• Some steps can be grouped together into a sub-task (called a method, function, procedure or
sub-routine) to simply the list of instructions.
• Some useful sub-tasks/methods already exist and can be called by our instructions.
• Steps can use existing objects (e.g. buttons, scroll bars and databases) to make our list of
instructions simpler.
The quality of a computer program depends on the quality of its design. Therefore, the process of
designing/writing algorithms must be done carefully. Bear the following in mind:
• The correct output depends on the input being correct as well as the program being correct.
• Algorithms must be tested to ensure that they produce the correct results. If errors are
encountered, they must be eliminated.
• Poor design and lack of developmental testing results in errors built into program as it is
developed.
• The primary goal in programming is to design and develop correct programs, not to correct
poorly designed and incorrect programs.
REMEMBER
1. If we give the computer the wrong instructions or instructions in the wrong order, the task won’t
be done correctly.
2. Construct an IPO diagram for the problem of accepting a maximum temperature and a
minimum temperature and printing the average temperature.
3. Construct an IPO diagram for the problem of accepting a measurement in inches and
converting it to centimetres (cm = 2.54 * in).
4. Construct an IPO diagram for the problem of finding and printing all three-digit odd
numbers that are divisible by 3 in a set of n numbers. Do a trace through your solution with
3 appropriate numbers.
5. Construct an IPO diagram for the problem of computing the perimeter of a square with side
s. Output the values of the side and the perimeter with appropriate labels. (Assume that s is
positive).
6. Construct an IPO diagram for the problem of computing and printing a triangle’s area given
its base and height.
7. Construct an IPO diagram for computing the sum of the first n integers. For example, the
sum of the first five integers is 1 + 2 + 3 + 4 + 5 = 15. Print the value of n and the value of
the sum.
9. Construct an IPO diagram for the problem of finding a student’s average test score for five
tests. Print the student’s name, five test scores and the average score, all appropriately
labelled. Perform a trace for the program for Joe Sudds, who scored 76, 85, 92, 79 and 85.
10. Construct an IPO diagram for the problem of accepting a time as a number of seconds after
midnight and outputting it as hours:minutes:seconds. For example, if the input were 50000
the output should be 13:53:20.
11. Construct an IPO diagram for the problem of accepting an input value in metres and
converting it to centimetres, millimetres and kilometres, and displaying the results.
12. Construct an IPO diagram for the problem of accepting a number from 1 to 7 and printing
the corresponding day of the week. For example, if 2 is entered then “Monday” must be
printed.
13. Construct an IPO diagram for the following problem: Input the amount of money spent to
fill a fuel tank, the price per litre, and the number of kilometres driven since last filling the
tank. Compute the kilometres used per litre, and print with headings the price per litre and
the kilometres per litre.
14. If one wants to send a parcel, postage charged will depend on the weight of the parcel. If a
parcel weighs 2kg or less, postage will be R30.25. An additional R10.05 is levied for each
kg or part of a kg in excess of 2kg. Construct an IPO diagram for the problem of reading in
the weight of a package and printing the total amount owing. Test your solution with a trace
using a value of 3.2 as input.
15. A salesman gets a commission of 5% on sales of R1,000 or less and 10% on sales of more
than R1000. In other words, a salesman who sells goods to the value of R1,500 gets a
commission of 5% on R1,000 and a commission of 10% on R500. Construct an IPO
diagram for the problem of accepting the sales amount as input, computing the salesman’s
commission, as well as the amount the company will receive after the commission is
deducted.
16. At the beginning of a journey the reading on the odometer of a motorcar is “distance”
kilometres and the petrol tank is absolutely full. Upon completion of the journey the
reading on the odometer is “total” kilometres and it takes “number” litres to fill up the tank
again. Construct an IPO diagram for the problem of reading the values “distance”, “total”
and “number” as input and to compute the total distance travelled and the petrol
consumption,
17. Construct an IPO diagram for the problem of reading in a value for N, a positive integer,
and then determining the factorial function:
N! = 1 x 2 x ... x N
18. Construct an IPO diagram for the problem of finding the largest number from a list of five
positive integers entered by the user.
19. Construct an IPO diagram for the problem of printing a sequence of 15 numbers. The first
number is 1, the second 2, the third 4, and so on; each number is twice the preceding
number.
20. Construct an IPO diagram for the problem of accepting the name and age of a first person
and the name and age of a second person. Assume the ages are different. Print the names
and ages in the following form:
Determine which person is older, and print both names in the following form:
21. Construct an IPO diagram for the problem of accepting a customer's name, a purchase
amount, and a tax code, and computing the sales tax. Print the customer's name, purchase
amount, sales tax and total amount due. The tax codes are as follows:
1.10 References
Bell, D. & Parr, M. (2009). C# for Students. Pearson Education Limited, Great Britain.