ALGORITHMS & FLOWCHARTS
WHAT IS AN A LG O RITHM ?
A n algorithm is “ a finite set of precise (clear
& specific) instructions for performing a
computation or for solving a problem”
• A computer program is an algorithm written in
a programming language
All programs are algorithms
Not all algorithms are programs!
• Examples
Directions to somebody’s house is an algorithm
A re c ip e for c oo king a c a ke is a n a lg orithm
The steps to compute the cosine of 90° is a n
algorithm
ALGORITHMS
• A tool for solving a well-
specified computational
problem
Input Algorithm Output
• Algorithms must be:
• Correct: For e a c h input p ro d u c e a n
appropriate output
• Efficient: run as quickly as possible, a n d use as
little memory as possible – more about this later
PROPERTIES OF ALGORITHMS
• All Algorithms share following properties:
• N e e d Input
• Produce Output
• Definiteness – the steps are defined precisely
• Correctness – should produce the correct
output
• Finiteness – the steps required should b e finite
• Effe c tive ne ss – e a c h ste p must b e a b le to
b e performed in a finite amount of time
• Generality – the algorithm should b e
applicable to all problems of a similar form
ALGORITHMS - EASY &
HARD
• Some are easy
• Finding the largest (or smallest) value in a list
• Finding a specific value in a list
• Some are a bit harder
• Sorting a list
• Some are very hard
• Finding the shortest path between Jaipur a n d
Manali
• Some are essentially impossible (at least
with current technology)
• Factoring large composite numbers
PROBLEMS AND ALGORITHMS
• We n e e d to solve a computational problem
• “Convert a weight in pounds to Kg”
• A n algorithm specifies how to solve it, e.g.:
• 1. Read weight-in-pounds
• 2. C a lc ula te we ig ht-in-Kg = we ig ht-in-p o und s
* 0.455
• 3. Print weight-in-Kg
• A c o mp ute r p ro g ra m is a c o mp ute r-
executable description of a n algorithm
GREATEST C O M M O N DIVISOR
• The first recorded algorithm - Euclid’s
algorithm for finding the greatest c o m m o n
divisor (GCD) of two natural numbers
• Definition: The G C D of two natural numbers x, y
is the largest integer j that divides both
(without remainder), i.e., mod(j, x)=0, mod(j,
y)=0, a n d j is the largest integer with this
property.
• The G C D Problem:
• Input: natural numbers x, y
• Output: GCD(x,y) – their G C D
ALGORITHM 1:
WELCOME MESSAGE
Algorithm to print a welc o me message.
I NPUT: na m e o f the use r
OUTPUT: Customized w e l c o m e message
BEGIN
1. PRI NT “ Ente r Yo ur Na m e : “
2. I NPUT Na m e
3.Print “Wel com e to programming “, N a m e
END
8
ALGORITHM 2:
ARITHMETIC
Algorithm to input and perform different
arithmetic operations on them.
INPUT: numbers A a n d B
OUTPUT: Result of operations +, -, *, /, a n d
M O D BEGIN
1. PRINT “Ente r two numb e rs: “
2. INPUT A , B
3. C ← A + B
4. PRINT “Sum: “, C
5. C ← A - B
6. PRINT “Diffe re nc e : “, C
Contd.
9
ALGORITHM 2:
7. C ← AARITHMETIC
*B
8. PRINT “Prod uc t: “, C
9. C ← A / B
10. PRINT “Division Quotient: “, C
11. C ← A M O D B
12.PRINT “Division Remainder: “, C
END
10
ALGORITHM 3: SCALE
CONVERSION
Algorithm to convert temperature in degree Celsius
to degree Fahrenheit.
INPUT: Temp in degree-Celsius C
OUTPUT: Temp in degree-Fahrenheit F
BEGIN
1. PRINT “Enter Temperature in
Degree-Celsius: “
2. INPUT C
3. F ← 1.8 * C + 32
4. PRINT “Te mp e ra ture in De g re e -Fa hre nhe it :
“ , F END
C o ntd .
11
DECISION MAKING BY
•
BRANCHING
When w e n e e d to choose from more than one alternate
paths, w e have to make a decision.
• This situation comes in real life many times. These choices
are mutually exclusive, i.e., only one alternative c a n b e
chosen.
• For example:
• When deciding on the dress to wear in the morning.
• When deciding on which restaurant to dine out at.
• Decision making c a n b e depi cted by branching
12
DECISION MAKING BY
BRANCHING
Types of Decision-making statements
• IF-ELSE
• SELECT-CASE
IF
sta te me nt-
1
sta te me nt-
2
IF
(C o nd itio n)
, THEN
sta te me nt- 13
3
DECISION MAKING BY
BRANCHING
IF-ELSE
sta te me nt-
1
sta te me nt-
2
IF
(C o nd itio n)
, THEN
sta te me nt-
3
sta te me nt-
4 14
ELSE
ALGORITHM 4:
EVEN/ODD NUMBERS
Algorithm to find if a given number is even or
odd.
INPUT: Numb e r
Num OUTPUT: Test
result BEGIN
1. PRINT “Ente r a
numb e r: “
2. INPUT Num
3. IF (A M O D 2 =
0), THEN
1. PRINT Num,
“ is e ve n
numb e r.”
4. ELSE
15
DECISION MAKING BY
Nested IF-ELSEBRANCHING
statement-1
IF ( c ond ition-1 ), THEN
IF ( c ond itio n-2 ),
THEN statement-
2
ELSE
sta te me nt-
3 END-IF
ELSE
sta te me
nt-4
sta te me nt-
Statement-6 16
5
ALGORITHM 5:
LEAP YEAR
Algorithm to find if a given year is a leap year or not.
INPUT: Ye a r Y
OUTPUT: Test result
[A century year is said to leap year if it is divisible by 400, and a
non- century year is a leap year if it is divisible by 4]
C o ntd .
17
ALGO. 5.1: LEAP YEAR –
BEG I
NESTED IF-ELSE
N
1. PRINT “Enter a year:
2. “ INPUT Y
3. IF (Y M O D 100 == 0), [century year, test M O D 400]
4. THEN [leap year]
5. IF (Y M O D 400
6. ==
ELSE0), THEN
7. PRINT Y, “is a regular year.”
8. l e a p year.”
END-IF
9. ELS [a non-century year, test for M O D
10. E IF (Y M O D 4 == 0), 4]
11. THENPRINT Y, “ is a l e a p
12. ELS year”
13. E PRINT Y, “ is a regular
14. END-year”
15. IF END-
END IF
18
DECISION MAKING BY
BRANCHING
Staircase IF-ELSE
statement-1
IF ( c ond ition-1 ),
THEN statement-
2
ELSE-IF ( c o nd itio n-2 ),
THEN statement-3
ELSE-IF ( c o nd itio n-3 ),
THEN statement-4
END-IF
Statement-5 19
DECISION MAKING BY
BRANCHING
Joining Conditions in IF-ELSE
1. AND
IF ( c ond ition-1 A ND c o nd itio n-2 ),
THEN statement-1
END-IF
2. OR
IF ( c ond ition-1 O R c o nd itio n-2 ),
THEN statement-1
END-IF
3. NOT
IF ( NO T c o nd itio n-1),
THEN statement-1
END- 20
IF
ALGO. 5.2: LEAP YEAR –
BEG I
STAIRCASE IF
N
1. PRINT “Enter a year:
2. “ INPUT Y
3. IF (Y M O D 100 == 0 [leap
4. A NDPRINT
Y M OY,
D “is
400a ==
l e a p year.” yea r]
5. 0), THEN
ELSE- IF (Y MOD 4 == 0), THEN [non-century
year]
6. PRINT Y, “ is a l e a p year”
7. ELSE
8. PRINT Y, “ is a regular year”
9. END-IF
END
21
DECISION MAKING BY
BRANCHING
SELECT-CASE
SELECT ( value )
CASE 1st-constant:
statement-1
CASE 2nd-constant:
statement-2
CASE 3rd-constant:
statement-3
CASE ELSE:
e lse -sta te me nt-
1 END-SELECT
22
ALGORITHM 6: FINDING
WEEKDAY NAME
Algorithm to find the name of the weekday, given its day number
in the week. Sunday is day 1 in the week.
INPUT: Weekday number N between 1 a n d 7
OUTPUT: Weekday n a m e between Sunday a n d Saturday
Using SELECT-CASE Using Ladder/Staircase IF-
ELSE
BEG I
1.
BEGIN PRINT “ Ente r we e kd a y num b e r: N 1. PRINT “ Ente r we e kd a y num b e r:
2. “ INPUT N 2. “ INPUT N
3. SELECT ( N ) 3. IF( N == 1), THEN
4. C A SE 1: 4. PRINT “ Sund a y”
5. PRINT 5. ELSE-IF( N == 2),
6. “ Sund a y” CASE 2: 6. THEN
7. PRINT 7. PRINT
8. “ M o nd a y” CASE 3: 8. “ M o nd a y” ELSE-
9. PRINT IF( N == 3), THEN
“ Tue sd a y” PRINT
C o ntd .
23
“ Tue sd a y”
ALGORITHM 6: FINDING
Using SELEC T-CWEEKDAY
ASE NAME
Using Ladder/Stairc ase IF-
ELSE
10. CASE 4: 9. ELSE-IF (N == 4), THEN
11. PRINT “Wednesday” 10. PRINT “Wednesday”
12. CASE 5: 11. ELSE-IF (N == 5), THEN
13. PRINT “Thursday” 12. PRINT “Thursday”
14. CASE 6: 13. ELSE-IF (N == 6), THEN
15. PRINT “Friday” 14. PRINT “Friday”
16. CASE 7: 15. ELSE-IF (N == 7), THEN
17. PRINT “Saturday” 16. PRINT “Saturday”
18. CASE ELSE: 17. ELSE
19. PRINT “Illegal input” 18. PRINT “Illegal input”
20. END-SELECT 19. END-IF
END END
The SLECT-CASE m a y take more typing effort, but on execution, it takes
less s p a c e a n d is far more efficient than c o m p a ra b l e IF-ELSE.
SELECT-CASE c a n b e used ONLY for: (a) Equality, (b) Between a variable
a n d a CONSTANT, (c) of Type Integer (in some cases Strings).
2
4
REPETITIVE
EXEC UTIO N BY
•
LO O PING
When a task needs to b e executed repetitively.
• The steps are exactly the same, only the values may change.
• Iteration or Loops are used for repeating instructions:
• Counter-driven: for a finite number of times; or
• Conditional: till a condition is met.
• When the count is over or the condition no longer holds,
the loop terminates
• For example,
• Counter-driven: For all students in the class, take the a tt e n d a n c e
of o n e student at a time
• Conditional: Va c c i n a t e a n eligible persons in the community.
Is any o n e left, repeat the process.
25
REPETITIVE
EXEC UTIO N BY
• Three basic loopLO O PING
types:
• While loop – continue the execution until the condition b e c o m e s false
• For loop – usually counter driven with specified number of times
• Do-While – like while, but with condition testing after the loop is executed
at least once.
• While a n d For loops are entry-control loops. Test the condition
for truthfulness before the loop is entered even for the first time.
• Do-While loop is a n exit-control loop. Test the condition for
truthfulness
after e a c h iteration of the loop to see if re-entry is required.
WHILE loop
statement-1
WHILE ( condition ),
D O statement-2
statement-3
END-DO
26
REPETITIVE
EXEC UTIO N BY
FOR loop
statement-1
LO O PINGFOR loop
statement-1
FO R ( I = 1 to N ), FO R ( I = 1 to N, STEP J ),
DO DO
sta te m e nt- sta te m e nt-
2 2
sta te m e nt- sta te m e nt-
3 3
END-FOR END-FOR
(defa ult step of Step J co u ld b e +ve or –
ve, a n d of any magnitude
+1) DO-WHILE
loop statement-1
DO
27
sta te m e nt-
ALGORITHM 7.1: ADDING FIRST
N NATURAL NOS.
•Algorithm to find the sum of first N natural numbers. The
value of N is entered by the user. Use While loop.
•INPUT: N as count
of natural numbers
1. PRINT “Enter the number of terms:
2. “ OUTPUT:
INPUT N Sum
3. SUM ← 0 [Initialize the sum to Zero]
4. I •←
BEGIN
1 [Initialize the c ounter to
5. WHILE ( I <= N ), one]
6. DO SUM ← [Add c urrent value of I
SUM + I to previously
7. I←I+ c a lc ulated sum]
8. 1
END-DO [Update the counter]
9. PRINT “ Sum o f first “ , N, ” na tura l num b e rs is: “ ,
END SUM
C o ntd .
28
ALGORITHM 7.2: ADDING FIRST
N NATURAL
•Algorithm to find the sum of firstNOS.
N natural
numbers. The value of N is entered by the
user. Use For loop.
•INPUT: N
as count of
1. natural
PRINT “Enter the number of terms:
2. “ INPUT N
3. numbers
SUM ←0 [Initialize the sum to Zero]
4. FOOUTPUT:
R ( I ← 1 to N ), [Initialization, Test, and
DO Update,
a ll a t one plac e]
5. Sum
SUM ← SUM + [A d d c urre nt va lue o f I to
I previously c a l c u l a t e d
6. END-FOR
•BEGIN sum]
7. PRINT “ Sum o f first “ , N, ” na tura l num b e rs is: “ ,
END SUM
C o ntd .
29
ALGORITHM 7.2: ADDING FIRST
N NATURAL NOS.
•Algorithm to find the sum of first N natural numbers. The
value of N is entered by the user. Use Do-While loop.
1. PRINT “Enter the number of terms:
2. •INPUT:
“ INPUT N N as count
3. [Initialize the sum to Zero]
4.
ofSUM
I←
←0
natural numbers [Initialize the c ounter to
5. OUTPUT:
1 Sum one]
6. DO [Add c urrent value of I
•BEGINS to previously
7. U
I←I+ c a lc ulated sum]
8. WHILEM
1 ( I <= N [Update the counter]
9. ) RINT “ Sum o f first “ , N, ” na tura l num b e rs is: “ ,
P
END SUM ←
30
S
ALGORITHM 8.1:
Algorithm to find test if a given number is Prime or Composite. A prime number
CHECKING FOR PRIME
is divisible by 1 and itself, i.e., it has only two factors.
INPUT: N the num b e r to te st
NUMBER
O UTPUT: Re sult if N is Prim e o r C o m p o site
BEGIN
1. PRINT “ Ente r the num b e r: “
2. INPUT N
3. Flag ← TRUE [Flag == TRUE for Prime, FALSE otherwise, Initially
Assume prime]
4. I ← 2 [Initialize the C ounter I to 2]
5.WHILE ( I REM
<= N←),NDOMOD I [Find remainder using MOD]
6. IF (REM == 0), [Another fac tor, disc ontinue
7. THEN testing]
8. Flag ← FALSE [Update Flag to indicate another
9. BREAK factor] [Jump out of the loop]
10. END-IIF
11. I←I+1
[Update the
counter]
12. END-DO
13. IF (Fla g == TRUE),
THEN
14. PRINT N, “ is
C o ntd .
31
Prim e
num b e r”
ALGORITHM 8.2:
Algorithm to find test if a given number is Prime or Composite. A prime number is
CHECKING FOR PRIME
divisible by 1 and itself, i.e., it has only two factors. An Efficient Algorithm
Strategy.
NUMBER
INPUT: N the num b e r to te st
O UTPUT: Re sult if N is Prim e o r C o m p o site
1.
BEGINPRINT “ Ente r the num b e r: “
2. INPUT N
3. Flag ← TRUE [Flag == TRUE for Prime, FALSE otherwise, Initially Assume
3. I←2 prime] [Initialize the C ounter I to 2]
4. WHILE ( I <= Floor(N/2) ), DO
6. REM ← N M O D I [Find remainder using MOD]
7. IF (REM == 0), THEN [Another fac tor, disc ontinue
8. Flag ← FALSE testing]
9. BREAK [Update Flag to indicate another
10. END-IIF factor] [Jump out of the loop]
11. I←I+1 [Update the
12. END-DO c ounter]
13. IF (Fla g == TRUE), THEN
14. PRINT N, “ is Prim e num b e r”
15. ELSE
16. PRINT N, “ is C o m p o site
num b e r”
17.END-IF
C o ntd .
32
END
ALGORITHM 8.2:
Algorithm to find test if a given number is Prime or Composite. A prime number is
CHECKING FOR PRIME
divisible by 1 and itself, i.e., it has only two factors. An Even More Efficient Algorithm
Strategy.
NUMBER
INPUT: N the numb e r to te st
OUTPUT: Result if N is Prime or Composite
BEGIN
1. PRINT “ Ente r the numb e r: “
2. INPUT N
3. Flag ← TRUE [Flag == TRUE for Prime, FALSE otherwise, Initially
Assume prime]
4. FO R ( I ← 2 TO Floor( Sqrt(N) [Find
) ),remainder
DO using MOD]
5. REM ← N M O D I [Another fac tor, disc ontinue
6. IF (REM == 0), THEN testing]
7. Flag ← FALSE [Update Flag to indicate another
8. BREAK factor] [Jump out of the loop]
9. END-IIF
10. END-FOR
11. IF (Fla g == TRUE), THEN
12. PRINT N, “ is Prim e num b e r”
13. ELSE
14. PRINT N, “ is C o m p o site num b e r”
15.END-IF C o ntd .
33
END
BASIC FLOWCHART SHAPES
AND DEFINITIONS
Start / End Project / Task Input / Output
The start or e n d of Process or action. Data: Inputs to, a n d
a workflow. outputs from, a process.
Sp li De c isio n Document
t or
Merge
Upright indicates a Decision point in a D o c u me n t or report.
process split, inverted process or
indicates a merge of workflow.
processes.
Off Pa g e
M a nua l C o nne c to r C o nne c to
Input r
Prompt for information, C o n n e c t o r used to
Used to c o n n e c t o n e
manually entered into c o n n e c t o n e p a g e of
part of a flowchart to
a system. a flowchart to
another.
another.
FLOWCHART
FOR A LOOP
FOR loop
statement-1
FO R ( I = 1 to N, STEP J ), DO
sta te m e nt-
2
sta te m e nt-
3
END-FOR
Step J co u ld b e +ve or –ve, a n d of
any magnitude
In Some languages (C-family), the same loop
is written as:
FOR ( Initialization; Test; Update ),
D O statement-2 3
5
statement-3
EXAMPLE:
ADDING
TWO
NUMBERS
Source: Visual Paradigm
EXAMPLE:
CALCULAT
E PRO FIT
A ND LOSS
EXAMPLE: ROOTS OF
A QUADRATIC
EQUATION
EXAMPLE:
FACTORIAL OF A
NUMBER /
PRO DUC T O F FIRST
N NATURAL
NUMBERS
Star
t
Input EXA M PLE: TESTING PRIM E
N NUM BERS
Flag =
TRUE I =
2
UB =
Floor(Sqrt(N))
F
I <= FALS
UB Flag E
?
T
TRU
N MOD T Flag = FLASE
E
I
Print
== 0
C omposit
BREA e
F1
I=I+
K Print
Prime
Number
Sto
p
EXAMPLE: FLOWCHART
FOR NAVIGATION
THANK
YOU
42