Algorithms & Flowcharts with Examples.PDF. Algorithms & Flowcharts with Examples.PDF. Open. Extract. Open with.
[' -t4 \'
ALGORITHMS,!' FLOWCHARTS
r\{ , ,',
What is an Algorithm? An Algorithm is a step-by-step method of performing any task' (Or)
..{'\F
,${t'
_d\
An Algorithm cafibe defined as a finite set of rules, which gives a sequellce of operations for solving a specific type of problern. (Or) An Algorithm is awell-developed, detailed ancl organized approach to solving a ccmplex problem. (Or) An Algorithm is ageneral, language independent set of action intended to perform a specific task.
It has the following five features (conditip4l): Finiteness: An algorithm should always terminate after a.finite number of steps. Each step must be (2) Definiteness: Each step of a n algorithm must be ctear AfalmUiguous' | definite" It must be perfectly clear what should be done. (3) Effectiveness: Each step must be effective. T'hat is it should be easil.v convertible into program statement and can be performed exactly in a finite amount of time. (4) Generality: The algorithm must be complete in itself. So that it can be used to solve all
(t)
problems of a specific type for any input data. (5) Input/output: Each algorithm must take zero, one or more i/p quantities and produce one or more o/p quantities. Consider shopping cxamPle Step 1: Going to shoP Step 2: Selecting and purchasing the required items Step 3: Returning back
We can fuither subdivide the f,rrst step of above algorithm Consider going to shoP examPle Step 1: Go to the bus stoP Step 2: Board the approPriate bus Step 3: Get the ticket Step 4: Reach the destination
Like this we can write the algorithms in English like sentences.
\r1.',
E
".', The goal of Computer Science is to develop sound
algorith:::-.::':
-.
: - -:-:x
problerns.
lr
'': .ir +,
An Algorithm is one of the most basic tools that are used to der el.-,p --r :r- ,:, :':r , - l logic. An algorithm is designed for a problern that is solved using a computer. Different algorithms may accomplish the same task, with a different set of in--s.-r:r=- : more or less the same time, space, and efforts. For developing an effective algorithm, flowchafts and pseudo codes are used b1' programmers. They are further expressed in programming language to develop computer programs.
isr The word algorithm comes from the name of fameous arad mathematician"abu jafar mohammed ibn musa Al-khowarizml" hterally meaning is father ofjafar mohammed, of moses native of Al-Khowarizm. The
gi o o o
son
are,
Devising the algorithm
Validating the algorithm Expressing the algorithm Devising an algorithm is a method of solving a problem. Each step of an algorithm must be precisely defined and no vague statements should be used. Pseudo code is used to describe the algorithm, in less formal language than a programming language. The next step in developing algorithm is validating the algorithm is (i.e. proof of correctness of an algorithm) a human must be able to perform each step using paper and pencil by giving the required input, use the algorithm and should get the required output
in a finite amount of time. The next step is to implement the algorithm in programming language.
Algorithm properties Algorithms are not computer programs, as they cannot be executed by a computer. Properties of Algorithm are: 1. There must be no ambiguity in any instruction. 2. There should not be any uncertainty about which instruction is to be executed next. 3. The description of the algorithm must be finite. An algorithm cannot be open-ended. 4. The execution of the algorithm should conclude after a finite number of steps" 5. The algorithm must be general enough to deal with any contingency. 6. The algorithm should use less memory space as much as possible. 7 " An algorithm takes zero or more inputs and results in one or more oulputs. 8. An algorithm should be efficient and flexible. Three basic operations that the statements of an algorithm have the following type
\
- A series of steps that we perform one after the other Selection - making a choice from multiple available options Iteration - Perfonning repetitive tasks Sequence
By combining these three we can write any algorithm.
Structure of an algorithm: The structure of an algorithm must starts with the step of Start/ Begrn and ends with End/Stop Step as shown below. In between steps of an algorithm from Begin to End has must follow any of the types such as Sequence, Selection or Iteration. Each and every algorithm has a name so we should place it at the top/ before start Step of an algorithm. We can also put comments for the steps of an algorithm whenever an instruction/ statement of an algorithm is complex.
/Alame of the algorithm Step L: StarU Begin Step 2: ....:... Step 3:
(comments)
Step n-1: Step n: Stop/End
Twes of an aleorithm: The steps of an algorithm is not only limited to a linear sequence of statements. During it is process it may diverge, repeat code or take decisions. For these pu{poses, control structures specify what has to be done to perform an algorithm. An algorithm statement that effects the order in which statements are executd or that effects whether the statements are executed, are called control structures. It affects the flow of controi-
Control structures are used to express algorithms, flowcharts, and pseudo codes as actual computer programs. Essentially there are three types of algorithms:
l.
Sequence Algorithms
2. Selection Algorithms 3. Iteration Algorithms
T
Sequence Algorithms: Sequence Algorithms follows the sequence control
stnrcrer-br--
nhere the
information flows in a straight line.
Hcode
Flowchart
br &-2
Action n The actions are performed in the same sequence (Top to bottom) in which they are written. Example: Simple sequence control structure that adds two numbers. Selection Algorithms: Selection Algorithms follows the Selection control structure as shown below. It allows a choice between two alternative paths, whether it is true or false. The first statement of a selection structure is a conditional statement. Once the sequence of steps in the selected path has been carried out, the paths are rejoined and then next instruction is carried out. Thus the selection structure has only single entry and single exit. Example: Selection control structure to find out larger of two numbers.
Flow chart
If condition
Pseudocode
If (.onAition
is true) THEN
List of actions ELSE
true?
List of different actions End-if Iteration Algorithms: lterative or repetitive Algorithms use the iterative control structure, which causes the intemrption to normal sequence of processing" It directs the system to loop back to previous statements, repeating the same sequence over and again, usually with new data.
When sequence of statements is repeated against a condition, it is said to be in a loop. Using looping the programmer avoids writing the same set of instructions again. The looping process may be one time or more times until the desired output is obtained with
inasingleprogram. Example: Iterative control structure to print first 10 natural numbers. pseudocode
Flowchart
REPEAT Sequence
I
Sequence 2
Sequence n
LJNTIL Condition is false Sequence Example #
Algorithm to find out sum of two (a' b) numbers
Step 1: Begin Step 2: Read the numbers a, b Step 3: Compute the sum of a, b Step 4: Store the result in c Step 5: Print c Step 6: End
#Algorithm to find out average of four numbers (p' q' r' Step 1: Begin Step 2: Read the values
ofP, q, r &
Step 3: Add the values of p, q, r
&
s
s
Step 4: Store the result in the variable 'sum' Step 5: Divide the sum by 4 St€p 6: Store the result in variable Step 7: Print avg
Step 8: End
'avg'
s).
Eil
Selection Examples: #
Algorithm for smallest among three
Step 1: Begin Step 2: Read a, b, c Step 3:
If
a0 and y max then
then go to step 9 assign n to max
Step 8: Increment count
by I
Step 9: Print max
Step 10: End
A Flow chaft is a blueprint for an algorithm. A Flow chartis a diagrammatic or pictorial representation of an algorithm.
A "Flow Chart" is a Snap Shot of our Process of solving a problem A " Flow Chart" is a Zoom
I
Lens
for your Business Pracesses.
(Dictionary) A schematic representation of a sequence of operations, as in a manufacturing process or computer program.
I
(Technical) A graphical rqrresentation of the sequence of operations in an information system or program. Information system flowcharts show bow data flows from source documents through the computer to final distribution to users. Program flowcharts show the sequence of instructions in a single program or subroutine. Different symbols are used to draw each tlpe of flowchart.
A Flowchart can
E E tr
shows logic of an algorithm emphasizes individual steps and their interconnections e.g. control flow from'one action to the next
TABLE OF F'LOWCIIART SYMBOLS I$}Ef ol,iilt.li!i'!:'.i:=,iiilrl"=,,,rr1:.,=ii.'$@._-$
,,1,1
n: ffi
Symht{ii Desoiytion
,
(alias) Terminator (Terminal Point, Oval)
*' utt "
This symbol is used to indicate where the flowchart begins or ends. When used to start it is labeled "start "and the label "end'7'stop"is used at the termination of the flowchart. A flowchart should always begin and end with this
synbol. Process
Show a Process or action step. This symbol is used forrepresenting arithmetic and data movement instructions. It can represent a single step('add 2 cups of flow')or an entire sub-
(make bread') with in a larger process. This is the most common symbol in both process flowcharts and business process maps. process
.c:3-
Data Input/Output
The Data flowchart shape indicates inputs to and outputs from a process. As such, the shape is more often referred to as an VO shape than a Data shape.
r***-*-*-fb
g
F6;L#*
Flo*]i"; il;""io.s
(Arrow,
process flows.Flow lines are used to connect
Connector)
symbols. These lines indicate the sequence of steps and the direction offlow ofa process.
Decision
Decision symbol denotes a decision (or branch) to be made. The program should continue along one of the two routes (IF/ELSE). This symbol has one entry and trvo exit paths. The path
{iffi
chosen depends
Annotation
srto* trte ai.".iion CIat itt"
on whether
if iJ"reo'io p.o"iae
;ddiiil;i ilio.-tai"n
about another flowchart symbol. The content may be in the form of descriptive comments, reinarks or explanatory notes.
Connector
(Inspection)
Connectors are usual'ly labeled with capital letters (A, B. AA) to shorv matching jump points. They are handy for avoiding florv lines
OI
that cross other shapes and flow lines. They are also handy forjumping to and from a sub-
On-page
process defined in a separate area than the main
connector
flowchart. [Just to confuse things further, same people will use a circle to indicate an operation and a square to indicate an inspection. That's why it's irnportant to include a symbol key in the
flov'chart.J Off-Page Connector
Or
Off-Page Connector shows continuation of a process flowchart onto another page. When using them in conjunction with Connectors, it's best to differentiate the labels, e.g. use numbers for Off-Page Connectors and capital letters for Connectors. In actual practice, most flowchads just use the Connect shape for both on-page and off-page references. The logical Or symbol shows when a process diverges - usually for more than 2 branches. When using this symbol, it is important to label the out-going flow lines to indicate the criteria to follow each branch.
Summing Junction
The logical Summing Junction flowchart shape is shows when multiple branches converge into a single process. The merge symbol is more common for this use, though. This symbol and the Or symbol are really more relevant in data processing flow diagrams than in process
flowcharts. Document
Pretty self explanatory - the Document flowchad symbol is for a process step that produces a document.
ai Docu.ent, except, well, multiple
Multi-
Same
Document
documents. This shape is not as commonly used as the Document flowchart shape, even when
multiple documents are implied. Display
h'dia;#
#*Gft
"fit#l"f6rrnutior
it
displayed to a person (e.g., PC user, machine operator).
ffi
ffi
Manual lnput
Manual Input flowchad shapes show process steps where the operator/ user is prompted for information that must be manually input into a system.
Card
This is the companion to the punched iape flowchart shapes. This shape is seldom used.
n
ffi -"
{fff*dtu&?r;"
Ifyoute very
Stord Data
e
-*--ffis'ai"
P***-'t tiT{
t"*****#
ffiwry---* ti,,-u
g"t*irbiti
Sto*ag.i
n*r.ltat tlttpt tt"d
for any process st€p that stfr€s data
Lq \**s*
I
good at stretching all the life out of a maching you may still have use for the Punched Tape symbol - usd fc input into old computers and CNC machines.
Punched Tape
I
*
tr,"rnoJi u"iuoJirii iec"gitore "vmot
Disk
data storage location, this
(Database)
depicts a database.
flowchrt
fr
a
$ry
adi#ftn":t*ay tf ttYi"g
--
Storage
Hard Drive'
Process
indepe'ndently defined process' To reduce complexity, some gtoup of instructions is specifred elsewhere as a function or subroutine'
(Subroutine)
which can be called for execution using this sYmbol.
uirlelines for Prep*ring Florvcharts a flowchart: The following guidelines should be used for creating S
1.
2. 3.
The flowchart shouldbe clear, neat, and easyto follow' The flowchart must have a logical start and finish' should be listed in logical In drawing a propef flowchart, all necessary requirements order.
4. The direction 5.
or top to of the flow of aprocedure should always be from 1eft to right
bottom. Only one flow line should come out from a process syrnbol'
of
6.
two or three flow lines Only one flow line should€nter a decision synbol. However, (one for each possible answer) may leave the decision symbol. :
7. Only one flow line is used with a terminal symbol' t
+
I
Or
8.
Within standard symbols, write briefly. If necessary, use the annotation symbol to describe data or process more clearly.
lThi.
e
I
g. In case of complex flowcharts,
pt**s will add two numbers
and store the value in SUM
connector slmrbols are used to reduce the number
of
flow lines. 10. Intersection of
flow lines should be avoided to make it
a more effective and better
way
of representing communication. 11. It is useful to test the validity of the flowchart by passing through it with normaVunusual test data.
Benefits of a Flow chart: are currently working and also find outs the key elements of a process by drawing clear lines between the end of one process and the start of next one.
A flowchart helps to clarifu how things
/ {
Makes Logic Clear: A flowchart makes logic clear. Communication: It is the better way of communicating the logic of a system to all concerned.
Efrective Analysis: A proble,m can be analyzed in an effective u'ay by using a flowchart. Useful in Coding It is acting as a guiCe or blueprint during the analysis and program development phase.
Proper Testing and Debugging: By nature the flowchart helps in detecting the errors in a program, shows exactlywhat the logic should do. Appropriate Documentation: Flowcharts serve as a good proglam documentation tool. Limitations of
,/ r'
a
Flowchart:
Complex: when a program is very large the Flowchart tend to be large quickly and it is difficult to follow. Costly: If flowcharts are to be drawn for a huge application, the time and cost factor of program development may get out ofproportion, making it costly.
Difficult to Modify:
Due to its synbolic nature, any changes or rnodifrcations to a flowcharl usually require redrawing the entire logic again, and redrarving a complex flowchart is not a simple task.
No Update: Usually programs are updated regularly. However the corresponding update of flowcharts may not take place, especially in the case of large programs. As a result the logic in the program
PSETIDOCODE:
'*
Pseudo code (pronounced as soo-doh-kohd) made up two words: pseudo and code. Pseudo means imitation and code refers to instructions, written in programming languages.
r*
Pseudo code is not real proqramminq code but
'a&.
It is eeneric wa)' of describine an aleorithm without using any specific programming
it is look like a programming
code.
language related notations.
+ *
Simply, we can say that it is an outline of a proqram written in the form i.e. easily converted into real programming statements. It uses plain Enelish like statements rather than symbols to represent the process of computer program
,*
It is also known as PDL (Program Design Language).It emphasis more on the design aspect of a computer program or structured English because usually pseudo instructions are written in normal English like statements but in a structured way. x& It is somewhat halfway between English and a programming language. sk The goal of writing pseudo code is to provide a high level description of an algorithm. It also suppresses many of the details that are insignificant. qL Example: Pseudocode to calculate an area of a rectangle PROMPT the user to enter the height of the rectangle PROMPT the user to enter width of the rectangle COMPUTE the area by multiplying the height with width
DISPLAY the area STOP *jl& Pseudocode uses some keywords to denote programming process
.f. Input : READ, OBTAIN,
{. * * *
GET, and pROMpT Output : PRINT, DISPLAY and SHOW Compute : COMPUTE, CALCULATE. and DETERMINE Initialise : SET and INITIALISE Add One : INCREMENT
t
Since, Pseudocode is detailed yet readable, and programmers.
+
Once pseudocode is accepted,
""&.
it can be inspected by the tearn of designers
it is transformed into actual program code using the
vocabulary and syntax of the chosen programming language. The benefit of pseudocode is that it enables the programmer to concentrate on the algorithms without worrying about all the syntactic details of particular programming language.
Benefits of a pseudocode:
* * * *
Pseudo code is language independent so
it
can be use by most programmers
It is easier to develop a program from a pseudocode than with a flowchart. It is easy to translate pseudocode into a programming language, this can be accomplished by less experienced prograrnmers. Unlike flowcharts, pseudocode i5 sompact and does not tend to run over many pages. It is a simple structure and readability makes it easier.
*
The main disadvantage of using pseudocode is that representation of the program's logic.
*
There are no accepted standards for writing pseudocodes. Programmers use their own style of writing pseudocode.
a
Pseudocode cannot be compiled and not be executed, and there are no real formatting or syntax rules. It simply one step, an important one, in producing the final code.
it does not provide visual
fnere
are
diferent wavs
1. 2. 3. 4.
Step form Pseudo code
Flow chart
Nassi-Shneiderman Step-form: o Problem solved with written statements. o One statement is logically related to preceding statement. o Each statement performs an action.ie solves apart of problem together these statements complete the solution.
'Why learn about programming?
,:il'.:1. -:a,..,::t:
t:i-
a
friends though!)
a a
Programming will helP You
o
So really,
why learn iA;9ut
machine, which i5,,,,,,
.h ,,.,..
will
T (l
// Write an Algorithm and Flow chart for making
a tea
Begin Step 1: Boil water. Step 2: Put tea powder in the kettle. Step3: Pour boiled water in the kettle.
Stq4: Wait for three minutes. Step5: Boil milk. Step6: Put boiled milk in a cup. StepT: Add sugar to the cup. Step8: Empty the kettle in the cuP.
Step9: Stii the cup with a spoon. End
Flow Chart for the above algorithm:
Put tea powder in the kettle
Pour boiled water in the kettle
Wait for three minutes
Put boiled milk in a cup
Add suear to the cup
Empty the kettle in the cup
Stir the cup with a spoon
Example 1:
//Algorithm to find whether a student has to pass or fail by reading four subjects marks. Begin
Ml, M2, M3, M4
Step 1:
Input
Step 2:
GRADE
Step 3:
if (GRADE 0 then calculate sqrt(d)/2iandstore calculate r 1 :real*imag and tT:real-imag Siep 11: Otherwise print "Roots are imaginary arrdrl't2" Step 12: end-if Step 13: end-if Step 14: end-if Step 15: StoP
FLOWCHART:
Read a,b,c
Print "equation is lineaC'
Print "roots are real & Equal" Print real
Rl: (-b+sqrt(d)l2a P2: (-b-sqrt(d))/2a
d:_d
imag: sqrt(d)/2a
rl :
real* imag 12: real- imag
Print "roots are real& uffeal" Print r1 & 12
Print'toots are imaginary''Print
rl
and12
FLOWCHART:
Print'oequation is linear"
Print "roots are real & Equal" Print real
P1: (-b+sqrt(d)Y2a R2: (-b-sqrt(d)l2a
d:_d
imag: sqrt(dl2a
:
real* imag 12: real- imag
r1
Print'oroots are real& unreal" Print 11 & 12
Print "roots are imagina4y''Print rl andr?
SUMMARY of Proerammins Lanzuases The Evolution of Programming Languages
To build programs, people use languages that are similar to human language. The results are translated into machine code, which computers understand. Programming languages fall into three broad categories:
.
Machine languages
.
Assembly languages
.
Higher-level languages
The Evolution of Programming Languages
-
Machine Laneuages Machine languages (first-generation lanzuaees) are the most basic type of computer languages, consisting of strings of numbers the computer's hardware can use.i.e. the program is in binary form 0's and I's.
Different types of hardware use different machine code. For example, IBM computers use different machine language than Apple computers. i.e. it is a Machine dependent language.
The Evolution of Programming Languages
-
Assembly Languages Assembly languages (second-generation lanzuaees) are only somewhat easier to work with than machine languages" To create programs in assembly language, developers use cryptic English-like phrases called mnemonics (: an abbreviated OPeration CODE) to represent strings of numbers. The code is then translated into object code, using a translator called an assembler.
4
!r:i.{A* s$ns{il $$lrs illgs
f,Li: fi*u
*X,*6BS{
+tstt 88.3$
8Si' S)t,$$$$
;scR0r.L
sc*ttlt
:ln*t
Ass**:h{y
;f0IIT I0
il{$*f Sr*lt$ Stfsfo
t*u nlt,t*tfll ;I0 24,79 tltT 1*l* if,ell 8t0si rlf * sl*ll{i itleurlllih t{ft, !{u r$.mlf iliful BIQUIST Lf$ sr{.8$ffft
SUPFF'|
^^/s^ {'rJLlg
txf ?ttl :f,nll S0$ :*Ftlt*ll f'*$t S***0$rIlS l* a*t* i $tsfLit 5f*rr{i r* $tt{st{ s$li l4l{r *fi,$* ;}Is}lit *f{uFsl Lf* SX,$TBII* :F{l|{l I* SInI|ie t$? ?1$ ;ln* los n{? i*f,tglil F*$tt lttl$
Asseryrhl*r
Fnt!3]..|r3!nr, trlr 3'l tttl *t *"t tstl s ttrtrr arfrar tr artt tltttl trt $1 tta, fit $ srfiE trfr*rntrlir3rlr0tEr'r't?1**$ l Btat Fl ftttttttt ?{tttt 3t ftEl t1't*'l t I trlttFrFrlsratllltltrrrarsrtl te|}1c f*'taFrltttttattrltttHtar?r tl1'lsts 1*tttltttt'1tBtft||llnfi rtftttll tl *tl ss{l}tSFtttlSrttlt'ltltrflfttlfi 0s$'l 0
Sbject code
There is a one-to-one correspondence betvzeen assembly language program and the machine language program.
The Evolution of Programming Languages Hiqher-Level Lanzuaqes
HigherJevel languages are more powerful than assembly language and allow the programmer to work in a more EnglishJike environment. Higher-level programming languages are divided into three "generations," each more powerful last: than the a
c o
Third- generation languages Fourth- generation languages Fifth- generation languages
Higher-Level Languages Third-Generation Lanzuases . Third-generation languages (3GLs) are the first to use true English-like phrasing, making them easier to use than previous languages"
3GLs are portable, meaning the object code created for one type of system can be translated for use on a different tlpe of system.
-
The following languages are 3GLs:
FORTAN, COBOL, BASIC, Pascal , C, C++, Java,ActiveX ...
Higher-Level Languages Fourth-Generation Lansuases Fourth-generation languages (4GLs) are even easier to use than 3GLs. 4GLs may use a text-based environment (like a 3GL) or may allow the programmer to work in a visual environment, using graphical tools. The following languages are 4GLs:
Visual Basic (VB), Visual Age and Authoring environments
Higher-Level Languages Fifth-Generation Languases Fifth-generation languages (5GLs) are an issue of debate in the programming community - some prografirmers cannot agree that they even exist. These high-level languages would use artificial intelligence to create software, making 5GLs extremely difficult to develop. Solve problems using constraints rather than algsritluns, used in
Prolog
Features of good programming language: Ease
ofuse
Portability Naturalness for the application
Reliability Safety Performance Cost
Promote strucfural programming
Artificial Intelligence
I
I
Cornpact code
Maintainability Reusability Provides interface to other languages
Concurrency suppofi Standardization
Types of programming language
BASIC
are Hundreds of high level languages have been developed and designed alnong these which is (Beginner, All purpose Symbolic Instruction code) FORTRAN, COBALT,
PASCAL, DBASE, C-Language JAVA etc. FORTRAN (Fortran Translator) was developed by IBM Corporation between 1954 and mathematical 1957 to be used for scientific and engineering application that require complex coml.iutation but it is a text base programming language'
Dennis Richie
in
1972
at Bell laboratories developed a C- programming language, C
language is a very popular package among the computer user,
it was first
used
to develop the
UNIX Operating system. C* is an extension of C, developed by Bjarne stroustrup in the early C language 1980,s at Bell laboratories. C* provicles a number of features that " spruce up" the people fiast the capabilities for doing so called object- oriented programming (OOP) Many the believe that (OOP) can greatly improve the software development process C* has become
dominant system implementation language. Java was developed
by SUN Micro system and released in 1995. Java is based on C and
and incorporates a number of features from other object oriented language" Java includes access extensive libraries for doing multimedia, networking, multi reading graphics data base
C*
and much more. Microsoft version
visual
of Java is called visual J* many people believe that Java and
J* will be the most significant
long-term competitor to Visual Basie'