7.5 Section 5 Algorithm Design
7.5 Section 5 Algorithm Design
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.
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
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.
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.
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.
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.
Individual modules
Final level
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.
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
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.
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
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 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
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.
NB
Clause 1 to 10 are facts
Clause 11 and 12 are rules
A capital letter denote a variable.