PROBLEM SOLVING AND PROGRAMMING

advertisement
CH/S4CIT(A)/Oct. 2005.
PROBLEM SOLVING AND PROGRAMMING
Problem Solving Procedures

Problem Identification. Clearly explain and present a problem.

Problem Analysis. Find out the type of input data, and the processing and output requirement.
Break the large problems into a set of smaller tasks separated from each other.

Algorithm Design. Design a set of steps which can be used to handle the required tasks. (May be
written in flowchart or pseudocode.)
** Algorithm. A finite number of steps with a set of well defined rules solving a problem.

Solution Development. Write down the steps in the algorithm in a computer programming
language.

Debugging and Testing. Locate and correct any errors (bugs) and ensuring that all data are
processed properly.

Documentation. Orderly present of the complete purpose, function and history of a program.
Problem Identification

Usually, the user should be asked more and more questions to define the problem more precisely.

One of the best ways of problem definition is to formulate a problem using clear and concise
statements.

The statement(s) may usually start with “The problem is to …”. e.g. “The problem is to calculate the
wages of employees based on their weekly working hours.
Problem Analysis

For a large system, we can split into a series of sub-problems and tackle each of these separately.

Top-down approach.
i.
In case a particular sub-problem is still too difficult to tackle as a whole, we may further split it
into several sub-problems.
ii.
Stepwise Refinement. The process of breaking down a problem into its separated parts; these
parts may be further broken down into even smaller parts, and so on.
iii.
Example,
0.
Travel from the Hong Kong
University to the Chinese
University of Hong Kong
PROBLEM SOLVING AND PROGRAMMING
page 1
CH/S4CIT(A)/Oct. 2005.
1. Walk to
Sheung Wan
Station
2.1 Take the MTR
from Sheung Wan
Station to Central
Station
2. Take the MTR to
Kowloon Tong Station
2.2 Change
at Central
Station
3. Take a train to Chinese
University Station
2.3 Take the MTR
from Central
Station to Mongkok
Station
4. Walk to the
Chinese
University
2.4 Change
at Mongkok
Station
2.5 Take the MTR
from Mongkok
Station to Kowloon
Tong Station
figure 1
). It indicates that the whole process is described else where.
** Pre-defined process symbol (
Here is another example for stepwise refinement,
Find the volume V of a right pyramid whose base is an equilateral triangle of side s and whose height is
h.
i.
The result of refinement is shown in fig. 2
ii.
If any step still cannot be managed, it may be further refined. For example step 2.1 may be refined
as shown in fig. 3.
0
1
Input the side
s of the
triangular
base and the
height of the
pyramid
2.1
Calculate the
altitude a of
the triangular
base
Find the volume of
a volume of a
pyramid.
2
Calculate the
area A of the
triangular base
2.2
Substitute
the altitude a
and the base
s in the
formula for
finding the
area of a
triangle
3
Calculate the
volume V of
the pyramid
2.3
Perform
multiplication
and division to
obtain the
area of the
triangle
3.1
Derive the
formula for
finding the
volume of a
pyramid
3.1.1
Dissect of triangular
prism into three
pyramids
4
Output the
volume V of
the pyramid
3.2
Substitute
the area A
of the base
and the
height h in
the formula
3.1.2
Show that the three
pyramids are equal in
volume
3.3
Perform
multiplication
and division
3.1.3
Write down the
formula for finding the
volume of a pyramid
figure 2
2.1
2.1.1
Draw
the
altitude
Calculate the
altitude a of the
triangular base
2.1.2
Show that the
altitude bisects the
base of the triangle
2.1.3
Apply the
Pythagoras
theorem
figure 3
PROBLEM SOLVING AND PROGRAMMING
page 2
CH/S4CIT(A)/Oct. 2005.


Bottom-up approach.
i.
A solution is made up of existing component solutions.
ii.
Software developers will select those useful existing solution and combine them to form a whole
new solution.
Trial-and-error approach.
i.
There is no obvious way of systematically developing a solution.
ii.
A proposed solution is made and a trial of it is performed to see is it is successful. If not a the
proposed solution is modified and another trial is performed.
Algorithm Design
Algorithm

An algorithm is a procedure in problem solving. It involves a series of steps.

Computer can only solve problems step by step. So before a computer can operate on a problem, an
algorithm must be developed.
Pseudocode

Pseudocode is a sequence of English-like statements that represent an algorithm.

Features of pseudocode:

i.
There are no formal syntax rules and guidelines.
ii.
It is written in plain English.
iii.
It does not depend on the programming language which is to be used in program coding.
iv.
A pseudocode program can be easily encoded to a procedure-oriented language such as Pascal,. It
is easy to change the pseudocode if there is any logical error in the solution.
Here is an example using pseudocode applying the stepwise refinement to solve the payroll problem,
Initial algorithm
First level refinement
1 Get data
2 Calculate wages
3 Output total wages
1 Get data
1.1 Get number of hours worked
1.2 Get hourly rate
2 Calculate wages
2.1 Calculate regular wages
2.2 Calculate overtime allowance
2.3 Calculate total wages
3 Output total wages
PROBLEM SOLVING AND PROGRAMMING
page 3
CH/S4CIT(A)/Oct. 2005.
Second level refinement
1 Get data
1.1 Get number of hours worked
1.2 Get hourly rate
2 Calculate wages
2.1 Calculate regular wages
2.2 Calculate overtime allowance
2.2.1 Calculate number of overtime hours
2.2.2 if overtime hours > 0
then calculate allowance
else set allowance to 0
2.3 Calculate total wages
3 Output total wages

So the resulting pseudo program for the calculation of tax may be as follows:
INPUT h as the number of hours worked
INPUT r as the hourly rate
regular_wage <- h * r
overtime_hours <- h – 40
if overtime hours > 0
then allowance <- overtime_hour * r
else allowance <- 0
total_wage <- regular_wage + allowance
OUTPUT total_wage

Here is a more practical example.
A small supermarket sells 10 types of items: A to J which can be grouped into 3 different categories.
A, B, C and D belong to category 1. E, F, G, H and I belongs to category 2, and J belongs to category
3. When a customer checks out at the counter, a program in the cashier’s computer is executed to
calculate the total number of purchased items for a customer as well as the subtotals for the 3
categories. The algorithm in pseudocode of the computer program is shown below.
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Step 6:
Step 7:
Step 8:
Step 9:
Step 10:
Declare TOTALSUM, I, QTY to be integer variables, DITEM to be a character variable, COMPLETE to be a Boolean
variable, and SUBTOTAL to be an one-dimensional integer array of size 3.
Initialize the SUBTOTAL array to 0; and TOTALSUM to be 0; and COMPLETE to be FALSE.
As long as COMPLETE is FALSE, do steps 4 – 9 again.
Read an item type into PITEM.
If PITEM equals ‘Q’, then assign TRUE to COMPLETE; otherwise
Read in the quantity of the item type purchased into QTY.
Do Step 6 again when the input value of QTY is not between 1 and 10 inclusively.
Increase the corresponding element in SUBTOTAL by QTY according to the category of PITEM.
Increase the value of TOTALSUM by QTY.
Display TOTALSUM and the SUBTOTAL array.
PROBLEM SOLVING AND PROGRAMMING
page 4
CH/S4CIT(A)/Oct. 2005.
Flowchart

A pictorial representation of an algorithm.

Flowcharts use standard symbols (specially shaped boxes) to indicate the type of operating to be
performed.

Specific details are written in each box.

The boxes are connected by lines and arrows which indicate the ‘direction of flow’.
** Symbols and boxes
Terminal symbol.
This indicates the beginning
or the end of the whole
algorithm.
Process box.
The details of any form of
action which must be taken
are written inside.
Decision box.
Input or output box.
Here, the algorithm requires
that data is inputted or
outputted (e.g. the value of
a variable).
This is used to decide
which of two actions to
follow. A question or
condition is written inside
the box. Two lines leave
the box. One for the
answer ‘Yes’ or ‘True’; the
other for the answer ‘No’ or
‘False’.
Connector symbol.
It indicates the flow of a
branch out of the chart at
one point and back at
another.
*** Three Basic Control Structures
 Sequence. (fig. 4) one thing happens after the other.

Selection or branching decision (fig. 5). choice of actions made between ‘Yes’ and ‘No’
START
START
READ A, B, C
READ A, B, C
Yes
Is B=C ?
D = BC
Y = A/D
No
PRINT Y
PRINT ERROR
MESSAGE
DIVISOR
IS ZERO
D = BC
Y = A/D
STOP
Figure 4. A flowchart for evaluation
Y = a / (b – c)
PRINT Y
STOP
PROBLEM SOLVING AND PROGRAMMING
Figure 5. An amended flowchart for
evaluation y = a / (b – c)
page 5
CH/S4CIT(A)/Oct. 2005.

Iteration. A process which repeats the same series of steps until the limit is reached. Two ways to set
the limit,
i.
rogue value (see fig. 6). A number which, when it is reached in the program, causes the loop to be
quit.
ii.
counter (see fig. 7). A variable which keeps track of the number of the times of a loop performed
so as to terminate the iteration after the required number.
START
START
READ F
I=1
Yes
F = -999?
READ F
No
5
C = ─ (F ─ 32)
9
STOP
PRINT C
Figure 6. A flowchart showing the use of a
Rogue value to terminate looping
(the shaded part shows the use of
of the rogue)
5
C = ─ (F ─ 32)
9
PRINT C
I=I+1
I  50?
STOP
Figrue 7. A flowchart showing the
use of a counter to terminate
looping (the shaded part shows the
use of the counter)
Solution Development

We use a programming language or a suitable software developing tool to communicate with the
computer.

If the algorithm developed in the previous stage is sound and the representation of the algorithm is
complete, the process in coding is simple and straight forward.
PROBLEM SOLVING AND PROGRAMMING
page 6
CH/S4CIT(A)/Oct. 2005.
Program Debugging and Testing
Program Debugging

There are three main types of errors to be debugged.

Syntax Errors


i.
Every language has its own rules of grammar, syntax.
ii.
Syntax errors occur when the program statement violates one or more rules of syntax.
iii.
e.g.
a = a+7;
(* use '=' instead of ':=' *);
int1 := num1 + num2;
(* It will be wrong if num1 or num2
are declared to be real type but int1
to be integer types *)
Run-time Errors
i.
When a program is run and producing results that the computer cannot handle and cannot continue
execution, run-time occur.
ii.
e.g. division by zero, accessing file not on disk, writing to a write-protected disk.
Logical Errors
i.
These are errors made in the process of devising the algorithm or in translating the algorithm into a
computer language.
ii.
Unlike the other two types of errors, the computer cannot detect and provide clues for correcting
logical chosen test data with unknown results.
iii.
Another way is to “trace” program, using the automatic trace feature in the system using.
Program Testing

Purpose. To guarantee that the program produces correct and meaningful results under all
circumstances.

The testing should include the following items,
i.
Typical valid data.
ii.
Boundary valid data.
iii.
Special and unusual valid data, which are exceptional cases and need special processing.
iv.
Invalid, incomplete or meaningless data, which are used to test the error handling abilities of the
program.
PROBLEM SOLVING AND PROGRAMMING
page 7
CH/S4CIT(A)/Oct. 2005.
Program Documentation
Program Documentation


The need of documentation
i.
To help memory.
ii.
To inform others, i.e. to communicate with other people who maintain the program.
iii.
Full details, especially details of the program’s relation to other program.
Guidelines for program documentation
i.
Title page. General information such as, the program’s title, the programmer’s name and the date.
ii.
Program description / specification. It should be,
a.
not using technical terms (jargon)
b. a detail specification of the task
c.
a guideline to user about the work done by the program
iii.
Algorithm / flowchart
iv.
Variable dictionary. The following table is an example of variable dictionary,
v.
Variable
A
B
C
D
X1, X2
Program listing.
vi.
Description
Coefficient of x in the quadratic equation
Coefficient of x
The constant term
The discriminant
The two roots of the equation
2
Test data and sample output.
a.
Appropriate test data should be prepared for different situations.
b. The expected results are determined before the program is run.
** The six phases of problem solving are not necessarily performed in the order we have described. It also should be
reminded that the phases are in a cycle.
PROBLEM SOLVING AND PROGRAMMING
page 8
Download