Problem Problem-Solving and and Program Design
Problem Problem-Solving and and Program Design
General problem-solving
solution to resolve
in our life we arefaced with many problems. Every problem requires a
solution. Finding the correct solution
it. For any problem, you might have more than one
to a problem can be considered as problem-solving. Problem-solving involves identifying
and analytical skills.
analysing and resolving problems using logic, reasoning skills
YOu can go to school every day using various means of transportation. We can consider
others on a daily basis, then you would choose the first option. Sometimes your parent's
vehicle is not available then you have to use the other options. From this you get the
clear idea that a problem can have many solutions, but you should use whichever
solution is most suitable to solve the problem.
ABOUT IT
Think about Stage 4: Select and justify the optimal solutions
weaknesses, choose the most
problems you their strengths and
y looking at the solutions andsolution that will solve the problem.
if your parent's vehicle
may have soived efticient or suitable (optimal)
new sh0es, or
the solution and review it to s e e everything is
fine with it. For example, after choosing the
deciding what option ofcatching the bus, you may
find that the bus stopped many times and made
career you would next time you will be able factor that into
late for school. So when you choose an option
ike to pursue. Did bus or implement another option.
your decision as to whether you should go by
you use these
five stages of
problem-solving?
Could you
solved the
haveComputer-based problem-solving
problem better if
you had used the Breaking down the problem into its significant parts
five stages? 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 dispiay their sum.
First of all, you might wonder if this isa problem statement, as you can solve it easily once
Problem-solving and Progream Desigo
2
you have a
solve this problem as it can't work on its
for the computer to
manually. But it is not easy to perform. Ihis is the reason why it is good
to
own. You need to give
all the instructions for it
to make the computer easily
solve it for you.
break down the problem into its parts
can be used to breakdown the problem. An
IPO
An IPO (Input-Processing-0utput) diagram
the input, output and processing parts of
diagram is a table with three columns showing
the problem. Storage is a form of processing because the computer stores data by using
constants. variable
A variable identifies a memory
An identifier that can store any value is called a location in which an item of data
variable. An identifier that always holds the same can be stored. The value of the
value is calied a constant. data can be changed.
Num1 Num2
10 15
Data types
The problem statements that looked at earlier required
we WHAT DoES IT AEAN?
to solve thee
data or inputs to be given to the computer
be given to the computer in data type
problem. To do this, data must Data types indicate the type of
a way it recognises. Data type
determines the type of data data that is stored in a variable,
variable
that a variable can store. A data type that treats a e.g. numbers or characters.
as a single unit is called an elementary data type.
1 List the main stages you should go through when trying to solve a general problem.
2 Variables and constants are both identifiers. Explain the difference between them.
3 What is the difference between an integer and a floating point number?
oblemsolving and Program
Design
2.5
2.5
Problem-solving using algorithms
Syou are aware,
computers are problem-solving devices. But
problems by themselves; computers cannot solve
you have to give them very clear instructions.
When we want
instructions to be very clear, we often break them down into smaller
Or
steps. For example, if your mom wanted parts,
you to bake a chicken, she would give you the
instructions in several steps that
you could easily follow, like
1 Preheat
your oven to 350 degrees.
2 Wash the
chicken thoroughly with water.
THINK 3
ABOUT IT Sprinkle salt and seasoning over each piece.
4 Put the chicken in the
A
recipe
is a kind baking dish and place it in the oven without covering
of algorithm. Have 5 Bake at 350
degrees for about one and a half hours or until the skin becomes a
golden
you come across brown colour.
any other 6 Take it out from the oven
and your baked chicken is ready to serve.
algorithms in real We do the same when
writing instructions for computers. These steps or instructions that
life? They are not can be used to
complete a task are called an algorithm. The word algorithm comes from
usually referred the word 'algorism',
meaning the process of doing calculations with Arabic numerals.
toas algorithms, Later, 'algorism' combined with the word arithmetic to form
but perhaps as 'algorithm'.
Bear in mind that these sets of
instructions. 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,
should create an algorithm before you
writing a program, not the reverse.
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
to tell you to take it out of the oven any steps, or forget
once it was baked. Some
steps or instructions that need to repeated, but there should algorithms might have
still be a clear end to the
process.
2 The steps must be precise
The instructions or
steps must be accurate; a computer cannot think for itself, so if
make a mistake in the instructions, it will have you
an incorrect outcome. For
your mom told you to bake the chicken for six hours instead of one and a
example, if
CSlook at the three steps for the following problem statement: its dred.
and calculate and display
length and width of a rectangle
AUMple: bet the
and width of the
are the length
statement, you would notice that inputs width,
ODlem the length and
and output is its area. Processing involves accepting
dngle, to use the
formula
ro
the area and it. This problem requires you
storing
diculating
calculating the area (multiply length by width)
main
to identify these three Steps,
O When a statement of a problem is given, you need and identify
the statement carefully
did in the previous problem statement. Look at
will be
S we
that are required. Normally,
the input and output
n e input,
Output and processing be in
will the
in the form of nouns and adjectives. The processing required
ressed
form of verbs or adverbs.
1 What is an algorithm?
2 List four characteristics of a good algorithm.
What are the three main steps involved in creating an algorithm?
4 What is meant by assignment?
Problem-solving and Program Design
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 1 or step1
Instruction 2 or step2 WHAT DOES 1T AAEAN?
Instruction 3 or step3
Instruction 4 or step 4 control structure
Control structures areinstructions
Here, the instructions will be completed in the order or statements that determine the
flow of control of steps in an
given. This control structure can be used for problems algorithm.
involving accepting inputs, performing calculations Sequence
storing them, and displaying the outputs. The following is Sequence is a control structure
a typical example of an algorithm that uses the sequence where instructions are written in
control structure where Steps 1 to 5 will be completed in the order they should take place.
Selection
The selection control structure is used in
problems with instructions to be carried out ifa
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
f <condition> then <instructions to be performed if the condition is true> else
sinstructions to be performed if the condition is false>
The following is an example of an
algorithm with a selection controi structure.
Step 1: Start
Step 2: Accept score
Design
P r Score
more
'student has failed' than 59 then
display 'the student has passed' else dispiay
Step 4: Stop
e
dDove
nas
example, if the score of a student is more than 59 it will display the udent
passed' and
if it is less than 60
it will displau 'the student has failed', which stu
Ony one of the two
messages can be displaued. If the condition is true (the score mea
is
nan s9, the
part after 'then' will be carried out, otherwise the mo
carried out. part after else win DE
bBounded iteration
c Unbounded iteration
Problemsolving and Program besign
2
2.6-2.7 How to create algorithms for problem
statements
Now that you understand how algorithms are created and their components, let's look at
some problem statements and write algorithms for them.
Problem statement 1
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 probleminto steps and write it in the form ofsingle 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% jf the price is more than S100.
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.
2 The algorithm can be written as:
Step 1: Start.
Step 2: Get the
price.
em-solving anc gramDesign
than $1000.
p 3: Check to see if price is morecalculate the discount using the formula
than $100,
4 f price is more
Problem statement 3
among them.
reate an algorithm that will read three
numbers and find the largest
involves
understand that the processing
s t a t e m e n t you need to
For this problem could approach this
the largest. You
and comparing three numbers to find
checking methods. Ihe two
let's c o n c e n t r a t e on two popular
problem in many ways, but
versions of the algorithm are as follows:
2 Method1
with the other two numbers to
In the first method could compare the first number
see which is larger, you
and then compare the second and third numbers the same way.
Step 1: Start.
Step 2: Get three numbers.
Step 3: Check ifthe
first number is bigger than the second and third number, if it is
bigger then display first number as the largest.
Step 4: Checkifthe second number is bigger than the first and third number, if it is
bigger then display second number as the largest.
Step 5: Checkifthe 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 Method2
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
value of first number as the number, then store the
the largest.
largest. Otherwise store the value of second number as
Step 4: Check if the largest of the first two
number. If it is, then store the numbers is bigger than the third
value of third number as the
Step 5: Display the largest number. largest.
Step 6: Stop.
From this
process, you can see that you
solving statement based on the have
can
several solutions for a
approach of the problem-
programmer.
Problem-solving and Program Design
2
Summary of key points
nt In this topic you have learned:
1 Narrative
2 Pseudocode
3 Flowchart
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.
WHAT DOES 1IT MEAN?
Step 2: Get the three numbers.
narratioe
Step 3: Add the numbers. Narrative is a representation of an
Step 4: Store the results in Sum. algorithm where each instruction
is written in everyday language.
Step 5: Display Sum.
Step 6: Stop.
olving and Program
Design
d n see, each instruction would be clearly understood by any person wn0 Speaks
English.
NOw let's look
at some other
examples of narrative.
Narrative algorithm 1
Wite an algorithm in narrative form to read in three numbers from the keyboard and
calculate and display their
product.
ememberthat, 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
ccepting 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 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
employee and calculate the income tax atprompt
the user to enter the
15%
salary of an
the salary and tax. if the salary more than S5000. Display
is
Problem-solving and Program Design
2
the
Now, in this algorithm, the input is the salary and the processing involves prompting
user to enter the salary, checking to see if the salary is more than 5000 and calculating
income tax. So the narrative
the income tax. The output is displaying the salary and the
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.
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 witha
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.
ram sign
Operators
d o r s are
symbols used
Lommonly used operators in for performingare:
calculations or making copa ons.
1 pseudocode
e u c operators-operators used to perform mathematical operations. lable .2
Tepresents the main arithmetic operators and their
operations.
Arithmetic operator Operation
Addition
Subtraction
Multiplication
Division
Table 2.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
less than
not equal to
equal to
3 Table 2.3
Logical operators-operators used
to make comparisons with
multiple criteria.
Logical operator 0peration
AND
And
OR
Or
NOT
Not
Just as in Table 2.4
order. The
mathematics, in computing all the
computer follows the BODMAS rule.operations
followed by Orders So
are carried out in
a
hierarchical
Addition and (such as powers and anything in Brackets will be done
Subtraction will be done last. So roots), then Division and
square first,
ensure that
you write them in the when you are
order in which writing Multiplication.
instructions
want you the you must
computer to carry them out.
Problem-solving and Program Design
Pseudocode terminology
terms used in pseudocode are:
Thegeneral programming language
.
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
Pseudocode algorithm 1
Write a pseudocode algorithmto 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
Step 1: Start.
Step 2: Get the three numbers.
Step 3: Add the three numbers, divide by 3 and store the results.
Step 4: Display the results.
Step 5: Stop.
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.)
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
display itsolgorithm
calculate and that will
accept the length and width of a rectangi and
area.
Step 1: start
Ste
Step 2: input
Step 3: input lengtl
width
(Accept length and store
st it in variable length
cIea
(Accept width and store
st it in variable idth.)
length width (Calculate the area by
*
Pseudocode algorithm 4
Write a pseudocode that will accept three unequal numbers andfind the smallest among
them.
Step 1: start
Step 2: read numi,num2,num3 [Accept three numbers and store them in variables
num1, num2 and num3.)
Step 3: if num1<num2 then
set sml numi
else
setsml num2
endif (Find the smaller of the first two numbers and store it in the variable
sm
Step 4: if num3<sml then
sml = num3 (Check if the third number is smaller than the
smaller value ofthe first two numbers, stored in variable sml. If
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
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 ind their product.
Step 1: start
Step 2: set product «+1[Start product offwith a value of 1.]
Step 3: fori+1 to 20 [This step repeats as the counter counts from 1 to 20.)
write "Enter next number"
read num
*
set productproduct num [Multiply the currentvalue of
product by the latest number entered.)
endfor
Step 4: write "The pioduct is" product
Step 5: Stop
he variable i acts as a counter
iteration that begins at Step 3.A counter must be
for the
an integer. When the algorithm reaches endfor it loops back to the 'for line and adds 1to
the value of i. This continues until the last
time, in this case, wheni has a value of 20.
Problem solying and
Program Design
Pseudocode algorithm 6
its sum.
ehe apseudocode algorithm that will accept a groupP of numbers and calculate
program stops
when the number.
use enter O as the
Step 1: start
Step 2: set sum = 0 (Start sum off with a value of U.)
Step 3: write "Enter first
Step 4: read num number.
Step 5: while num<>0 do
current value of sum to the
set sum sum + num [Add the
latest number entered.)
Enter 0 to finish"
Write "Enter next number.
read num
endwhile
Step 6: write "The sum is" sum
Step 7: stop
1 Write a narrative algorithm that will accept the radius of a circle and calculate and display its
area.
2 Write
a
pseudocode algorithm that will accept three numbers and calculate and display the
largest of the three.
A3 Write a pseudocode algorithm that will accept the marks in a test for a
then calculate and group of 25 students
display the average mark.
4 Add steps to the
previous algorithm so it also displays the highest mark.