0% found this document useful (0 votes)
6 views18 pages

Chapter 7

Uploaded by

ryan.khan22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views18 pages

Chapter 7

Uploaded by

ryan.khan22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 7

Algorithm design and problem solving

The Program Development Life Cycle (PDLC) is an iterative process that allows for
feedback and adjustments to be made at each phase, to ensure that the final product
meets the needs of the stakeholders and is of high quality. It provides an organized plan
for breaking down the task of program development into manageable chunks, each of
which must be completed before moving on to the next phase. It includes the following
four stages:
• Analysis
• Design
• Coding
• Testing

Analysis
The first step in the program development cycle is to define the problem. This is done by
identifying and understanding why is the program or software being developed. Usually,
it’s in the form of a program specification. The program specification defines the problem
statement, what is required from the software development team, and what is the output
of the solution to the problem they’ve been tasked with solving. It also includes
identifying the stakeholders, their needs and expectations, and determining the
functional and non-functional requirements for the program known as the "requirements
specification" for the program. In larger development teams, the system analyst is
responsible for this step. It uses tools such as abstraction and decomposition to identify
what exactly is required from the program

Abstraction focuses on the essential elements needed for the solution while eliminating
unnecessary details and information. Your car is a great example of abstraction. You can
start a car by turning the key or pressing the start button. You don’t need to know how
the engine is getting started, what all components your car has.

Decomposition is the process of breaking large, complex problems into smaller,


manageable parts. Daily tasks can be decomposed into constituent parts for easier
understanding and solving

Design
In this phase, the program’s architecture and design are developed. This includes creating
a detailed design of the program’s components and interfaces. The program specification
derived from the analysis stage is used as a guide for program development. The design
phase of the software development process also includes designing the way a user will
perform various tasks when using the software and how various parts of the system will
work together. This can be formally documented using structure charts, flowcharts and
pseudocode
Coding
This is the stage where developers begin coding and setting up the infrastructure for the
system. Coding the program means translating an algorithm into specific programming
language. If the software project is larger and the team is made up of more than one
member, the various development tasks will be assigned to team members. Programmer
must follow the language rules, violation of any rule causes error. They will refer to the
plans and documents created by the design team and will work with the designers to
ensure what they are creating aligns with the design plans. The programmer writes a
section of code (module) then tests it. The module may work fine, but more likely the
programmer will amend or fix the code, and test it again. This is called iterative testing.
The process repeats (iterates) until the module works as intended.

Testing
The completed program or set of programs is executed multiple times using various test
data sets. This testing process ensures that all the tasks within the program work together
as specified in the program design. Running the program with different test data can
identify and address potential issues and errors. Syntax error and logical error are
collectively known as bugs. The process of identifying errors and eliminating them is
known as debugging. The testing phase aims to verify the overall functionality and
performance of the program by evaluating its behavior with various inputs.

Computer systems, sub systems and decomposition


A computer system consists of hardware components that have been carefully chosen so
that they work well together and software components or programs that run in the
computer. In its most basic form, a computer system is a programmable electronic device
that can accept input; store data; and retrieve, process and output information. A
computer system is also made up of many subsystems — for example, the storage, where
data on a computer is saved, is a system in itself. In order to understand how a computer
system is built up and how it works it is often divided up into sub-systems. This division
can be shown using top-down design.

A top-down design is the decomposition of a system into smaller parts in order to


comprehend its compositional sub-systems. In top-down design, a system’s overview is
designed, specifying, yet not detailing any first-level subsystems. Then, every subsystem
is refined in greater detail, for example, sometimes dividing into many different levels of
subsystem, so that the whole specification is decomposed to basic elements. As soon as
these base elements are identified, it is easier to build these elements as computer
modules. Once the modules are built, it is effortless to put them together, building the
whole system from these individual elements. Division of tasks into subtasks essentially
splits the problem into various smaller programs, which helps developers to easily code
these simpler parts.
Benefits of top-down design:

• Different designers can work on modules individually then bring the sun
problems together at the end.
• Once each module has been designed, they can be given to different
programmers to code. This speeds up the development of the program.
• As each module is a shorter program, they are easier to write, test and debug
than the full system.
Computer systems and subsystems
• Computer systems can be of varying sizes
• They are made up of software, hardware, data, communication, people
• Each computer system can be divided into further subsystems until each subsystem
performs a single action.

Design methods

Structure diagrams
Structure diagrams are a graphical way of representing a problem, showing the different
levels of detail. They are a great way to illustrate all the systems and sub-systems. It shows
the hierarchy or structure of the different components or modules of the system and
shows how they connect and interact with each other.
Below are some examples of structure diagrams:
Algorithm
An algorithm is a sequence of steps, which perform a specific task. In computing,
algorithms are usually represented as a program flowchart, or in pseudocode, so that the
purpose of the task and the processes needed to complete it are clear to those who study
it.

Variables and constants


A variable in a computer program is a named data store than contains a value that may
change during the execution of a program. In order to make programs understandable to
others, variables should be given meaningful names.
A constant in a computer program is a named data store than contains a value that does
not change during the execution of a program. As with variables, in order to make
programs understandable to others, constants should also be given meaningful names.

Declaring variables and constants


It is considered good practice to declare the constants and variables to be used in that
program.
Only literals can be used as the value of a constant. A variable, another constant or an
expression must never be used.

Flowcharts
A flowchart is a diagrammatic representation of an algorithm, a step-by-step approach to
solving a task. Flowcharts are the graphical representation of the data or the algorithm
for a better understanding of the code visually. It displays step-by-step solutions to a
problem, algorithm, or process. A flowchart is a picture of boxes that indicates the process
flow sequentially. Since a flowchart is a pictorial representation of a process or algorithm,
it’s easy to interpret and understand the process.

Subroutine
A subroutine is a piece of code written separately from the main code to be ‘called’ where
needed. This subroutine can be called many times, and saves the time and effort of
rewriting it every time. In order to be able to call this code, it is given a unique name and
denoted using a subroutine symbol. Each subroutine will have its own flowchart. For the
cake example, you could have a subroutine called ‘eggs’. The processes of breaking and
separating the eggs and whisking the whites would all be part of this subroutine, so
instead of writing those steps into your main flowchart you could call the ‘eggs’
subroutine, which includes all the steps.

An example of flowchart is shown below:

Pseudocode
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does
not use any programming language in its representation instead it uses the simple English
language text as it is intended for human understanding rather than machine reading. In
simple words pseudocode is a simplified form of programming code that uses common
programming terminologies, but does not use the strict syntax rules of a programming
language.

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


in the way that it is written.
• a consistent 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.
Common operations in pseudocodes

1) Sequence
The ordering of the steps in an algorithm is very important. An incorrect order can lead
to incorrect results and/or extra steps that are not required by the task.

2) Assignment - Each variable is assigned using a left arrow.

[Variable name] [Value to be assigned]

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.

3) Input and output

Values are input using the INPUT command as follows:


INPUT <identifier>
Values are output using the OUTPUT command as follows:
OUTPUT <identifier>
4) Conditional/Selection Statements
Selection is a very useful technique, allowing different routes through the steps of a
program. For example, data items can be picked out according to given criteria, such as:
selecting the largest value or smallest value, selecting items over a certain price, selecting
everyone who is male.

IF-THEN-ELSE-ENDIF statements
In pseudocode, the "if-then-else" construct is used for conditional statements.
If: Checks a condition and executes a block of code if the condition is true.
Else: Specifies an alternative block of code to be executed if the condition in the "if"
statement is false.
EndIf: Marks the end of the if-then-else block.
CASE…OF…OTHERWISE…ENDCASE
A 'CASE' structure is a control flow statement in programming. It allows the execution of
different code segments based on the value of a specific variable or expression. This
structure offers a more streamlined and organized approach compared to using multiple
IF statements, particularly when dealing with several conditions.
Below is a list of comparison operators

5) Loop Structures (Iterations)


Iteration is the process of repeatedly executing a set of statements or a block of code. It
involves the repetition of a specific sequence of instructions until a certain condition is
met or a specified number of iterations have been performed.
These are:
» Count-controlled loops (for a set number of iterations)
» Pre-condition loops – may have no iterations
» Post-condition loops – always has at least one iteration.

Count-controlled loops are used when the number of iterations is predetermined. They
are often implemented using 'FOR' loops.

FOR…TO…NEXT: It will run for a determined/known amount of times

Post-condition loops such as REPEAT - UNTIL loops in many programming languages,


guarantee that the loop body is executed at least once, as the condition check occurs
after the loop body. REPEAT… UNTIL will run at least once till condition is satisfied;
verification is done after running code

Pre-condition loops, like 'while' loops, evaluate the condition before entering the loop
body. They are ideal when the number of iterations is unknown in advance.
WHILE…DO…ENDWHILE may not ever run; verification is done before running code.

6) Totalling and counting


Totalling statements are used to calculate the sum or total of a set of values.
Counting statements are used to keep track of the number of occurrences or elements in
a set. These concepts are frequently used in loops to process data, and they are
fundamental for tasks like calculating averages, finding the maximum or minimum values,
or determining the frequency of certain elements in a dataset.

TotalWeight = TotalWeight + Weight


Counter = Counter + 1

Calculating the average (mean) of all the values in a list is an extension of the totalling
method

Total ← 0
FOR Counter ← 1 TO NumberOfValues
Total ← Total + StudentMark[Counter]
NEXT Counter
Average ← Total / NumberOfValues

PassCount ← 0
FOR Counter ← 1 TO LoopLimit
INPUT Value
IF Value > Range
THEN
PassCount ← PassCount + 1
ENDIF
NEXT Counter
7) Maximum and minimum: Finding the largest and smallest values in a list are two
standard methods that are frequently found in algorithms. For example:

MaximumMark ← 0
MinimumMark ← 100
FOR Counter ← 1 TO ClassSize
IF StudentMark > MaximumMark
THEN
MaximumMark ← StudentMark
ENDIF
IF StudentMark < MinimumMark
THEN
MinimumMark ← StudentMark
ENDIF

Validation and Verification


Validation is an automatic computer check to ensure that the data entered is sensible and
reasonable. It does not check the accuracy of data.
There are many different types of validation checks including:
• range checks
• length checks
• type checks
• presence checks
• format checks
• check digits
Range Validation: This technique checks if the data entered into the system falls within
a specific range of values, such as a customer’s age between 18 and 65 years old. For
example
REPEAT
INPUT Value
IF Value < MinimumValue OR Value > MaximumValue
THEN
OUTPUT "The student's mark should be in the range", MinimumValue ," to ",
MaximumValue
ENDIF
UNTIL Value >= MinimumValue AND Value <= MaximumValue

Length Validation: This technique checks if the data entered into the system has a specific
length, such as a password with at least 8 characters. For example:
OUTPUT "Please enter your password of ", Limit , " characters "
REPEAT
INPUT password
IF LENGTH(password) <> Limit
THEN
OUTPUT "Your password must be exactly" , Limit ," characters, please re-enter "
ENDIF
UNTIL LENGTH(password) = Limit

Type Validation: This technique checks if the data entered into the system is of the
correct data type, such as a string, integer, or date. For example:

OUTPUT "Enter the value”


REPEAT
INPUT Value
IF Value <> DIV(Value, 1)
THEN
OUTPUT "This must be a whole number, please re-enter"
ENDIF
UNTIL Value = DIV(Value, 1)

Presence Validation: A presence check checks to ensure that some data has been entered
and the value has not been left blank. For example
OUTPUT "Please enter the value”
REPEAT
INPUT Value
IF Value = ""
THEN
OUTPUT "*=Required "
ENDIF
UNTIL Value <> ""

Format Validation: This technique checks if the data entered into the system follows a
specific format, such as a date in the MM/DD/YYYY format.

Check Digit Validation: A check digit is the final digit included in a code; it is calculated
from all the other digits. Check digits are used for barcodes, product codes, International
Standard Book Numbers (ISBN), and Vehicle Identification Numbers (VIN).
Check digits are used to identify errors in data entry caused by mis-typing or
mis-scanning a barcode. They can usually detect the following types of error:

» an incorrect digit entered, for example, 5327 entered instead of 5307


» transposition errors where two numbers have changed order for example 5037
instead of 5307
» omitted or extra digits, for example, 537 instead of 5307 or 53107 instead of
5307
» phonetic errors, for example, 13, thirteen, instead of 30, thirty.

Data verification is a post-processing activity. It's the checkpoint that confirms whether
the data has remained correct and unaltered when copied from one medium to another.
Verification is performed to ensure that the data entered exactly matches the original
source.
There are two main methods of verification:
Double entry - entering the data twice and the two instances are then compared for
consistency.
A visual check is a basic yet essential method of data verification. It involves a manual
review of the data entered into a system by an individual. The primary purpose is to
identify and correct overt errors.

Test data
It is important to test algorithms to check how they perform under a range of conditions.
When creating a testing plan, the test data that you use shouldn’t be random values, but
rather values that fulfill the following test criteria. It helps identify errors and assess how
the program handles different scenarios.

Trace table
A trace table is a technique used to test algorithms or computer programs for logic errors
that occur while the algorithm or program executes. It stimulates the flow of execution
where statements are executed step by step and the values of variables change as an
assignment statement is executed. They help programmers to visualize how a particular
algorithm works.
A dry run refers to the manual process of systematically executing an algorithm by
following each step-in sequence. Test data is employed to execute a dry run of the
flowchart and document the outcomes in a trace table.

Writing and amending algorithms


1. Make sure that the problem is clearly understood which includes knowing the
purpose of the algorithm and the tasks to be completed by the algorithm.
2. Break the problem into smaller problems (e.g. in a program which outputs average
values, divide the problem into multiple ones i.e. how to count the number of
iterations and how to count the total of all values)
3. Identify the data that is needed to be saved into variables/constants/arrays and
what datatype it is, and declare all the variables/constants/arrays accordingly,
with meaning full names
4. 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.
5. Construct your algorithm, making sure that it can be easily read and understood
by someone else. Take particular care with syntax e.g. when conditions are used
for loops and selection.
6. Use several sets of test data (Normal, Abnormal and Boundary) to dry run your
algorithm and check if the expected results are achieved (a trace table can be used
for this purpose). If error is found, find the point of error in the trace table and fix
it in the code.
GLOSSARY
Analysis – part of the program development life cycle; a process of investigation, leading
to the specification of what a program is required to do
Design – part of the program development life cycle; uses the program specification from
the analysis stage to show to how the program should be developed coding – part of the
program development life cycle; the writing of the program or suite of programs
Testing – part of the program development life cycle; systematic checks done on a
program to make sure that it works under all conditions
Abstraction – a method used in the analysis stage of the program development life cycle;
the key elements required for the solution to the problem are kept and any unnecessary
details and information that are not required are discarded
Decomposition – a method used in the analysis stage of the program development life
cycle; a complex problem is broken down into smaller parts, which can then be sub
divided into even smaller parts that can be solved more easily
Top-down design – the breaking down of a computer system into a set of sub-systems,
then breaking each subsystem down into a set of smaller sub-systems, until each
subsystem just performs a single action
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 by a program using the input data and
any other previously stored data
Output – 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 media for use in the
future
Structure diagram – a diagram that shows the design of a computer system in a
hierarchical way, with each level giving a more detailed breakdown of the system into
subsystems
Flowchart – a diagram that shows the steps required for a task (sub-system) and the order
in which the steps are to be performed
Algorithm – an ordered set of steps to solve a problem
Pseudocode – a simple method of showing an algorithm; it describes what the algorithm
does by using English key words that are very similar to those used in a high-level
programming language but without the strict syntax rules
Linear search – an algorithm that inspects each item in a list in turn to see if the item
matches the value searched for
Bubble sort – an algorithm that makes multiple passes through a list comparing each
element with the next element and swapping them. This continues until there is apass
where no more swaps are made
Validation – automated checks carried out by a program that data is reasonable before it
is accepted into a computer system
Verification – checking that data has been accurately copied from another source and
input into a computer or transferred from one part of a computer system to another
Set of test data – all the items of data required to work through a solution
Normal data – data that is accepted by a program
Abnormal data – data that is rejected by a program
Extreme data – the largest/smallest data value that is accepted by a program
Boundary data – the largest/smallest data value that is accepted by a program and the
corresponding smallest/ largest rejected data value
Range check – a check that the value of a number is between an upper value and a lower
value
Length check – a method used to check that the data entered is a specific number of
characters long or that the number of characters is between an upper value and a lower
value
Type check – a check that the data entered is of a specific type
Presence check – a check that a data item has been entered
Format check – a check that the characters entered conform to a pre-defined pattern
Check digit – an additional digit appended to a number to check if the entered number is
error-free; check digit is a data entry check and not a data transmission check

You might also like