Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

7.5 Section 5 Algorithm Design

The document discusses various algorithm design concepts including standard algorithms, selection structures, repetition structures, searching algorithms, and flowcharts. It provides examples and explanations of pseudocode, if/else statements, for loops, while loops, recursion, and linear and binary search algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

7.5 Section 5 Algorithm Design

The document discusses various algorithm design concepts including standard algorithms, selection structures, repetition structures, searching algorithms, and flowcharts. It provides examples and explanations of pseudocode, if/else statements, for loops, while loops, recursion, and linear and binary search algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

7.

5 Section 5 Algorithm Design and Programming Concepts

7.5.1 Standard Algorithms


 An algorithm is a set of instructions that gives a sequence of operations for solving a problem.
 Pseudocodes provide a means of expressing algorithms without worrying about syntax of a
particular language. It uses control structures and keywords similar to those found in
programming languages.
 There are no hard and fast rules as to how Pseudocode statements should be written e.g.
 An assignment statement to assign a value 10 to X, could be written in any of the following
ways:
Assign 10 to X
X ← 10
X := 10
Put 10 in X

Selection Structure (decision structure)


 Is used when a decision or comparison has to be made.
 It shows a condition from which the decision is based and a set of actions to be taken if the
condition is true and a set of actions to be taken if the decision is false.
Testing a condition
 In selection or condition statements comparisons can be tested using the following:
= equals
> greater than
< less than
>= greater than or equal to
<= less than or equal to
<> is not equal to
Pseudocode using If...then...else...endif
If age >= 17
Display ‘You can drive a car’.
Else
Display ‘You are too young to drive a car’.
Endif.

Case of ...
 Case of ... is an alternative solution to IF...THEN...ELSE structure.
 It is used when there multiple options from which to choose.
 The Case statement includes:
The word CASE
The word of
A group of statements

Example
An examination system uses the categories of marks shown below.

Examination mark Result


Mark < 40% Fail
>= 40% and < 60% Pass
>= 60% and < 80% Merit
>= 80% and <= 100% Distinction
By using a Pseudocode, write a code to implement this decision making problem
using suitable selection structure.
Solution 1 Solution 2
Input mark SELECT CASE Mark
If Mark < 40 CASE 0 TO 39
Then Print ‘Fail’
Print ‘Fail’ CASE 40 TO 59
Else Print ‘Pass’
If Mark >=40 AND Mark < 60 CASE 60 TO 79
Then Print ‘Merit’
Print ‘Pass’ CASE >= 80
Else Print ‘Distinction’
If Mark >= 60 AND Mark <80 END SELECT
Then
Print ‘Merit’
Else
Print ‘Distinction’
Endif
Endif
Endif

Program flowcharts
 Is a diagram that can provide another way of showing an algorithm rather than using a
Pseudocode.

If

Condition

Statement_2
Statement_1

Endif
Repetition/Iteration
 A section of program is repeated many times e.g. in while-do statement and repeat until
statements
While...do
 The structure is used when you do not know how many times the steps inside a loop need to be
performed.
 A condition is tested at the start of the loop and is used to either end the loop or continue
carrying out the instructions inside the loop.
E.g.
While Total < 100 Do Flowchart
Read item_name while
Display item_name
Total = Total + 1
Endwhile. Statement sequence
condition true

false

endwhile

Repeat....Until
 The sequence of instructions inside the loop is always performed at least once, because the test
is performed after sequence instructions have been carried.
 If the condition is false, the loop repeats.
 If the condition is true, the loop ends.
E.g. Repeat
Total = 0
Repeat
Read Number Statement sequence
Total = Total + Number
Until
Total >= 100 False
Print Total. condition

True

Endrepeat

Repeat until While...do


1. Executed at least once 1. May never be executed
2. The condition is tested at the end of the 2. Condition is tested before entry into the loop
loop. 3. Terminate if the condition is false
3. Terminate if the condition is true.

For ...to...next loop


 Used when you want to perform the sequence of instructions in the loop a set number of times.
 This type of loop is called a counting loop because it counts how many times the instructions
inside the loop have been carried out.
E.g.
Total = 0
For N = 1 to 10
Read number
Total = Total + number
Next N
Print Total

Write a Pseudocode where you input 50 numbers and the number of


negative numbers are counted and then the result is output.

Linear structure
 The processing steps are carried out one after the other in the sequence given.
E.g.
While a< b
Begin
Statement 1
Statement 2
Statement 3
End

Recursion
 A function that calls itself is called a recursive function.
 It needs a stopping condition.

Example of a recursive function to calculate Factorial n (n!)

Function Factorial(n)
Begin
If n=1 or n = 0 then
Factorial = 1
Else
Factorial = n * factorial (n-1)
Endif
End.

Advantages
 Is more natural and easier for the programmer to write and understand recursive routines.
 Recursive solutions are very short and quick to code
 Recursive routines are more appropriate for problems, e.g. when traversing a tree structure

Disadvantages
 The computer has to make multiple procedure and function calls, each time storing return
addresses and copies of local or temporary variables, all of which takes more time and space.
 If the recursion continues too long, the stack containing return addresses may overflow and the
program will crush.
 Can be difficult to debug as it is harder to dry run a recursive routine.
 Can run slower than the corresponding iterative routine because of the overheads in calling
procedures, storing return addresses.

Flowcharts
 A program flowchart is a diagram that can be helpful to explain an algorithm visually
rather than by using Pseudocode.
Example
Produce a flowchart that will display the number of integers entered using the keyboard and
will also add up all the numbers entered and display the final total. The flowchart should
end when the number o is entered .

Answer
Start

Count = 0
Sum = 0

Enter number

Number =0 End

Count = count + 1

Sum = sum + 1

Display count

Display sum

Dry run

 Once you have drawn a flowchart or produced pseudocode you need to check for errors and this
is best done using a dry run.
 A dry run a check to make sure that the logic is correct and no steps have been left out.
 Test data are used as input for the pseudocode or flowchart.
 The steps are obeyed in turn and the values of the variables are recorded in a table as they
change.
 The output is also recorded in the table which is called trace tables.

Trace tables
 Used to test algorithms, to make sure that there are no errors in the logic of the algorithm.
 Result are displayed in a table
Example
Use a trace table to show the values var1, n, and the condition n < 5 when the following
statements are executed.

var1 ← 3 var1 n n <5


n←0
While n < 5 do
begin
var1 ← var1 + n
n←n+1
end

Searching Algorithms

Linear Search
 A linear search assumes that data to be in consecutive locations such as in an array.
 Does not require data to be in any particular order.
 To find the position of a particular value involves looking at each value in turn starting with the
first and comparing it with the value you are looking for.
 The search is ended when the value is found or the end of the list is reached.
 Its a very slow method, particularly if there are large number of data values.

Algorithm for linear search


Start at the beginning of the list
Repeat
Test the next item for a match
Until item found or end of list reached.

Binary Search
 Is used for searching an ordered array.
 Is much faster than linear search for bigger arrays.
 The ordered array is divided into 3 parts:
A middle part
The lower part of the array
The upper part of the array
 Compare the middle item with the item sought
 If is not equal, then
 If it is greater than the sought item, discard the upper half
 If it is less than the sought item, discard the lower half
NB The number of items being searched is therefore halved and the process repeated until the last
item is examined.
 Binary search is recursive.
 The maximum number of comparison that has to be made in a binary search of 2 n items is n + 1.
 Thus an item in a list of 1024 (210) items can be found in maximum of 11 comparison.
Binary Recursive Solution
Procedure Binary_Search (Bottom, Top, Item)
ItemSought := False
Searchfailed := False
Midpoint := Integer part of ((Top + Bottom)/2)
If A[Midpoint] = ItemSought
Then Found := True
Else
If Bottom > Top
Then Searchfailed := True
Else
If A[Midpoint] < ItemSought
Then Binary_Search (Midpoint + 1, Top, ItemSought)
Else Binary_Search (Bottom, Midpoint, ItemSought)
Endif
Endif
Endif
End.

Binary Iterative Solution


Procedure Binary_Search (Bottom, Top, Item)
ItemSought := False;
Searchfailed := False;
Top := N; Bottom := 1
Repeat
Midpoint := Integer part of ((Top + Bottom)/2)
If A[Midpoint] = ItemSought
Then Found := True
Else
If Bottom > Top
Then Searchfailed := True
Else
If A[Midpoint] < ItemSought
Then Bottom := Midpoint + 1
Else Top := Midpoint - 1
Endif
Endif
Endif
Until Itemfound or Searchfailed
EndProc.

Comparison of linear Search and Binary Search


Search Advantages Disadvantages
Linear Search 1. Additional data is simple appended to 1. A search is inefficient if there
the end. is an large number of data
2. The Search algorithm is straightforward item.
3. The Search works well if there is a small 2. Missing data item cannot be
number of data items identified until every item has
compared
Binary Search 1. Large number of data items can be 1. Data items must be stored
searched very quickly before the search is carried
2. Missing data items can be identified out.
quickly. 2. Adding and deleting data item
is slow (as every change
involves resorting the data)

System Design Approaches


Top down design
 Its a technique where the problem is defined and then split into a number of smaller subtasks.
Each of the subtasks is successfully split and refined until it is small enough to sbe understood
and programmed.
 It starts with the original problem at the highest level.
 The next and subsequent levels show how the problems in the previous levels are split
up to form smaller , more manageable problems.
 This continues until each of the blocks i.e. the lowest level is self-contained, easily
solvable problem.
 The individual problems can then be solved and combined according to the links that
have been used.

links Original problem

Individual modules

Final level

Advantages of Top-down design

1. More than one person (programmers) can be engaged on solving parts of the same problem
simultaneously.
2. More experienced programmers can be given more complex modules to write and the can work
on the simpler modules.
3. Modules can be tested independently.
4. If the programmer leaves partway through a project, it is easier for someone else to take over a
set of self-contained module.
5. A large project becomes easier to monitor and control.
6. Program maintenance becomes easier because the affected modules can be quickly identified
and changed.
7. A module is small enough to be understable and therefore easier to debug.
8. Some modules can be standard procedures and can be used in different programs.
Bottom-Up-design

 Involves designing a number of small modules before designing the larger structure.
 This is considered bad practice, since it is often difficult to ensure that an efficient system is
developed by this method.
 The parts of the program may not fit together very easily.
 There may be lack of consistency between modules.

7.5.3 Programming Languages

Language features
1. Programming constructs
 Are used in structured programming to support the Top-down approach applied when
developing an algorithm.
 Programming constructs are used in program flowchart and pseudocode.
 There are three programming constructs;
Sequential construct – They execute one or more statements or instructions one after
the other i.e. in sequence.
Selection constructs – They perform a logical test to determine the course of action to
be taken. Therefore depending on situations, different paths may be followed.
Iteration construct – iteration is a vital task that a computer does. Loops depend on a
logical test like in selection construct, however the statement or statements may be
executed several times.
2. Block structure
 Programming languages that encourage the use of blocks are called block structured
languages.
 A block is a group of program statements that are treated as a single unit
 A block consists of a declaration part, which includes constant, variables and type definitions
and procedures and function declarations and a statement part.

Constant
 Is a data item associated with a location in memory, once a value is assigned to it, it cannot
be changed while the program is running.
 Constant must have an identifier name and a declared data type, e.g. Pi is an identifier name
for a constant that is assigned a value.
Const Pi As Single
Pi = 3.141593
 Constant are useful as they can be referred to many times in the program code by their
identifier name.

Variable
 Is a data item associated with a location in memory. The value of the variable may change
during the running of the program.
 The variable is given an identifier name, e.g. No of children is an identifier name.
 Variables can be local or global.

Global variables
Are identifiers which are declared in the main program.
Can be used throughout the program and all subprograms.
A global variable can be accessed and modified from anywhere within the system.
Local variables
A variable which is inside a procedure or function.
They exist only during a call to the subprogram

Identifier
 Is a name that is used to represent a variable, constant, a function, a procedure, an object or any
other element in a program.

Scope of identifier
 The scope of identifier defines the extent to which an identifier is potentially accessible within a
system.

Statement
 Is a program instruction written in high level language that is human readable and it can be
executed.
 When a statement is translated, it often generates several machine-code instructions.

Expression

Subroutine, Procedure and Functions

Subroutine
 A subroutine (function, procedure or subprogram) is a portion of code written in a larger
program which performs a specific task and relatively independent of the remaining code.
 High level languages(HLL) provide libraries of useful pre-written programs, which are termed
pre-defined procedures and functions.
 They have previously been written, compiled and tested so that they can be used by
programmers.

Procedure
 Is a type of subroutine which is called by main program by writing its name followed by any
parameter passing within the brackets
 Parameter are passed by values or by reference.
 A procedure can have one or more parameters, usually referred to as the parameter list. This act
as an interface between the calling programs and the procedure.

Function
 Is also a type of subroutine.
 A function can accept parameters and return a single value.
 The name of the function is used as a variable having that value.
 Function calls appears in programs as expressions.
 The function has to contain an assignment to give its value.
 The function type has to be specified.
 A function can be maintained separately from the main program that allows different programs
to use them.
 A function start with a function header.
 A function is not normally used when more than one value is to be passed back
Procedure Functions
1. Returns more than one value. 1. Returns a single value
2. Is called by calling program by writing its 2. The name of the function is used as a
name, followed by an parameter passing variable having that value
within the brackets. 3. Function calls appear in the calling program
3. as an expression.
4. Starts with a function header

Parameter Passing
 A parameter is a means of passing information to and from a procedure.
 Parameters can be of two types:
Formal parameters: These are declared within the procedure heading.
Actual parameters: These are parameters which are passed in the call statement of the
main programs.
 Any identifier whose value will be changed in the subprogram must be declared as a variable
using the var statement. These are called variable parameters and they provide a two way
communication.
 Parameters whose values do not change in the subprogram are called value parameters. They
provide one way transfer of data from the main program to the procedure.
 Parameter can be passed by:
Passing by value: the actual value is passed and the original value is retained when
subroutine is finished.
Passing by reference: the address of the values is passed and any change to the value of the
parameter in the subroutine changes the original value.

Programming Language
Low level languages (LLL)
 The 1st generation of computer language is machine language (late 1940s).
 It is the actual patterns of 0s and 1s used in the computer memory.
 It was difficult to write and led to many errors in program code that were difficult to debug.
 Early 1950s, the 2nd generation was introduced i.e. Assembly language.
 It is written in using mnemonics (abbreviations that represent the instructions in more memorable way).
 Assembly language is translated into machine code using a program called assembler.
 Each assembly language instruction is translated into equivalent machine code statement.
 Assembly language occupy a little space as possible and execute as fast as possible.
 Assembly language are still used for applications where timing or storage space is critical, e.g. parts of
operating system and device drivers programs in embedded system.
 Assembly language and machine code are called low level languages.
 Assembly language and machine code are machine dependent i.e. each type of computer will have its
own assembly language.

High level languages (HLL)


 Third generation (late 1950s – 1970s) were developed i.e. the HLL.
 HLL are designed around the problem to be solved rather than the machine .
Characteristics of HLL
 They are problem oriented i.e. each HLL has structures and facilities appropriate to a particular type of
problem, e.g. FORTRAN (FORmula TRANslation) and ALGOL (ALGOrithmic Language were developed for
scientific and engineering problems, BASIC (Beginners All purpose Symbolic Instruction Code) was
developed as a teaching language.
 They are portable which means that a program written for one machine will run on any other machine for
which the appropriate compiler and interpreter is available.
 Statements in HLL resemble English like statements or mathematical expressions and they are easier to
learn and understood than assembly language.
 Each statement in HLL will be translated into several machine code instructions

Facilities of HLL
 Selection structures such as if...then..else, SELECT CASE statements
 Iteration structures such as while...do
 Built in routines to simplify input and output (readln, writeln in Pascal.
 Built in functions such as sqr, log, chr etc.
 Data structures such as string, record

Types of HLL
1. Business language – COBOL
2. Scientific language – FORTRAN and ALGOL
3. Educational language – PASCAL and LOGO
4. System programming – C
5. Object oriented programming – C++, DELPHI, Smalltalk,
6. Artificial Intelligence – PROLOG

Procedural (Imperative) languages


 They specify how to solve a problem as a sequence of steps. E.g. To find the area of a rectangle
the steps are:
1. INPUT the length
2. INPUT the breadth
3. Multiply the length by the breadth and store the result
4. OUTPUT the result.
 Each line of code is executed one after the other in sequence.
 They use the constructs: sequence, selection and iteration
 The programmer has to specify exactly what the program has to do.
 Procedural languages are used to solve a wide variety of problems e.g. to solve scientific and
engineering problems (FORTRAN and ALGOL), while others are more suitable for solving
business problems(COBOL) and others are suitable for solving control problems that need real
time solutions e.g. C, Ada, Modula-2 and Occam
 Procedural languages may include functions and procedures but they always specify the order in
which instructions must be used to solve the problems.

Features which make FORTRAN suitable for mathematical applications


 It has large library of inbuilt mathematical functions such as log, sqrt, sin etc.
 Comprehensive libraries of statistical and engineering routines are readily available and well
documented.
 Double precision arithmetic means that calculations can be performed with great accuracy
 Good array handling capabilities means suitable for solving e.g. large sets simultaneous
equations.

Facilities which make COBOL a suitable for data processing applications


 Good validation facilities
 A sort verb which allows files to be sorted into any sequence
 Excellent file handling capabilities
 Good report formatting capabilities
 Facility to access database from within a COBOL program

Problems in maintaining programs written procedural language


 If the structure of the data changes all programs which use the data need to be altered e.g. the
addition of a new field may cause changes to a number of programs in a system.
 If the functions of the system changes, program alterations will be widespread. e.g. if a bank
change cheque processing from batch to an interactive process, it leads to a totally redesigned
system even though actual data entities don’t change.

Object –oriented programming language (Visual Basic)


An object-oriented program implements objects that contain both the data to represent these
objects and the operations/methods that can be performed on them.
 Data and operations are encapsulated that is they are combined together.
 Data encapsulation is the concept that data can only be accessed via the methods provided by
the class.
 A class is a specification of an object. E.g. Bank Account

Bank Account
Account number
Customer Name Data
Balance
Credit on amount
Debit on amount
Provide the balance methods /operations
Provide the customer details

 An object is group of data and associated program routines used within an object-oriented
programming system.
 Inheritance is the means by which the properties and methods from the object class are copied
to the object being created so that only the difference have to be reprogrammed.
 A derived class is a class resulting from the inheritance process. It have all the features of the
parent class plus any new features specified.
 Two classes that are derived from the same base are said to be polymorphic.
 Polymorphism means that two object may share many characters but have unique features of
their own.

Objects in Windows
 An object is an independent procedure that contains both the instructions and data to perform
some task, and the code necessary to handle various messages it may receive.
 Objects in windows include forms, dialogue boxes, command buttons, list boxes and text boxes
 An object contains all that is needed to make that particular aspect of the program carry out bits
task:
 The procedure (methods) that are needed to respond to events that may occur
 The data that is needed by the procedures.
 The process of bundling together procedures and data is referred to as encapsulation.

Data and procedure for a command button object

Data Methods
Name: Button 1 OnClick
Caption: Press Me OnDragDrop
Height: 41 OnDragOver
Tab Stop: True OnEnter
Visibility: True Inheritance diagram OnExit
Width: 121 MAMMAL CLASS
Properties Methods
Age Eat
Gender Breathe
Body Temperature Sleep

HUMAN CLASS TIGER CLASS


(Inherits these properties and methods)
(Inherits these properties and methods)
Properties Methods
Age Eat Properties Methods
Gender Breathe Age Eat
Body Temperature Sleep Gender Breathe
Body Temperature Sleep
Additional Properties and Methods Additional Properties and Methods
Name Talk
Species Hunt
Declarative languages
e.g. Prolog (PROgraming in logic)
 In declarative languages, the computer is told what the problem is, not how to solve it.
 It consists a set of facts and rules about a particular thing rather than a sequence of instructions.
 The languages are useful when solving problems in artificial intelligence, such as medical
diagnosis or fault finding in applications.

Characteristics of Prolog
 Instead of defining how a problem is solved, the programmer states the facts and rules
associated with the problem.
 The order in which the facts and rules are stated is not important, unlike the statement in
imperative language.
 It is easy to add new rules, delete or change existing rules.
 The route through the program follows does not have to be stated by the programmer, Prolog
will select a possible route through a program and if that fails, it will backtrack to that pointand
try another route.

Example of Prolog database


1. parent (jim, joan)
2. parent (mark, linda)
3. parent (sarah, joan)
4. parent (jim, Kevin)
5. parent (sarah, Kevin)
6. female (joan)
7. female (linda)
8. female (sarah)
9. male (mark)
10. male (Kevin)
11. Father (A, B) IF parent (A, B) AND male (A)
12. Mother (A, B) IF parent (A, B) AND female (A)

NB
 Clause 1 to 10 are facts
 Clause 11 and 12 are rules
 A capital letter denote a variable.

*Prolog operates by attempting to satisfy a series of goals /querry.

a) A query might be mother (sarah, joan)


Use rule 12 by looking for parent(sarah, joan)
Having found this in fact 3, satisfy the goal female(sarah)
Having found in fact 8, the answer is yes.

b) Another query might be mother (X, joan)


Use rule 12 to satisfy this goal
Satisfy the subgoal parent (X, joan)
Parent (jim, joan) is found in fact 1
Satisfy female (jim)
The goal is not satisfied
Backtrack to subgoal parent(X, joan)and continue down the database, parent(sarah) is found
on fact 3
Satisfy subgoal female(sarah)
The goal is satisfied in fact 8
Therefore X = sarah.

General purpose languages


 Are developed to solve different problems
 Example of general purpose language is Pascal

Special purpose languages


 Are developed to solve specific problems
 Examples are: COBOL, C etc

You might also like