Algorithm Design and problem solving2
Algorithm Design and problem solving2
PROBLEM SOLVING
Learning Objectives
Select appropriate identifier names.
Write programs in pseudocode using
input, process and output.
Write pseudocode using assignment,
sequence, selection and repetition.
Write pseudocode from a structured
English description and from
flowchart.
VARIABLES
Example:
Structured English Pseudocode Flowchart
SET
Set X to 12 X 12 X TO 12
Flowchart
INCREMENT
INCREMENT Y Y Y+1 Y
SEQUENCE: Execution of instructions in a predetermined order, one
after another. Under this we can have the following:
Updating a value:
Y 5
The value of Y can be updated (either to increase or decrease it as the
program instructs)
Y 5+ 1
Example
Y 5
Copying the value of Y to Z, we have
Y Z
Z Y
Swapping two values
To swap the content of two variables, writing the pseudocode
like
Y Z
Z Y; is not correct
Because there could be issue of overwriting.
INPUT “Enter
Fahrenheit”
Fahrenheit
Celsius = Fahreheit – 32 *
(5/9)
OUTPUT Celsius
End
Pseudocode
Km = Miles * 1.61
IF A > B B 3
IF A IS GREATER THAN B THEN…
THEN...... ELSE…
ELSE…… ENDIF Y
A>B Do this
N
Do this
CONDITION (SELECTION
CONSTRUCT)
A Condition consists of at least one logic
proposition, that is, a statement that can be
either true or false.
Example:
IF A > B
THEN….
ELSE….
ENDIF
COMPARISON OPERATOR
Operator Comparison Meaning
= equal to
< less than
> greater than
<= less than or equal
to
>= greater than or
equal to
<> not equal to
Worked Example 1:
Write a program that takes an input age from the user and outputs
“You can vote” if the age is 18 or above, otherwise outputs “You
cannot vote yet”. Selection Construct
INPUT
Age
Age No
OUTPUT
>= You cannot
18 vote
Yes
OUTPUT
You can vote
END
TASK (CLASS EXERCISE)
A town has a bus service where passengers
under the age of 12 and over the age of 60
do not need to pay a fare.
i) Write the logic statement for free fares
(Pseudocode)
ii) Draw the flowchart for the above.
WORKED EXAMPLE 2
Question: Take three number as input and output the smallest
number.
e.g. N1 N2 N3
10 15 8
Pseudocode
INPUT Number 1 (N1)
INPUT Number 2 (N2)
INPUT Number 3 (N3)
IF N1 < N2
THEN
IF N1 < N3
THEN
OUTPUT N1
ELSE
OUTPUT N3
ENDIF
ELSE
IF N2 < N3
THEN
OUTPUT N2
ELSE
OUTPUT N3
ENDIF
ENDIF
START
INPUT
FLOWCHART N1
INPUT
N2
INPUT
N3
Y N1 Y N1 OUTPUT
< <
N2 N3
N1
N
N2
OUTPUT
<
N3 N3
N
OUTPUT
N2 Y
END
ASSIGNMENT
Take three numbers as input and
output the largest number.
Express this in Pseudocode and
flowchart
LOOP
Looping means continuous execution of a
command until a condition is met.