Sunteți pe pagina 1din 31

Writing Pseudo

Code
MSIT
Agenda
 History of Algorithm
 Definition of Algorithm
 Algorithm criteria
 Different ways to write Algorithm
 What is Pseudo Code?
 Need for Pseudo Code.
 Pseudo Code Standards.
 Different Constructs.
History Of Algorithm
 The word algorithm comes from the name
of a Persian author ,Abu Ja’far Mohammed
bin Musa al Khowarazimi(825 A.D.).
 This word has taken on a special
significance in computer science, where
“algorithm” has come to refer to a method
that can be used by a computer for the
solution of a problem.
 That is what makes algorithm different
from words such as process, technique, or
method.
Definition of Algorithm
 An algorithm is a finite set of instructions that, if
followed ,accomplishes a particular task.

 All algorithms must satisfy following criteria.


1. Input
2. Output
3. Definiteness
4. Finiteness
5. Effectiveness
Algorithm criteria’s..
• Input: Zero or more inputs externally supplied.
• Output: At least one quantity is produced.
• Definiteness: Each instruction is clear and
unambiguous.
• Finiteness: If we trace out the instructions of
an algorithm , then for all the cases, the
algorithm terminates after a finite number of
steps.
• Effectiveness: Every instruction must be very
basic so that it can be carried out, in principle,
by a person using only pencil and paper.
Contd..
 According to criteria 1 and 2 algorithm
needs to produce one or more outputs for
the given zero or more inputs.
 According to criteria 3 each operation
should be definite , that it must be very
clear about what should be done.
 For examples: Directions such as “add 6 or 7
to x” or “compute 5/0” are not permitted
because it is not clear which of the two
possibilities should be done or what the result
is.
Contd..
 Criteria 4 says that they terminate after finite
number of operations.
 A reasonable consideration is that time for
termination should be reasonably short.
 Consider an algorithm that decides whether any given
position in game of chess is a winning position.
 This algorithm works by examining all possible moves
and countermoves that could be made from starting
position.
 The problem with this algorithm is that even using the
most sophisticated modern computers, it takes billions
of years to make the decision.
Contd..
 According to criteria 5, each operation should be
effective.

 That it can be done by a person using a pencil


and paper.

 For example:
 Performing arithmetic operations on integers is an
example of effective operation.
 But arithmetic operations on real numbers violates
effectiveness.
 As each value may be expressible only by infinitely long
decimal expansions.
 Adding such values violates effectiveness.
Contd..
 We can describe an algorithm in many
ways .

 We can use natural language like English,


if we choose this operation , the resulting
operations instructions are definite.

 Graphical representations called Flow


Charts are another possibility, but they
work well only if the algorithm is small and
simple.
Difference between Pseudo
Code & Flowchart
 Algorithm Lamp:
Begin:
If Lamp_plugged in then,
If Bulb_burned out then,
Replace bulb
Else buy new bulb.
Else plug in lamp.
End:
Pseudo Code
Flow Chart
Pseudo Code
 Pseudo code consists of short, English phrases
used to explain specific tasks within a program's
algorithm .
 Pseudo code is a kind of structured English for
describing algorithms.
 It allows the designer to focus on the logic of the
algorithm without being distracted by details of
language syntax.
 At the same time, the pseudo code needs to be
complete.
 It describe the entire logic of the algorithm so
that implementation becomes a rote mechanical
task of translating line by line into source code.
Contd..
 In general the vocabulary used in the pseudo code should
be the vocabulary of the problem domain, not of the
implementation domain.

 The pseudo code is a narrative for someone who knows the


requirements (problem domain) and is trying to learn how
the solution is organized. E.g.
 Extract the next word from the line (good)
set word to get next token (poor)
 Append the file extension to the name (good)
name = name + extension (poor)
 FOR all the characters in the name (good)
FOR character = first to last (ok)
Need for pseudo code
 The programming process is a complicated one.

 You must first understand the program specifications, then


you need to organize your thoughts and create the
program.

 This is a difficult task when the program is not easy.

 You must break the main tasks that must be accomplished


into smaller ones in order to be able to eventually write
fully developed code.

 Writing pseudo code will save you time later during the
construction & testing phase of a program's development.
Pseudo code standards
 Each textbook and each individual designer may
have their own personal style of pseudo code.

 Pseudo code is not a rigorous notation, since it is


read by other people, not by the computer.

 There is no universal "standard" for the industry,


but for instructional purposes it is helpful if we all
follow a similar style.

 The following format is recommended for


expressing your solutions.
standard constructs
These are the basic constructs for flow of control are
sufficient to implement any "proper" algorithm.

 SEQUENCE is a linear progression where one task is


performed sequentially after another.

 WHILE is a loop (repetition) with a simple conditional test at


its beginning.

 IF-THEN-ELSE is a decision (selection) in which a choice is


made between two alternative courses of action.

 REPEAT-UNTIL is a loop with a simple conditional test at the


bottom.

 CASE is a multiway branch (decision) based on the value of an


expression. CASE is a generalization of IF-THEN-ELSE.

 FOR is a "counting" loop.


Sequence
 Sequential control is indicated by writing one action after another,
each action on a line by itself.
 The actions are performed in the sequence (top to bottom) that they
are written.
 Example (non-computer)
 Brush teeth
Wash face
Comb hair
Smile in mirror
 Example (computer)
 READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
 Several keywords are often used to indicate common input,
output, and processing operations.
 Input: READ, OBTAIN, GET
 Output: PRINT, DISPLAY, SHOW
 Compute: COMPUTE, CALCULATE, DETERMINE
 Initialize: SET, INIT
 Add one: INCREMENT, BUMP
IF-THEN-ELSE
 Binary choice on a given Boolean condition is indicated by the use
of four keywords: IF, THEN, ELSE, and ENDIF. The general form
is:

IF condition THEN
sequence 1
ELSE sequence 2
ENDIF

 The ELSE keyword and "sequence 2" are optional. If the condition
is true, sequence 1 is performed, otherwise sequence 2 is
performed. Example
IF HoursWorked > NormalMax THEN
Display overtime message
ELSE Display regular time message
ENDIF
WHILE
 The WHILE construct is used to specify a loop with a test at the
top.
 The beginning and ending of the loop are indicated by two
keywords WHILE and ENDWHILE. The general form is:

WHILE condition
Sequence
ENDWHILE

 The loop is entered only if the condition is true.


 The "sequence" is performed for each iteration. At the conclusion
of each iteration, the condition is evaluated and the loop continues
as long as the condition is true.
 Example
WHILE Population < Limit
Compute Population as Population + Births – Deaths
ENDWHILE
CASE
 A CASE construct indicates a multiway branch based on
conditions that are mutually exclusive.
 Four keywords, CASE, OF, OTHERS, and ENDCASE, and
conditions are used to indicate the various alternatives. The
general form is:

CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASE

The OTHERS clause with its default sequence is optional.


Conditions are normally numbers or characters
Case
 indicating the value of "expression", but they can be English
statements or some other notation that specifies the condition
under which the given sequence is to be performed.
Examples:
 CASE Title OF
Mr : Print "Mister"
Mrs : Print "Missus"
Miss : Print "Miss"
Ms : Print "Mizz"
Dr : Print "Doctor"
ENDCASE

 CASE grade OF
A : points = 4
B : points = 3
C : points = 2
D : points = 1
F : points = 0
ENDCASE
REPEAT-UNTIL
 This loop is similar to the WHILE loop except that the test is
performed at the bottom of the loop instead of at the top.

 Two keywords, REPEAT and UNTIL are used. The general form is:

REPEAT
Sequence
UNTIL condition

 The "sequence" in this type of loop is always performed at least


once, because the test is performed after the sequence is
executed.

 At the conclusion of each iteration, the condition is evaluated,


and the loop repeats if the condition is false.

 The loop terminates when the condition becomes true.


For Loop
 This loop is a specialized construct for iterating a specific
number of times, often called a "counting" loop.
 Two keywords, FOR and ENDFOR are used. The general
form is:

FOR iteration bounds


Sequence
ENDFOR

it is best to describe the loop using problem domain


vocabulary.
Examples:
 FOR each month of the year (good)
 FOR month = 1 to 12 (ok)
 FOR each employee in the list (good)
 FOR empno = 1 to listsize (ok)
NESTED CONSTRUCTS
 The constructs can be embedded within each
other, and this is made clear by use of indenting.
 Nested constructs should be clearly indented from
their surrounding constructs.
Example
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
INCREMENT total
END IF
UNTIL Temperature < zero
Print total
In the above example, the IF construct is nested within
the REPEAT construct, and therefore is indented.
INVOKING SUBPROCEDURES
 In computer science, a subroutine (function, procedure, or
subprogram) is a sequence of code which performs a
specific task, as part of a larger program, and is grouped as
one or more statement blocks.

 Subroutines can be "called", thus allowing programs to


access the subroutine repeatedly without the subroutine's
code having been written more than once. ...

 Use the CALL keyword to invoke sub procedures or sub-


routines.
Example to invoke
subroutines.
 Example:
 Algorithm adding
Begin:
Read a;
Read b;
Call sum(a,b);//invoking sub-routine
end

 Algorithm Sum(a,b)
Begin:
Set c=a +b;
Display c;
End:
Exception Handling
 Handling of errors in the code manually is called
Exception Handling.

 BEGIN
statements
EXCEPTION
WHEN exception type
statements to handle exception
WHEN another exception type
statements to handle exception
END
Recursive Algorithms
 Calling a sub-routine within itself is called
recursive sub-routine.

Algorithm RSum(a,n)
{
If (n<=0) then return 0.0;
Else return RSum(a,n-1)+a[n];//calling
subroutine within itself.
}
Example:
 Algorithm Fibonacci (n)
 //compute the nth Fib`onacci number
 Begin:
 if n<=1 then
 Display n;//write output to console
 else

 set n1=0;
 set n2=1;
 for i=2 to n do

 set res=n1+n2;
 n1=n2;
 n2=res;

 display res;//writing the result to console

 End:
Example
 Algorithm Fibonacci(n)
 //compute the nth Fib`onacci number
 { if(n<=1) then
 write(n);//write output to console
 else
 {
 n1:=0;n2:=1;
 for i:=2 to n do
 {
 res:=n1+n2;
 n1:=n2;
 n2:=res;
 }
 write(res);//writing the result to console
 }
 }

 The same example written in 2 convetnions


 There is no specific convention to write Pseudo Code.
 Pseudo Code is meant for the user not for the system
References
 Text book Fundamentals of Computer
Algorothms(Galgotia)
 By.
 ELLIS HOROWITZ
 SARTAJ SAHNI
 SANGUTHEVAR RAJASEKARAN

 http://en.wikipedia.org/wiki/Pseudocode
 http://www.csc.calpoly.edu/~jdalbey/SWE/pdl_std.ht
 http://www.wiley.com/college/busin/icmis/oakman/ou
 http://www.webopedia.com/TERM/P/pseudocode.htm

S-ar putea să vă placă și