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

G10 Chapter 7 - Algorithm Design and Problem Solving

Uploaded by

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

G10 Chapter 7 - Algorithm Design and Problem Solving

Uploaded by

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

Algorithm Design and

Problem Solving
Chapter 7
Analysis
Before any problem can be solved, it needs to be clearly defined and set out so anyone
working on the solution understands what is needed. This is called the ‘requirements
specification’ for the program. The analysis stage uses abstraction and decomposition
tools to identify exactly what is required from the program.

Abstraction keeps the key elements required for the solution to the
problem and discards any unnecessary details and information that is
not required.

Decomposition breaks down a complex problem into smaller parts,


which can then be subdivided into even smaller parts, that can be
solved easily.
Analysis
Before any problem can be solved, it needs to be clearly defined and set out so anyone
working on the solution understands what is needed. This is called the ‘requirements
specification’ for the program. The analysis stage uses abstraction and decomposition
tools to identify exactly what is required from the program.

For example, a map only shows what is required for travelling from one
place to another. Different methods of transport will require different
types of map.

Any daily task can be divided into several parts. For example, getting
dressed:
» Select items to wear
» Remove any clothes being worn
» Put selected items on in order.
Abstraction
● Abstraction is the concept of simplifying complex systems by
hiding the intricate details and exposing only the essential
features.
● It allows developers to focus on high-level functionalities without
needing to understand the underlying implementation.
● By using abstraction, code becomes easier to manage, reuse, and
maintain, facilitating clearer communication and better design.
Abstraction
Abstraction
Design
The program specification from the analysis stage is used to show to how the program
should be developed. When the design stage is complete, the programmer should
know what is to be done, i.e. all the tasks that need to be completed, how each task is
to be performed and how the tasks work together.

This can be formally documented using structure charts, flowcharts and pseudocode
Coding and iterative testing
The program or set of programs is developed.

Each module of the program is written using a suitable programming language and
then tested to see if it works.

Iterative testing means that modular tests are conducted, code amended, and tests
repeated until the module performs as required.

"Iterative" refers to a process that is repeated multiple times, often with the aim of
refining or improving the outcome with each cycle.
Testing
The completed program or set of programs is run many times with different sets of
test data.

This ensures that all the tasks completed work together as specified in the program
design.
Computer systems, sub-systems
and decomposition
A computer system is made up of software, data, hardware, communications and
people; each computer system can be divided up into a set of sub-systems. Each
sub-system can be further divided into sub-systems and so on until each
sub-system just performs a single action.

Computer systems can be very large, very small or any size in between; most people
interact with many different computer systems during their daily life without realising it.

For example, when you wake up in the morning, you might use an app on your
smartphone for your alarm, then you might check the weather forecast on your
computer before driving to work. The alarm program is a very small computer system
but when you check the weather forecast, you obtain the information you need from
one of the largest computer systems in the world.
The computer system and its
sub-systems
Top-down design is the decomposition of a computer system into a set of sub-
systems, then breaking each sub-system down into a set of smaller sub-systems,
until each sub-system just performs a single action.

This is an effective way of designing a computer system to provide a solution to a


problem, since each part of the problem is broken down into smaller more manageable
problems. The process of breaking down into smaller sub-systems is called stepwise
refinement.

This structured approach works for the development of both large and small computer
systems. When larger computer systems are being developed this means that several
programmers can work independently to develop and test different sub-systems for the
same system at the same time. This reduces the development and testing time.
Decomposing a problem
Any problem that uses a computer system for its solution needs to be decomposed into
its component parts. The component parts of any computer system are:

» inputs – the data used by the system that needs to be entered while the system is
active

» processes – the tasks that need to be performed using the input data and any other
previously stored data

» outputs – information that needs to be displayed or printed for the users of the system

» storage – data that needs to be stored in files on an appropriate medium for use in
the future.
Decomposing a problem: an
alarm app
For example, the alarm app can be decomposed into:

» inputs – time to set the alarm, remove a previously set alarm time, switch an alarm off,
press snooze button

» processes – continuously check if the current time matches an alarm time that has
been set, storage and removal of alarm times, management of snooze

» outputs – continuous sound/tune (at alarm time or after snooze time expired)

» storage – time(s) for alarms set.


Methods used to design and
construct a solution to a problem
Solutions to problems need to be designed and developed rigorously. The use of formal
methods enables the process to be clearly shown for others to understand the
proposed solution.

The following methods need to be used by IGCSE Computer Science students:

» structure diagrams

» flowcharts

» pseudocode.
Structure diagram
Structure diagrams can be used to show top-down design in a diagrammatic form.
Structure diagrams are hierarchical, showing how a computer system solution can be
divided into sub-systems with each level giving a more detailed breakdown.

If necessary, each sub-system can be further divided.


Structure diagram: alarm for
smartphone
Consider the alarm app computer system for a smart phone; this could be divided into
three sub-systems, setting the alarm, checking for the alarm time, sounding the alarm.
These sub-systems could then be further sub-divided; a structure diagram makes the
process clearer.
Flowcharts
A flowchart shows
diagrammatically the steps
required to complete a task and
the order that they are to be
performed.

These steps, together with the


order, are called an algorithm.
Flowcharts are an effective way to
communicate how the algorithm
that makes up a system or
sub-system works.
Flowcharts symbol
Begin/End

Terminator flowchart symbols are


used at the beginning and end of
each flowchart.
Flowcharts symbol
Process

Process flowchart symbols are used to show actions, for example, when values are
assigned to variables.

If a process has been defined elsewhere then the name of that process is shown.
Flowcharts symbol
Input and Output

The same flowchart symbol is used to show the input of data and output of
information.
Flowcharts symbol
Decision

Decision flowchart symbols are used to decide which action is to be taken next; these
can be used for selection and repetition/iteration. There are always two outputs from a
decision flowchart symbol.
Flowcharts symbol
Flow lines

Flowchart flow lines use arrows to show the direction of flow, which is usually, but not
always, top to bottom and left to right.
Flowcharts
symbol
Convert the following steps into
flowchart
Step 1: Start

Step 2: get l,b values

Step 3: Calculate A=l*b

Step 4: Display A

Step 5: Stop

an algorithm to find area of a


rectangle
Convert the following steps into
flowchart
Step 1: Start

Step 2: get r value

Step 3: Calculate A=3.14*r*r

Step 4: Calculate C=2*3.14*r

Step 5: Display A,C

Step 6: Stop

an algorithm for Calculating area


and circumference of circle
Convert the following steps into
flowchart
Step 1: Start

Step 2: get P, n, r value

Step 3:Calculate SI=(p*n*r)/100

Step 4: Display S

Step 5: Stop

an algorithm for Calculating


simple interest
Convert the following steps into
flowchart
Step 1: Start

Step 2: get l,b values

Step 3: Calculate A=l*b

Step 4: Display A

Step 5: Stop

an algorithm to find area of a


rectangle
Convert the following steps into
flowchart
Step 1: Start

Step 2: get r value

Step 3: Calculate A=3.14*r*r

Step 4: Calculate C=2.3.14*r

Step 5: Display A,C

Step 6: Stop

an algorithm for Calculating area


and circumference of circle
Convert the following steps into
flowchart
Step 1: Start

Step 2: get P, n, r value

Step 3:Calculate SI=(p*n*r)/100

Step 4: Display S

Step 5: Stop

an algorithm for Calculating


simple interest
Convert the following steps into
Python code
length = float(input("Enter the
Step 1: Start length (l): "))

Step 2: get l,b values breadth = float(input("Enter the


breadth (b): "))
Step 3: Calculate A=l*b
area = length * breadth
Step 4: Display A
print(f"The area of the rectangle
Step 5: Stop is: {area}")

an algorithm to find area of a


rectangle
Convert the following steps into
Python code
radius = float(input("Enter the
Step 1: Start radius (r): "))

Step 2: get r value area = 3.14 * radius * radius

Step 3: Calculate A=3.14*r*r circumference = 2 * 3.14 * radius

Step 4: Calculate C=2.3.14*r print(f"The area of the circle is:


{area}")
Step 5: Display A,C
print(f"The circumference of the
Step 6: Stop circle is: {circumference}")
an algorithm for Calculating area
and circumference of circle
Convert the following steps into
python code principal = float(input("Enter the
principal amount (P): "))

Step 1: Start time = float(input("Enter the time


period in years (n): "))
Step 2: get P, n, r value
rate = float(input("Enter the rate of
Step 3:Calculate SI=(p*n*r)/100 interest (r): "))

Step 4: Display S simple_interest = (principal * time *


rate) / 100
Step 5: Stop
print(f"The simple interest (SI) is:
an algorithm for Calculating {simple_interest}")
simple interest
Pseudocode
Pseudocode describes what the algorithm does by using English key words that are
very similar to those used in a high-level programming language.

Data items to be processed by the algorithm are given meaningful names in the same
way that variables and constants are in a high-level programming language.

However, pseudocode is not bound by the strict syntax rules of a programming


language. It does what its name says, it pretends to be programming code!

To ensure that pseudocode is easily understandable by others it is useful to be


consistent in the way that it is written.
Pseudocode rules
● a non-proportional font is used throughout
● all keywords (words used to describe a specific action e.g. INPUT)
are written in capital letters
● all names given to data items and subroutines start with a capital
letter
● where conditional and loop statements are used, repeated or
selected statements are indented by two spaces.
The pseudocode for an
assignment statement
A value is assigned to an item/variable using the ̈ operator.

The variable on the left of the ̈ is assigned the value of the expression on the right. The
expression on the right can be a single value or several values combined with any of the
following mathematical operators.
The pseudocode for an
assignment statement
The pseudocode for conditional
statements
When different actions are performed by an algorithm according to the values of the
variables, conditional statements can be used to decide which action should be taken.

There are two types of conditional statement:

1. A condition that can be true or false such as: IF ... THEN ... ELSE ... ENDIF
The pseudocode for conditional statements
The pseudocode for conditional
statements
When different actions are performed by an algorithm according to the values of the
variables, conditional statements can be used to decide which action should be taken.

There are two types of conditional statement:

2. a choice between several different values, such as: CASE OF ... OTHERWISE ... ENDCASE
The pseudocode for conditional statements
The pseudocode for conditional statements
The pseudocode for iteration
When some actions performed as part of an algorithm need repeating this is called
iteration. Loop structures are used to perform the iteration.

Pseudocode includes these three different types of loop structure:

● A set number of repetitions: FOR… TO… NEXT


● A repetition, where the number of repeats is not known, that is completed at least
once: REPEAT… UNTIL
● A repetition, where the number of repeats is not known, that may never be
completed: WHILE… DO… ENDWHILE
All types of loops can all perform the same
task, for example displaying ten stars:
FOR… TO… NEXT loop
● A variable is set up, with a start value and an end value, this variable is incremented
in steps of one until the end value is reached and the iteration finishes.
● The variable can be used within the loop so long as its value is not changed.
● This type of loop is very useful for reading values into lists with a known length.
REPEAT… UNTIL loop
● This loop structure is used when the number of repetitions/iterations is not known
and the actions are repeated UNTIL a given condition becomes true.
● The actions in this loop are always completed at least once.
● This is a post-condition loop as the test for exiting the loop is at the end of the loop.
WHILE… DO… ENDWHILE loop
● This loop structure is used when the number of repetitions/iterations is not known
and the actions are only repeated WHILE a given condition is true.
● If the WHILE condition is untrue then the actions in this loop are never performed.
● This is a pre-condition loop as the test for exiting the loop is at the beginning of the
loop.
The pseudocode for input and output
statements
● INPUT and OUTPUT are used for the entry of data and display of information.
Sometimes READ can be used instead of INPUT but this is usually used for reading
from files – see Chapter 8. Also, PRINT can be used instead of OUTPUT if a hard copy
is required.
● INPUT is used for data entry; it is usually followed by a variable where the data input
is stored, for example:
The pseudocode for input and output
statements
OUTPUT is used to display information either on a screen or printed on paper; it is
usually followed by a single value that is a string or a variable, or a list of values
separated by commas, for example:
Validation
Validation is the automated checking by a program that data is reasonable before it is
accepted into a computer system.
When data is validated by a computer system, if the data is rejected a message should
be output explaining why the data was rejected and another opportunity given to enter
the data.
There are many different types of validation checks including:
» range checks
» length checks
» type checks
» presence checks
» format checks
» check digits.
Range check
Length check
Length check
Type check
Presence check
Format check & check digit
Verification
Verification - double entry
Verification - screen/visual check
Test data
A set of test data is all the items of data required to work through a solution.

In order to determine whether a solution is working as it should, it needs to be tested.


Usually before a whole system is tested each sub-system is tested separately.

Algorithms written in pseudocode or as flowcharts can be tested by a person working


through them using any data that is required and seeing what the result is. Computer
programs can be tested by running them on a computer using any data that is required
and seeing what result is output.

However, in order to test a solution thoroughly it may need to be worked through several
times with different sets of test data.
Test data - normal data
In order to prove that program or algorithm solutions do what they are supposed to do, a
set of test data should be used that the program would normally be expected to work
with, together with the result(s) that are expected from that data.

The type of test data used to do this is called normal data. Normal data should be used
to work through the solution to find the actual result(s) and see if they are the same as
the expected result(s).

For example, consider an algorithm that records the percentage marks, entered in whole
numbers, from ten end-of-term examinations for a pupil, and then finds the average
mark.

A set of normal test data for this purpose could be:

Normal test data: 50, 50, 50, 50, 50, 50 50, 50, 50, 50

Expected result: 50
Test data - abnormal/erroneous data
Solutions also need to be tested to prove that they do not do what they are supposed not
to do. In order to do this, test data should be chosen that would be rejected by the
solution as not suitable, if the solution is working properly.

This type of test data is called abnormal test data. (It is also sometimes called
erroneous test data.)

For example, erroneous/abnormal data for our algorithm to find the average percentage
marks from ten end of term examinations could be:

Erroneous/abnormal data: -12, eleven

Expected results: both of these values should be rejected


Test data - extreme data
When testing algorithms with numerical values, sometimes only a given range of values
should be allowed. For example, percentage marks should only be in the range 0 to 100.
Our algorithm above should be tested with extreme data. Extreme data are the largest
and smallest values that normal data can take. In this case:
Extreme data: 0, 100
Expected results: these values should be accepted
There is another type of test data called boundary data. This is used to establish where
the largest and smallest values occur. At each boundary two values are required: one
value is accepted and the other value is rejected.
For example, for percentage marks in the range 0 to 100, the algorithm should be tested
with the following boundary data:
Boundary data for 0 is: -1, 0
Expected results: -1 is rejected, 0 is accepted
The purpose of an algorithm
● An algorithm sets out the steps to complete a given task.

● This is usually shown as a flowchart or pseudocode, so that the purpose of the task
and the processes needed to complete it are clear to those who study it.

● An algorithm defines the steps necessary to produce the desired outcome, and the
computer follows the instructions to complete the task efficiently and accurately.
The purpose of an algorithm
Standard methods of solution
The ability to repeat existing methods is very important in the design of algorithms; when an
algorithm is turned into a program the same methods may be repeated many thousands of
times.
You need to be able to use and understand these standard methods used in algorithms:

➔ Totalling

➔ Counting

➔ Finding maximum, minimum, and average (mean) values

➔ Searching using a linear search

➔ Sorting using a bubble sort.

All the standard methods of solution are shown as pseudocode algorithms and will be used to
practise program writing in the next chapter.
Totalling
Counting
Counting
Maximum, minimum and average
Maximum, minimum and average
Maximum, minimum and average
Linear search
A search is used to check if a value is stored in a list, performed by systematically
working through the items in the list.

This is called a linear search, which inspects each item in a list in turn to see if the
item matches the value searched for.
Linear search
Linear search
Linear search
Linear Search is a simple searching algorithm that checks each element of a list or
array sequentially to find a target value. The process continues until the target
element is found or the entire list is traversed.

Example 1:

Problem: Find the number 7 in the list [1, 2, 3, 4, 5, 6, 7, 8, 9].

Steps:

● Start at the first element 1, compare it with 7. No match.


● Move to the next element 2, compare it with 7. No match.
● Continue this process until you reach 7.
● When you reach 7, return the index of 7, which is 6 (0-based index).

Result:The target number 7 is found at index 6.


Linear search
Example 2:

Problem: Find the number 10 in the list [1, 2, 3, 4, 5, 6, 7, 8, 9].

Steps:

● Start at the first element 1, compare it with 10. No match.


● Move to the next element 2, compare it with 10. No match.
● Continue checking until you reach the last element 9.
● Since there is no match, return -1 indicating that 10 is not in the list.

Result:

The target number 10 is not found, so the result is -1.


Linear search
Bubble Sort
Lists can be more useful if the items are sorted in a meaningful order. For example,
names could be sorted in alphabetical order, or temperatures could be sorted in
ascending or descending order.

This method of sorting is called a bubble sort. Each element is compared with the next
element and swapped if the elements are in the wrong order, starting from the first
element and finishing with next-to-last element. Once it reaches the end of the list,
we can be sure that the last element is now in the correct place.

However, other items in the list may still be out of order. Each element in the list is
compared again apart from the last one because we know the final element is in the
correct place. This continues to repeat until there is only one element left to check or no
swaps are made.
Bubble Sort
Bubble Sort
Bubble Sort is a simple comparison-based sorting algorithm. It works by repeatedly
stepping through the list, comparing adjacent elements, and swapping them if they
are in the wrong order. This process is repeated until the list is sorted.

The algorithm gets its name because smaller elements "bubble" to the top (beginning)
of the list, and larger elements "sink" to the bottom (end) during each pass through the
list.
Bubble Sort
Advantages of Bubble Sort:

● Simple to implement and understand.


● Stable sort (it preserves the relative order of equal elements).
Disadvantages of Bubble Sort:

● Inefficient for large datasets due to its O(n²) time complexity.

(O(n²) means the running time grows quadratically with the input size,
and for large datasets, it can become very slow.)

● It's generally slower than more advanced algorithms like quicksort or


merge sort.
Bubble Sort
Example:

Problem: Sort the list [5, 2, 9, 1, 5, 6] using Bubble Sort.

Steps:

● Pass 1:
○ Compare 5 and 2 → swap them → [2, 5, 9, 1, 5, 6]
○ Compare 5 and 9 → no swap → [2, 5, 9, 1, 5, 6]
○ Compare 9 and 1 → swap them → [2, 5, 1, 9, 5, 6]
○ Compare 9 and 5 → swap them → [2, 5, 1, 5, 9, 6]
○ Compare 9 and 6 → swap them → [2, 5, 1, 5, 6, 9]
● After the first pass, the largest number 9 is at the end.
Bubble Sort
● Pass 2:
○ Compare 2 and 5 → no swap → [2, 5, 1, 5, 6, 9]
○ Compare 5 and 1 → swap them → [2, 1, 5, 5, 6, 9]
○ Compare 5 and 5 → no swap → [2, 1, 5, 5, 6, 9]
○ Compare 5 and 6 → no swap → [2, 1, 5, 5, 6, 9]
● After the second pass, 6 is in its correct position.
● Pass 3:
○ Compare 2 and 1 → swap them → [1, 2, 5, 5, 6, 9]
○ Compare 2 and 5 → no swap → [1, 2, 5, 5, 6, 9]
○ Compare 5 and 5 → no swap → [1, 2, 5, 5, 6, 9]
● The list is now fully sorted: [1, 2, 5, 5, 6, 9].

Result:

● The list after sorting is [1, 2, 5, 5, 6, 9].


Bubble Sort
features of a high‐level programming language that a
programmer could use to make sure that their program will be
easier to understand by another programmer.
Variables
A variable is a named storage location that can hold a value and whose content can
change during the execution of a program.

Variables are used to store data that may need to be updated or changed, such as user
input, results of calculations, or the state of a program.

Meaningful names: Give variables descriptive names to make the code more readable and
maintainable (e.g., use user_age instead of just x).

Example:

age = 25

name = "Alice"
Constant
A constant is similar to a variable, but its value is set once and cannot be changed during the
execution of the program.

Constants are used to store values that should remain the same throughout the program, such as
mathematical constants (e.g., Pi), configuration values (e.g., max user limit), or other fixed data.

Naming conventions: Constants are typically written in all uppercase letters (e.g., MAX_USERS, PI)
to distinguish them from variables.

Limit constant usage: Constants should only be used for values that should never change (e.g., PI),
not for values that are expected to vary throughout the program.
Trace table
A trace table can be used to record the results from each step in an algorithm; it is used
to record the value of an item (variable) each time that it changes.
The manual exercise of working through an algorithm step by step is called a dry run.
A trace table is set up with a column for each variable and a column for any output. For
example:
Test data is then used to dry run the flowchart and record the results on the trace table.
During a dry run:

● every time the value of a variable is changed, the new value is entered in that
column of the trace table

● every time a value is output, the value is shown in the output column.

Test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5


Trace tables and test data can be used to identify and correct errors.
Trace table

Test data: 9, 7, 3, 12, 6, 4, 15, 2, 8, 5


Trace table
Trace table
Writing and amending algorithms
There are a number of stages when producing an algorithm for a given
problem:
1. Make sure that the problem is clearly specified – the purpose of the
algorithm and the tasks to be completed by the algorithm.
2. Break the problem down in to sub-problems; if it is complex, you may
want to consider writing an algorithm for each sub-problem. Most problems,
even the simplest ones can be divided into:
– Set up processes
– Input
– Processing of data
– Permanent storage of data (if required)
– Output of results.
3. Decide on how any data is to be obtained and stored, what is going to
happen to the data and how any results are going to be displayed.
4. Design the structure of your algorithm using a structure diagram.
Writing and amending algorithms
5. Decide on how you are going to construct your algorithm, either using a
flowchart or pseudocode. If you are told how to construct your algorithm, then
follow the guidance.

6. Construct your algorithm, making sure that it can be easily read and
understood by someone else. Precision is required when writing algorithms, just
as it is when writing program code. This involves setting it out clearly and using
meaningful names for any data stores.

7. Use several sets of test data (Normal,Abnormal and Boundary) to dry


run your algorithm and show the results in trace tables, to enable you to find any
errors.

8. If any errors are found, correct them and repeat the process until you
think that your algorithm works perfectly.
Writing and amending algorithms
Have a look at this structure diagram and flowchart for the algorithm to select the
largest, Max, and smallest, Min, numbers from a list of ten numbers. This time the
flowchart is more easily readable than the structure chart:
features of a high‐level programming language that a
programmer could use to make sure that their program will be
easier to understand by another programmer.

You might also like