Ehb208e 3
Ehb208e 3
BLG221E
Algorithm
s
BLG221E
ALGORITHMS AND FLOWCHARTS
• Implementation phase
– implement using a programming language
Steps in Problem Solving
Pseudocode of algorithm:
Input a set of 4 marks
Calculate their average by summing and dividing
by 4
if average is below 60
Print “FAIL”
else
Print “PASS”
The Flowchart
Flowchart is another algorithm representation but graphical.
A flowchart must have a one START
start and one stop
Steps in a flowchart must Input
M1,M2,M3,M4
connect. Can’t leave a step
“hanging” with no
connection. GRADE(M1+M2+M3+M4)/4
N IS Y
GRADE<60
PRINT PRINT
“PASS” “FAIL”
STOP
Flowchart Symbols We see some of the
most common
Name Symbol Use in Flowchart
flowchart symbols in
this picture.
Oval Denotes the beginning or end of the program
START
Algorithm:
Step 1: Input a, b, c Input
a, b, c
Step 2: d sqrtb
( b 4 a c )
Step 3: x1 (–b + d) / (2 x a) d sqrt(b x b – 4 x a x c)
Step 4: x2 (–b – d) / (2 x a) x (–b + d) / (2 x a)
1
Print
x1 ,x2
STOP
Example 2 (Your job)
Draw the flowchart of the factorial calculation.
Example 3 (Your job)
Draw the flowchart of finding the smallest element of the
given list.
THREE CONSTRUCTS
Computer scientists have defined three
constructs for a structured program or
algorithm.
Summation Sorting
Product
Smallest and
largest
Summation Algorithm
One commonly used algorithm in computer science is
summation. We can add two or three integers very easily,
but how can we add many integers?
The solution is simple: we use add operator in a loop.
Example:
• the factorial function
6! = 6 * 5 * 4 * 3 * 2 * 1
We could write:
6! = 6 * 5!
Example 2: factorial function
In general, we can express the factorial
function as follows:
n! = n * (n-1)!
Is this correct? Well… almost.
n! = 1 (if n is equal to 1)
n! = n * (n-1)! (if n is larger than 1)
Factorial function
For certain problems (such as the factorial
function), a recursive solution often leads to short
and elegant code. Compare the recursive solution
with the iterative solution:
Recursive solution Iterative
solution
int fac (int numb){ int fac (int numb) {
if(numb<=1)
return 1; int product=1;
else
return numb*fac(numb- while(numb>1)
1); {
} product
*= numb;
numb--; }
return product;
Recursion
We have to pay a price for recursion:
calling a function consumes more time and memory
than adjusting a loop counter.
High performance applications (graphic action games,
simulations of nuclear explosions) hardly ever use
recursion.
In less demanding applications recursion is an
attractive alternative for iteration (for the right
problems!)
Recursion
If we use iteration, we must be careful not to
create an infinite loop by accident:
Oops!
No
terminatio
n condition