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

CS11AlgorithmDesign&ProblemSloving

Uploaded by

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

CS11AlgorithmDesign&ProblemSloving

Uploaded by

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

02.

11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

Learning objectives
0. show understanding that an algorithm is a solution to a problem expressed as a sequence of
defined steps
1. use suitable identifiers for the representation of data used by a problem and summarise
identifiers using an identifier table
2. show understanding that many algorithms are expressed using the four basic constructs of
assignment, sequence, selection and repetition
3. show understanding that simple algorithms consist of input, process, output at various stages
4. document a simple algorithm using: structured English, pseudocode, program flowchart
5. derive pseudocode or a program flowchart from a structured English description of a problem
6. derive pseudocode from a given program flowchart
7. show an appreciation of why logic statements are used to define parts of an algorithm solution
8. use logic statements to define parts of an algorithm solution use the technical terms associated
with arrays including upper and lower bound
9. select a suitable data structure (1D or 2D array) to use for a given task
10. write algorithms to process array data including sorting using a bubble sort and searching using
a linear search.

2.1.1 Algorithms
0. show understanding that an algorithm is a solution to a problem expressed as a sequence of
defined steps
1. use suitable identifier names for the representation of data used by a problem
- summarise identifier names using an identifier table
2. show understanding that many algorithms are expressed using the four basic constructs of
assignment, sequence, selection and repetition
3. show understanding that simple algorithms consist of input, process, output at various
stages
4. document a simple algorithm using:
- structured English
Part 2

- pseudocode (on the examination paper, any given pseudocode will be presented using the
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

Courier New font)


- program flowchart
Fundamentals Problem-Solving and Programing Skills

5. derive pseudocode or a program flowchart from a structured English description of a problem


6. derive pseudocode from a given program flowchart or vice versa
7. use the process of stepwise refinement to express an algorithm to a level of detail from which
the task may be programmed
8. decompose a problem into sub-tasks leading to the concept of a program module (procedure/
function)
9. show an appreciation of why logic statements are used to define parts of an algorithm solution
10. use logic statements to define parts of an algorithm solution

14
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

11.01 What is an algorithm? P126

An algorithm is a sequence of steps designed to perform some task which:


• has been done manually
• has been done manually with the aid of a device, such as a calculator
• has been done using a computer program, but for which we are now seeking a better computer-
based solution.
The ‘sequence of steps’ could be implemented as a computer program. The program will be designed
to solve a problem and the computer system is used to provide a solution. Consider a variety of
applications which are done by a computer program:
• the printout of utility bills
• the issuing of reminders for utility bills which have not been paid on the due date
• the control or simulation of an industrial process
• stock control and management order processing and tracking
• accounting
• resource management.
For all of these common data-processing applications there is a clear problem to be solved for which
the computer system is used to provide a solution.
What are the underlying algorithms? The algorithms to solve the problem will be designed from a
detailed knowledge of the operation of the application. For example:
• We know that bills are sent out every three months.
• a payment reminder is sent when the payment becomes 30 days overdue.
Consider the task of repairing a puncture on a bicycle. A computer solution will not be used to solve
the problem but the underlying steps for the task can be called an algorithm. To complete the task,
we work through a sequence of steps:
0 Check all tools and materials are available
1 IF 'no' then delay the task
2 IF 'yes' then
Part 2

2.1 Remove the wheel


2.2 Remove the inner-tube
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

3 Check - is there major damage?


3.1 IF 'yes' then buy a new inner tube
Fundamentals Problem-Solving and Programing Skills

3.2 IF 'No' then


3.2.1 Inflate the tube to locate the leak
3.2.2 Apply glue and a patch
3.2.3 Inflate the tube to re-test 5
4 IF 'still leaking' then
4.1 Purchase new inner tube
5 Re-assemble.

15
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

11.02 Expressing Algorithm P128

Structured English
Structured English provides a more formal way of documenting the stages of the algorithm:
PROCESS RepairPuncture
Start: JobDone ← "NO"
IF 'a1l tools are not available'
THEN
Delay the task
GOTO End
ELSE
Remove the wheel
Remove the inner-tube
ENDIF
IF 'there is major damage'
THEN
Buy a new inner tube
GOTO Delay
ELSE
Inflate the tube to locate the leak
Apply glue and a patch
Inflate the tube to re-test
ENDIF
IF 'still leaking'
THEN
Purchase new inner tube
GOTO Delay
ELSE
Part 2

Re-assemble
JobDone ← "YES"
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

ENDIF
Delay: Purchase new inner-tube
Fundamentals Problem-Solving and Programing Skills

IF JobDone ← "NO"
THEN
GOTO Start
ENDIF
End:
ENDPROCESS
In the structured English:
• Three labels (Start, Delay and End) have been used to mark particular steps in the
algorithm.
• When a decision has to be made the keywords IF - THEN - ELSE - ENDIF have been used.
• Indentation and the use of blank lines (‘whitespace’) has been used to indicate which steps
belong together.
• The complete process has been given an identifier name, RepairPuncture.

16
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

• The process is marked with clear PROCESS and ENDPROCESS statements.


• The algorithm has used a GOTO keyword to jump to a particular step in the algorithm. For a
high-level language, the use of GOTO is considered bad programming practice as it encourages
'spaghetti-like' algorithm design. For assembly language, a GOTO structure is used: the JME
<address> instruction is the equivalent of a pseudocode GOTO statement.

Identifier names
We have used several identifier names:
• for the whole process - RepairPuncture
• to indicate whether or not the process has been completed - JobDone
• to label steps - Start, Delay and End.

Four basic constructs


All problems which can be documented as a sequence of steps can be shown using the four basic
constructs: assignment, sequence, selection and repetition(iteration).

Sequence
Traditional high-level programming languages are designed for problems which can be designed as
a sequence of steps. It is a feature of a text editor or IDE for program development that the lines of
code can be numbered to show the sequence.

Assignment
In our algorithm, JobDone is initially assigned the value ‘NO’ and later assigned a value of
‘YES’.
Note that the symbol ← has been used to mean ‘the value on the right of the statement is assigned to
the identifier on the left’.

Selection
In our algorithm, a question is asked: ‘are all the tools available?’
This is called a condition. The result of the condition is always either TRUE or FALSE. The
Part 2

algorithm carries out a different set of steps for the TRUE and FALSE results.

Iteration
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

Iteration will occur in an algorithm design when a block of steps is repeated. This is done in a
Fundamentals Problem-Solving and Programing Skills

program with the use of a loop structure

Stepwise refinement
In the design, one of the steps is stated as Re-assemble.
This may not convey to a reader of the design precisely what this involves, so the step could be
expanded; that is, we could use stepwise refinement.
Re-assemble consists of:
Replace the inner tube
Replace the tyre
Replace the wheel
Inf1ate the inner tube

17
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

Program flowcharts ‘RepairPuncture’ Flowchart


A flowchart can be used as an alternative to a
structured-English description of the algorithm
design.
A program flowchart uses the following symbols:
• start and Stop

Start

• assignment or action

Action

• decision box

Conditi Yes
on?

No

• flow lines to show sequence

• input and output

Input

Here is a flowchart for the RepairPuncture


problem. It does not require any input from the user
and did not produce outputs. Most tasks - and so,
most programs - will perform both input and output.
Part 2

Note the following features of the flowchart:


• Every flow-line has an arrow
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

• The main ‘flow’ of the flowchart should be


Fundamentals Problem-Solving and Programing Skills

from top to bottom.


• There is only one start point and one end point.
• The left-hand vertical flow-line is effectively
causing iteration.
• The decision boxes are performing selection.
Progress check:
0. Name the four basic constructs used to
design and code a high-level language
program.
1. What term describes the breaking down of
a step in an algorithm into a sequence of
smaller steps?

18
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

Input - Processing - Output


A garage buys in used cars and aims to sell the vehicles at a profit. The garage has to decide on the
selling price. The garage will record data for:
• the price paid
• the date the vehicle was first registered (i.e. when it was new)
• the mileage.
A program is to be written to calculate the selling price. The design for this task has three clearly
defined stages:
• The input is the three data items about the car.
• The processing will calculate the selling price as follows:
- The price will drop by 5% for every month in age.
- The calculated price is called the Provisional Sell Price.
- An adjustment may be made to this figure based on the mileage of the vehicle.
- Normal mileage is 1000 km for every one month. This normal mileage is calculated for
the vehicle. If the actual mileage is less than this figure, the provisional Sell Price is
increased by 5%. This Provisional Sell Price is then set to be the advertised price, called
‘Sell Price’.
• The output from the program is the Sell Price and Profit.

An identifier table
The task requires the input, processing and output of data items. We shall use the identifier names
summarised in this Identifier Table for the Garage Application:
Identifier name Description
PricePaid Original price paid
RegDate Registration date
Mileage Car mileage when purchased
NormalMileage The expected car mileage based on the age of the car
ProvSellPrice The calculated selling price
Part 2

SellPrice The adjusted selling price


Profit Sell Price - Price Paid
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

Later, when we attempt to write pseudocode or program code for the problem, the programmer will
Fundamentals Problem-Solving and Programing Skills

need to specify the type of data which will be stored by e.ach identifier.

2.1.2 Structure charts


0. use a structure chart to express the parameters passed between the various modules/procedures/
functions which are part of the algorithm design
1. describe the purpose of a structure chart
2. construct a structure chart for a given problem
3. derive equivalent pseudocode from a structure chart

12.03 Structure charts P167


A first description of the problem could be in structured English:
0. INPUT the price paid, registration date, mileage
1. CALCULATE Selling price
2. CALCULATE Profit
3. OUTPUT Selling price, Profit

19
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

These processes will have data inputs, called parameters We shall make up an identifier name for
each process and use the identifiers in the table (page 19) for the parameters.
This gives a high-level description of the problem:
InputCarData(PricePaid, RegDate, Mileage)
CalculateSellingPrice(RegDate, PricePaid, Mileage)
OutputSellPrice(SellPrice, Profit)
These stages are designed as 'modules'. Later they will be implemented with program code as
'procedures'.
The breaking down of the problem into modules and the passing of data values into each module
can be shown using a structure chart hereunder:

CarPriceCalculator

RegDate
PricePaid
Mileage

InputCarData CalculateSellingPrice OutputSellPrice

2.1.3 Corrective maintenance


4. perform white-box testing by:
a) selecting suitable data
b) using a trace table
5. identify any error(s) in the algorithm by using the completed trace table
6. amend the algorithm if required
Part 2

15.06 Corrective maintenance P243


·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

The name implies that something is wrong! All program code needs to be extensively tested. This
Fundamentals Problem-Solving and Programing Skills

will involve:
• choosing appropriate test data
• using a trace table to check carefully how the data values change as each step of the program
is executed.
Before we can complete a trace table, we need to formalise the algorithm required. We shall write
this using pseudocode with the identifier names from the table (page 19). (The // symbol denotes a
‘comment’)
00 // InputCarData module
01 INPUT Pricepaid
02 INPUT ReqDate
04 INPUT Mileage
05 // CalculateSelling Price module
06 Months ← TodaysDate - RegDate

20
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

07 Norma1Mi1eage ← Months * 1000


08 ProvSellPrice ← PricePaid * (100 - 5 * Months) / 100
09 IF Mileage < NormalMileage
10 THEN
11 SellPrice ← ProvSellPrice * 105 / 100
12 ELSE
13 SellPrice ← ProvSellPrice
14 ENDIF
15 Profit ← PricePaid - SellPrice
16 // OutputSellprice module
17 OUTPUT SellPrice, Profit
• The lines of pseudocode have been numbered (for easy reference only).
• The stages in the pseudocode follow exactly the three stages in the structure chart.
• The pseudocode has used a number of ‘keywords’:
- INPUT
- OUTPUT
- IF - THEN - ELSE - ENDIF
• The symbol ← has been used for ‘assignment’: Line 6 is read as ' The Months value is calculated
by subtracting the RegDate value from the TodaysDate value.

Completing the trace table


We now have everything we need to complete a trace of the algorithm for selected data.
What test data would be appropriate for our car price calculator program? The data items are the
original price paid for the car, the mileage and the registration date.
Take today's date as September 2018.
Case 1: A car registered in July 2017 is purchased for $5000. It has done 12 000 miles. The values
of the data items shall be:
PricePaid RegDate Mileage Months NormalMileage ProvSellPrice SellPrice
Part 2

07/2017

Case 2: A car registered in November 2017 is purchased for $5000. It has done 8000 miles. These
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

figures mean the vehicles has the ‘low mileage’ price adjustment. As the provisional selling price
has changed, this new value can be shown on the next row:
Fundamentals Problem-Solving and Programing Skills

PricePaid RegDate Mileage Months NormalMileage ProvSellPrice SellPrice

In any trace table, as more values are calculated the numbers will occupy more rows.
Progress check: A program calculates the interest earned on $100. The value of the investment
increases by 20% each year. Stop the process when the amount reaches $150. Draw a trace table
to complete the execution of this algorithm, adding blank rows as required, and draw a program
flowchart for this calculator algorithm:
YearNumber Amount OUTPUT

21
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

00 YearNumber ← 1
01 Amount ← 100
02 Amount ← Amount * 1.20
03 IF Amount >= 150
04 THEN
05 OUTPUT YearNumber
06 STOP
07 ELSE
08 YearNumber ← YearNumber + 1
09 GOTO Step 03
10 ENDIF
2.1.3 Adaptive maintenance
7. make amendments to an algorithm and data structure in response to specification changes
8. analyse an existing program and make amendments to enhance functionality

15.07 Adaptive maintenance P244

An existing program may need to be 'adapted' or changed. This could be for a variety of reasons.
The most likely is that the user now has slightly different requirements and so the specification of
the program needs to be changed. If the program design needs to be changed, so will the program
code.
For our car purchase program, the garage might decide the following:
• Car users are now traveling on average a greater distance in a month. It's now on average 200
miles per month (not 1000).
• Cars seem to be holding their price better: We need to calculate that the value goes down by
only 3% per month (not 5%).
These changes to the specification, and possible other specification changes, will require that the
program code is amended and re-tested.
Progress check: A program is to developed to calculate the tax paid by employees each month.
Part 2

The program has been written and successfully used for a year. Why might adaptive maintenance
be required at some future date?
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING
Fundamentals Problem-Solving and Programing Skills

Chapter Summary

⃞ An algorithm is a solution to a problem expressed as a sequence of defined steps. The


algorithm may involve logic statements.
⃞ In programming, identifier names are used for the various data items used in the problem
and are documented in an identifier table showing the identifier name, data type and a
description.
⃞ Many algorithms use the four basic constructs: assignment, sequence, selection and
repetition.
⃞ Some steps may be expanded into more detail. This processing is called stepwise refinement.
Individual steps are often coded in the program using procedures and functions.
⃞ Many problems consist of the three stages: input, processing and output.
⃞ An algorithm can be expressed in structured English, pseudocode or a program flowchart.

22
02.11 Algorithm Design and Problem-Solving Flair · Discipline · Academic Rigour

⃞ A structure chart is used to document the parameters passed in and out of modules which
make up the program design.
⃞ Corrective maintenance is carried out using white box testing. This involves drawing up
suitable test cases with appropriate data and then -using a trace table-tracing various routes
through the code.
⃞ Adaptive maintenance takes place when the user makes a change to the program
specification.

Exam-style questions

0. Ali uses a sequential file of records to store the user IDs and encrypted passwords. When a user
types in their User ID, the program calls a function, FindPassword, with parameter
ThisUseriD. The function searches each record in the file for ThisUseriD and retums the
encrypted password. If ThisUseriD is not stored in the file, the function returns an error
code. Complete the pseudocode:.
FUNCTION FindPassword (ThisUseriD: STRING) RETURNS . . . . . . . . .

DECLARE Found: BOOLEAN

OPENFILE FOR INPUT // for reading

Found ← FALSE

WHILE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

FILEREAD next record

IF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

THEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ENDIF
Part 2

ENDWHILE
·
CHAPTER 11 ALGORITHM DESIGN AND PROBLEM-SOLVING

IF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

THEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fundamentals Problem-Solving and Programing Skills

ELSe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ENDIF

CLOSEFILE “PASSWORDS”

ENDFUNCTION [8]
Cambridge International AS and A Level Computing 9691 Paper 23, Q2b, Nov 2014

23

You might also like