0% found this document useful (0 votes)
347 views

Problem Problem-Solving and and Program Design

This document discusses problem-solving and program design. It outlines the general stages of problem-solving as: 1) defining the problem, 2) analyzing the problem, 3) proposing and evaluating possible solutions, 4) selecting and justifying the optimal solution, and 5) implementing and reviewing the solution. It then explains how these stages are modified for computer-based problem-solving, focusing on breaking problems down into their input, processing, output, and storage components using an IPO diagram. An example of getting two numbers, adding them, and displaying the sum is used to demonstrate this breakdown.

Uploaded by

Riah Tiffany
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
347 views

Problem Problem-Solving and and Program Design

This document discusses problem-solving and program design. It outlines the general stages of problem-solving as: 1) defining the problem, 2) analyzing the problem, 3) proposing and evaluating possible solutions, 4) selecting and justifying the optimal solution, and 5) implementing and reviewing the solution. It then explains how these stages are modified for computer-based problem-solving, focusing on breaking problems down into their input, processing, output, and storage components using an IPO diagram. An example of getting two numbers, adding them, and displaying the sum is used to demonstrate this breakdown.

Uploaded by

Riah Tiffany
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Problem-solving and Program Design

2.1-2.4 Problem-solving using computers

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

this as a problem. You have options like:


a Go with your parents in their vehicle.
b Gowith your friend or neighbour in their vehicle.
c Catch a bus.
d Go by bicycle.
e Walk.
is far and you comfortable that you travel with
Maybe the school or your parents are not

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.

Generally problems can be solved by following stages:

Stage 1:Definition ofthe problem


In this first stage, you have to look at the problem carefully and identify what is the actual
problem, and then write it down. This is known as the problem statement. By doing this
you will be able to ensure that you have the right problem to solve. In the above example
your definition of problem would be how to reach school on time.

Stage 2: Analyse the problem


In this stage, you need to look at the problem and identify the inputs, outputs and
processing that is required to complete the task. In order to reach school your input will
be getting the transportation, output will be reaching school on time, and processing
Would be travelling in the chosen transportation.

Stage 3: Propose and evaluate possible solutions


As realised above, problems may have more than one solution. In this stage you are to
identify the solutions that are available, see which ones are suitable for solving the task
and the strength and weakness of each solution. In the above problem staterment you
Problemm-solving and
Program Desig

most suitable for


which one of them is
THINK you.
Optons so you would need
to decide

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)

recently, for is broken, you might catch a bus.

example, Stage 5: Implementation and review


choosing some is
stage, the optimal solution put
In this into practice and checked to
see if it works. Observe

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:

Stage 1: Definition of the problem


As mentioned earlier in the stages of general problem-solving, this is where the actual
problem is clearly defined. The problem must be looked at carefully and if it is not
phrased properly, you should modify that to make sure that it is clearly stated. We know
that once a problem is well understood, we can solve it easily.

Stage 2: Analyse the problem


In this stage, you need to identify the inputs to be used, outputs required, values to be
stored [if any), and the processing that needs to be done to get the correct outputs.
Inputs will be the instructions that are needed to solve the problem, processing will be
working with the given instructions, output will be the expected results and storage will
be the values that need to be stored in order to display the results. It is a good practise to
break down the problem into its four pieces as input, processing, output and storage.

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

calculator to add the


numbers or it you get a piece of paper to add them
can

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

its processing capabilities.


breakdown of problem into its parts.
Table 2.1 is an IPO diagram showing the

Input Processing Output


Accept two numbers
Add the numbers
Two numbers Sum
Store results
Display the result Table 2.1
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

Stage 3: Propose and evaluate possible solutions


In the problem of how to get to school, we noted that there are many solutions. Generally,
all problem statements have more than one option. So, you evaluate each option to see
which is most appropriate for you and choose the best option.

Stage 4: Develop and represent an algorithm


In this stage, break down the problem into simple WHAT DOES IT MEAN?
manageable steps, so that you can handle them easily.
These simple steps of a problem are known as an algorithm
An algorithm is a finite numberof
algorithm. You will learn about the algorithms in detail accurate, unambiguous steps that
later in the section on page 76. solve a problem or task.

Stage 5: Test and validate the algorithm desk checking


Desk checking is manually going
Check the algorithm you wrote using some values to through an algorithm with a set of
ensure that it produces the required results. This process different values to see if it will
of desk checking allows you to solve some errors before produce the required results.

you convert it into computer instructions. progra


A program is a set of instructions
Stage 6: Implement the algorithm written in a programming language
that directs the computer to solve
In this stage, the steps of algorithm are written using a
a problem.
programming language so that a computer can operate
on it. When the instructions are in a
programming
language,the instructions are called a program.
blem solviag and
Program Design

Stage 7: Run the program


is
a g e , run your program using a programming language
to see
ifthe program
producing the correct results.
Stage 8: Document and maintain the program
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.

Constants, variables and literals


Computers use memory to store data and information. WHAT DOES IT MEANT
Each of the data items being inputted has to be stored
in a location in the computer's memory. You could fdentifien
consider memory as a collection of boxes. Each of The name used for identifying a
variable or a constant.
these boxes can hold values, that is, data items. To
represent a box to store a value, it is represented with constar
A constant identifies a memory
a labelcalled an identifier. location where a fixed item of data
There aretwo kinds ofidentifiers:variables and is stored.

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

Fig. 2.1: Storing values in a memory location


In Fig 2.1 above, Num1 and Num2 identifiers for two memory locations and they store
are
the values 10 and 15. Num1 and Num2 are variables as
they are identifiers of storage
ocations that can store any values.
Please that when a new value is placed in a variable, the old value is ovewritten
note
byy
the new value because, as see, only
you can 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', "largest="'and 'enter number.
They are normally used with the
input/output instructions that appear as a message for the user.
Problem-solving and Program Deslg

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.

A variable can store any of the following data types:


5,
integers: These are whole numbers, positive or negative without decimal places, e.g.
45, 39, and +126.
real numbers: These positive or negative numbers with decimal
Floating point or are

values, e.g 0.55, 39.2,-5.6 and +6.7.


Characters: A character is anything that you can key in from a keyboard. This includes
letters, numbers and special characters, e.g. k, L, # and*.

Summary of key points


In this topic you have learned:

that a problem can be solvedin stages.


.howa problem can be broken down in parts.
that data is stored as variables, constants and literals.
that the data stored in variables belongs to a 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

chicken would be burned!


halí, your
Probiematolyngand Program Design

3 The steps must be unambiguous


can be
The steps must be very clear so that they
carried out easily - it wouldn't work if your mom just
told you to put the chicken in the oven without saying efficient fnstruction
An efficient instruction is one that
for how long or at what temperature. An instruction is clear and can be carried out.
that can be carried out is called an efficien
fte e of control
instruction. A logical flow from one process to
the next is known as a flow of
4 The steps must have flow of control from one
control.
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 t to the
chicken.
5 The steps must terminate
There must be a clear end to the instructions. The final step in the process of baking a
chicken would be to take the chicken out of the oven. The steps for solving the
problem must have a start and end.
6 The steps must lead to an output
An algorithm must have at least one output. In the example of baking a chicken, the
output would be to have a baked chicken!

Steps for developing an algorithm


Any algorithm that is used to solve a problem or task can be divided into three main steps
1 The input step- This is where the instructions from the user are being gathered.
2 The processing step- Thisis where the instructions are worked through. It can involve
all or some of the following steps:
a Assignment- In this step the values are assigned to variables.
b Decision- This step will be included when you have to check for any conditions to
be followed.
c Repetition-When you have to repeat a task a specified number oftimes then you
would include this step.
3 The output step- This step is used to display the results.
em-solving and Program Desiggn
Program Design

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.

Summary of key points


In this topic you have learned:
that a solution can be found by breaking the problem down into steps in an algorithm.

that an algorithm should be finite, precise, unambiguous.


that an algorithm should have a logical flow of control, should terminate and should
produce an output.

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

the 2.5-2.6 Control structures


The steps that are identified for preparing algorithms can be written using three basic
control structures 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
ps, 1 Sequernce
ntbeify 2 Selection
3 Iteration (Repetition)

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.

the order given. selection


Selection is a control structure
Step 1: Start where a choice has to be made
Step 2: Get two numbers between two or more options.
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 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

Iteration or repetition or loop


teration forms the
repetitive stage of the processing8 WHAT BOES IT MEAN
step. There are times where we have to repeat a
process. Suppose you want to accept 100 numbers repetition ar iteration
from the user and find their Repetition or iteration control
sum, it would be wise to structures are used to repeat a
repeat the process of getting the numbers 100 times
certain process a number of times.
rather than writing instructions 100 times to
accept
the
bounded iteration
numbers. Repetition ofa set of instructions a fixed
Bounded iteration is the process
number of times is called bounded iteration. of repeating a set of steps or
Commonly used iteration statements in algorithms instructions a fixed number of
times.
includefor-endfor.
There are also situations where the process has to be unbounded iteration
Unbounded iteration is the process
repeated until a specific condition becomes false. For of repeating a set of steps or
example, find the sum of a set of numbers terminated instructions until a particular
by 0. Here, getting numbers and finding their sum will condition becomes false.
be repeated until the user
supplies 0 as the value for
the number. Repeating a set of a number of
steps
times until a
particular condition becomes false is called unbounded iteration. Common
unbounded iteration statements are
while-endwhile, and repeat-until.
Summary of key points
In this topic you have learned:
that algorithms use the control structures
of sequence, selection and iteration.

1 Name three types of control


structures that are
2 State the difference commonly used in programming languages.
between bounded iteration and
3 Give one unbounded iteration.
example of statement used in following control structures:
a Selection

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

discount =price* 10/100. formula new price =


price discount.
a l c u l a t e the new price by
using the
P 6: Display the new price.
Step
Step 7: Stop.

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:

how to write an algorithm to solve a problem statement.

1 For each of the following problem statements


aidentify the input, output and processing steps.
b write thealgorithm.
Write an algorithm to read three numbers and find their product.
Write an algorithm that displays the area ofa rectangle by accepting length and width from
the user.
Write an algorithm that will read the radius of a circle and calculate and display its
perimeter.

o 2.6-2.7 Representing an algorithm using


narrative and pseudocode
In the previous topics, you learned that algorithms are step-by-step definitions of a task
or a problem. In this topic you will learn about how they are represented. Algorithms can
be represernted in three different ways, they are:

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

greater than or equal


to

less than or equal to

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

.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 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
*

length and width and mulupig


SOutput area [display store the results
the results storedininarea.
variable area.)
Step 6: stop
n e two examples above used the control structure sequence, so each
D e carried out inthe order it has been written. Now let's look at examples
of
pseudocode where the control structure selection 1s
use
Pseudocode algorithm3
e apseudocode algorithm thatwillprompt the user to input two unequal numbers
and find which is the larger.
Step 1: start
Step 2: write "Enter frst 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
Step 6: ifa>b then variable b.]
setlarge a
eise
setlarge b
endif (Check to see if a is bigger than b. If it is, then store
variable large otherwise store the the vaiue of a in
value of b in variable large.)
Step 7: write large [Display the value of the
In the
variable large.)
example above, the selection construct
instructions over several lines, it is a if-then-else was used. When
in writing
Step 6, because it increases the good practise to write them in an indented format
readability of the program and also as
identify any errors. helps to easily
Now, let's look at another
example that involves
multiple selection statements.
Problem-solving and Program Desig9

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

Now let's look


another m p l e with the u n b o u n d e d iteration c o n s t r u c t , u s i n g a w
example
endwhile loop. v

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

Summary of key points


In this topic you have learned:

howto wite an algorithm in narrative and pseudocode formats.

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.

You might also like