Algorithm and Flow Chart
ALGORITHMS AND FLOWCHARTS
Steps in Problem Solving
Pseudocode & Algorithm
Write an algorithm to determine a student’s final grade and indicate whether it is passing or failing. The final grade is calculated as the average of four marks.
Pseudocode & Algorithm
Pseudocode:
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm
Step 2: GRADE ← (M1+M2+M3+M4)/4
Step 3: if (GRADE < 60) then
Print “FAIL”
else
Print “PASS”
endif
The Flowchart
A Flowchart is another algorithm but graphical.
e.g. control flow from one action to the next
Flowchart Symbols
General Used Symbols
Example
“PASS”
Step 1: Input M1,M2,M3,M4
Step 2: GRADE ← (M1+M2+M3+M4)/4
Step 3: if (GRADE < 60) then
Print “FAIL”
else
Print “PASS”
endif
START
Input
M1,M2,M3,M4
GRADE←(M1+M2+M3+M4)/4
IS
GRADE<60
“FAIL”
STOP
Y
N
Example 2
Pseudocode:
Example 2
Algorithm
START
Input
Lft
Lcm ← Lft x 30
Lcm
STOP
Flowchart
Example 3
Write an algorithm and draw a flowchart that will read the two sides of a rectangle and calculate its area.
Pseudocode
Example 3
Algorithm
START
Input
W, L
A ← L x W
A
STOP
Example 4
Example 4
Pseudocode:
Example 4
START
Input
a, b, c
d ← sqrt(b x b – 4 x a x c)
x1 ,x2
STOP
x1 ←(–b + d) / (2 x a)
X2 ← (–b – d) / (2 x a)
DECISION STRUCTURES
DECISION STRUCTURES
is
A>B
Print B
Print A
Y
N
IF–THEN–ELSE STRUCTURE
If condition then
true alternative
else
false alternative
endif
IF–THEN–ELSE STRUCTURE
If A>B then
print A
else
print B
endif
is
A>B
Print B
Print A
Y
N
Relational Operators
Relational Operators | |
Operator | Description |
> | Greater than |
< | Less than |
= | Equal to |
≥ | Greater than or equal to |
≤ | Less than or equal to |
≠ | Not equal to |
Your flowchart
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX ← VALUE1
else
MAX ← VALUE2
endif
Step 3: Print “The largest value is”, MAX
Example 5
MAX ← VALUE1
“The largest value is”, MAX
STOP
Y
N
START
Input
VALUE1,VALUE2
MAX ← VALUE2
is
VALUE1>VALUE2
nested if statements
IF–THEN–ELSE statement
Example 6
Example 6
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX ← N1 [N1>N2, N1>N3]
else
MAX ← N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX ← N2 [N2>N1, N2>N3]
else
MAX ← N3 [N3>N2>N1]
endif
endif
Step 3: Print “The largest number is”, MAX
Example 6�YOUR JOB
Example 7
Example 7
Bonus Schedule | |
OVERTIME – (2/3)*ABSENT | Bonus Paid |
>40 hours >30 but ≤ 40 hours >20 but ≤ 30 hours >10 but ≤ 20 hours ≤ 10 hours | $50 $40 $30 $20 $10 |
Step 1: Input NAME,OVERTIME,ABSENT
Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then
PAYMENT ← 50
else if (OVERTIME–(2/3)*ABSENT > 30) then
PAYMENT ← 40
else if (OVERTIME–(2/3)*ABSENT > 20) then
PAYMENT ← 30
else if (OVERTIME–(2/3)*ABSENT > 10) then
PAYMENT ←20
else
PAYMENT ← 10
endif
Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
Example 7