Write down algorithms
• How to write down algorithm?
Subject: Introduction to Algorithm • Write Pseudo-code
Draw Flowchart
Lecturer: Hoang Do Thanh Tung •
• Do Exercise
Credit points 3 ECTS
Level Undergraduate
Teaching time 04/05– 31/6/2021
Location University of Science and Technology of Hanoi
When/Where to write Algorithms?
Software
Operating System
Applications
Programs
Program consists of programmer code
Program Development
1. Define the Problem
Inputs – Processing Steps – Outputs
2. Outline the Solution
Break problem into smaller tasks or steps
Major: Processing Steps, Subtasks, Control Structures, Variables, Record Structures, Mainline Logic
3. Develop the Outline into an Algorithm
Pseudocode, Flowcharts
4. Test the Algorithm for Correctness
Desk Checking; Identify Major Logic Errors
5. Code the Algorithm in a specific language
6. Run the Program on the Computer
Test Data from Test Team
7. Document and Maintain the Program
Occurs through the entire process
Solution Planning
(a) Defining the problem Defining Diagram
Defining Diagram
(b) Control Structures Control Structures
Sequence (sequential instructions)
Variables,
Selection (IF, CASE)
Constants, Literals
Repetition (DO WHILE, DO UNTIL)
Variables
Constants Pseudocode or
Literals Flowchart
(c) Solution Algorithm
Pseudocode or
Desk Checking
Flowchart
(d) Desk Checking
Designing A Solution Algorithm
Control
Requirements Structures
ALGORITHM
Pseudocode Flowchart
Designing A Solution Algorithm
Customer Interview
Solution planner
Verify
Requirements
Requirements
Development Pseudocode
Flowcharts
Design Algorithm
Defining the Problem
The problem must be defined in terms of:
Input: Data to be processed.
Output: The expected result.
Lookfor nouns in the problem statement that suggest output and
input.
and processing: The statements to achieve.
Look for verbs to suggest processing steps.
input data output data
Keyboard Processing Screen
8
Example 1
Area and Perimeter of a rectangle
Input
Length
width
Processing
Area = length*width
Perimeter = 2*( length + width)
Output
Area
Perimeter
9
Example 2
Sum and Average of 5 numbers
Input
five number x1, x2, x3, x4, x5
Processing
Sum = x1+x2+x3+x4+x5
Average = Sum/5
Output
Sum
Average
Page 10
Example 3
Area and Perimeter of a circle
Input
Radius
PI
Processing
Area = PI * Radius * Radius
Perimeter = 2 * PI * Radius
Output
Area
Perimeter
Page 11
Exercise:
How fast is a car traveling if it goes 50 miles in 2 hours?
Input: the distance and time the car has traveled
Process: speed = distance / time
Output: a number giving the speed in miles per hour
What is the rest?
Write down Algorithms
Pseudo code
Algorithm Pseudocode
Flowcharts
Coding the Program in a formal language Coding Translating
Program Source Code
(The “.cpp”)
Program Source code
Compiling the program into machine code Compiling Translating
Machine code Machine Code
How to write down algorithm?
How to write Algorithms
Properties of Algorithms
Computer programs are concrete representations of
algorithms , but algorithms are not program
Algorithms can be used in any programming language
Algorithms have a lot of structure, ex: conditionals,
loops, and recursion…
How to write down in detail an algorithm with?
Natural language
Programming language
Pseudocode
Flowcharts
How to write Algorithms
Natural language
Fullof ambiguities, subtleties, and shades of
meaning, but algorithms must be described as
accurately as possible
Programming language
C, C++, C#, Java, Python, Ruby, Erlang, Haskell,
OcaML, Scheme, Visual Basic, Smalltalk, Javascript,
Processing, Squeak, Forth, TEX, Fortran, COBOL,
Intercal, or Brainfuck …
We should only focus on algorithm design
Write down with Pseudo-code
Pseudocode
Pseudocode looks like programming languages
Uses the structure of formal programming languages
Instructions may be written using mathematics, pure
language
Well-written pseudocode making the algorithm much easier
to understand, analyze, debug, and implement.
Pseudocode should allow any competent programmer to
implement the underlying algorithm, quickly and correctly,
in their favorite programming language
Structure of an algorithm
Algorithm
Variables
Instructions
• An algorithm consists of instructions
• Instructions involve variables
Behavior of an algorithm
Computer
Input Output
(keyboard) (screen)
Algorithm
Instructions of an algorithm
Basic (primitive) instructions
Read the input from user
Print the output to the user
Cary out basic arithmetical computations
Conditional instructions
Execute an instruction (or a block of instructions) if a condition
is true
Repeat instructions
Execute a block of instructions (multiple) times until a certain
condition is met
and…variables
Variables and Arrays…
Computers work with data (numbers, words, etc)
Data must be stored (in variables)
Each variable is assigned a storage “box”
can store one number at any time
eg: sum, j, carry
Arrays:
Often deal with many numbers
Such as A1, A2, A3, … , A100
Store as an “array” A[1], A[2], … , A[100]
we treat each of them as a variable,
each is assigned a storage “box”
Basic instructions (1)
Assign values to variables using basic arithmetic operations
Example: Let’s assume we have two variable, a and b.
We execute:
Set the value of a to 3
This instruction changes the value of a to 3.
Now we execute
Set the value of b to a*3 + 12
This instruction changes the value of b to 3+3 + 12 = 21
Basic instructions (2)
Read input from user
Example:
get the value of [variable] a [from user]
When this instruction is executed,
the algorithm stops,
waits for the user to type in an answer, and
the value typed by the user is stored into variable a.
Basic instructions (3)
3. Print to user (screen)
Print variables and/or text
Example:
print the value of variable x
When a print instruction is executed, the algorithm writes to screen the value of variable x
print “Hello world!”
This instruction prints to screen the text “Hello world!”
Why do we need quotation signs?
Print hello
Print “hello”
Basic instructions (4)
Incorrect
Set 1 to a
Add a + b (what do you do with the result?)
Set a+b+3
NOT the same
set a to b
set b to a
Example: what is the output of the following algorithms?
set a to 2 set a to 2
set b to 4 set b to 4
set a to b set b to a
print a, b print a, b
Example
Write an algorithm that asks the user for three numbers, computes
their sum and average and outputs them.
One possible algorithm for this problem:
Variables: a,b,c, sum, avg
Get the values of a, b, c from user
Set avg to (a+b+c)/3
Set sum to (a+b+c)
Print sum, avg
Example
Write an algorithm that reads the value of a circle radius from the
user, and prints the circumference of a circle with that radius.
One possible algorithm for this problem:
variables: r, c
1. Get the value of r from user
2. Set c to 2 * pi * r
3. Print “The circumference of your circle is “ c
Exercise
Write an algorithm that asks the user for his year of birth, then prints
it out, says thank you and good bye. It should look like this:
Hi. Please tell me your year of birth: 1920
You said 1920. Congratulations. Goodbye.
Conditional Instructions
An instruction depending whether the condition is true or
false. The else part is optional.
if <condition> then
<instruction(s) to be done>
else
<instruction(s) to be done otherwise>
Example
if the value of x is 0 then
set the value of a to 0,
else
set the vale of a to a+1
Example
If the value of a is greater than10 then
substract 10 from a
-------------------
If the value of x is >10 then
set b to x – 10
set c to x+10
print b,
Else
set x to x + 10
print x
Example
Consider the following algorithm:
print “Enter two values”
get a, get b
if the value of a is larger the value of b then
print a
else
print b
What does the program print if the user enter 10, 13?
Describe in English what the algorithm accomplishes.
Exercise
Write an algorithm that asks the user for two numbers that
represent the scores to a soccer game Bowdoin vs. Colby,
and prints out either “You won”, “You tied” or “You lost”.
Enter Bowdoin score: 4
Enter Colby score: 2
You won.
Compact Pseudocode
This is correct
Get the value of a from user
Get the value of b from user
If the value of a is equal to the value of b then
print the value of a
else
set the value of c to the value of a + the value of b and print c
But, we’ll slowly converge towards a more compact, math-like style
Get a, get b
ALGORITHM
If (a==b) then
1. Read (S, E, G);
print a
2. Distance (E–S);
Else
3. Average D/G;
set c = a + b
4. Print Average;
print c
5. Stop
Compact Pseudocode
Examples:
If (a >= b) …
If (a + b <= c)…
If (x == y)…
If (the remainder of x divided by y == 0)
…
Note: the operator for “remainder” is denoted %
If (x%2 == 0) print “even number”
Example
Write an algorithm to compute the distance traveled and the average
miles per gallon on a trip when given as input the number of gallons used and the
starting and ending mileage readings on the odometer.
Variables: gallons, start, end, distance, mpg
get gallons, start, end
distance = end - start
mpg = distance / gallons
print mpg
if mpg > 25.0 then
print “You are getting good gas mileage”
else
print “You are NOT getting good gas mileage”
Exercise
Equivalent:
Set the value of a to 1
Set a to 1
a=1
Equivalent
Add 1 to count
Set count to count + 1
Increment the value of count by 1
count = count + 1
Writing in pseudocode gives you the freedom to choose
any of these. In general people prefer the shorter form.
Combining Conditions
Use logical operators: and, or, not
If (condition 1 and condition 2)
True if BOTH are true
If (condition 1 or condition 2)
True if at least one is true
If (not condition 1)
True if condition 1 is not true
Examples
If (score > 85 and score < 95) then print “grade
is A-”
If (not (score < 2)) print “you passed”
Exercise
Write an algorithm that asks the user for an exam score, which
is expected to be a number between 0 and 100. If the score
does not fit in this range, display an error message. Otherwise
assign a letter grade A, B, C, D or F. The breaks are 90, 80, 70,
60. For example:
Please enter a score, between 0 and 100: 110.
Sorry, that’s impossible.
Please enter a score between 0 and 100: 85
The grade is B.
Looping Primitive – while-loop
The while-loop
loop a “variable” number of times
Syntax
false
condition?
while (condition) do
true
(some sequence
of statements) Some sequence
of statements;
endwhile
Exercising a while loop
j 1; (* General Loop *)
while (j <= 3) do Read(n);
print j; j 1;
j j + 1; while (j <= n) do
endwhile print j, A[j];
print “--- Done ---” j j + 1;
endwhile
print “--- Done ---”
Output:
1
2
3
--- Done ---
Looping Primitive – for-loop
j a;
First, the for-loop
loop a “fixed” or (pre-determined) number
of times
Syntax false
(j <= b)?
for j a to b do true
(some sequence
Some sequence
of statements) of statements;
endfor
j j+1;
Exercise
for j 1 to 3 do
print j;
endfor
print “--- Done ---”
Output:
1
2
3
--- Done ---
Exercise
for j 1 to 4 do j 1;
print 2*j; while (j <= 4) do
endfor print 2*j;
print “--- Done ---” j j + 1;
endwhile
print “--- Done ---”
Output:
Output:
2
2
4
4
6
6
8
8
--- Done ---
--- Done ---
Simple iterative algorithm: Sum
Given: List of numbers: A1, A2, A3, …., An
Output: To compute the sum of the numbers
Note: Store numbers in array A[1], A[2], … , A[n]
Sum(A, n);
begin
Sum_sf 0;
k 1;
while (k <= n) do
Sum_sf Sum_sf + A[k];
k k + 1;
endwhile
Sum Sum_sf;
Print “Sum is”, Sum
end;
Exercising Algorithm Sum:
A[1] A[2] A[3] A[4] A[5] A[6] n=6
Input:
2 5 10 3 12 24
k Sum-sf Sum
? 0 ?
1 2 ?
Processing: 2 7 ?
3 17 ?
4 20 ?
5 32 ?
6 56 ?
6 56 56
Output: Sum is 56
Algorithm for Sum (with for-loop)
We can also use a while-loop instead of a for loop.
1. Sum(A, n);
2. (* Find the sum of A1, A2,…, An. *)
3. begin
4. Sum_sf 0;
5. for k 1 to n do
6. Sum_sf Sum_sf + A[k];
7. endfor
8. Sum Sum_sf;
9. Print “Sum is”, Sum
10.end;
➢ Exercise: (a) Note the differences…
(b) Modify it to compute the average?
Remarks about the iterative algorithm…
Note the three stages:
1. Initialization
Set some values at the beginning
2. Iteration
This is the KEY STEP
Where most of work is done
3. Post-Processing or Cleanup
Can use this setup for other problems
Calculating average, sum-of-squares
Finding max, min; Searching for a number,
Another Example of Algorithm (with loops)
PROBLEM: Start with a collection of names N1, N2, ..., N10000,
and corresponding telephone numbers T1, T2, ..., T10000.
Given a name, Name, find a telephone number for that
name if a match on an Ni occurs; otherwise, print "Not
Found".
Note: In the book, subscripts are used for N1, N2, etc.
A FIRST ATTEMPT AT A SOLUTION TO THE TELEPHONE SEARCH
PROBLEM
1. Get values for N1, N2, ..., N10000, T1, T2, ,,,, T10000, and Name.
2. if Name is N1, then print T1 ; Stop endif;
3. if Name is N2, then print T2; Stop; endif;
4. If Name is N3 then print T3; Stop; endif;
... ... ...
{a lot of tedious writing here that is being skipped}
... ... ...
10001. If Name is N10000, then print T10000 ; Stop; endif
10002. Print "Not found"
10003. Stop.
A SECOND ATTEMPT AT A SOLUTION TO THE TELEPHONE SEARCH PROBLEM
1. Get values for N1, N2, ..., N10000, T1, T2, ,,,, T10000, and Name.
2. Set the value of i to 1 and the value of Found to NO.
3. Repeat steps 4 through 7 until (Found is Yes)
4. If Name is equal to Ni, then
5. Print the telephone number Ti
6. Set the value of Found to Yes
Else
7. Add 1 to the value of i
8. Endif
9. Stop.
ANOTHER ATTEMPT AT A SOLUTION TO THE TELEPHONE SEARCH PROBLEM
1. Get values for N1, N2, ..., N10000, T1, T2, ,,,, T10000, and Name.
2. Set the value of i to 1 and the value of Found to NO.
3. Repeat steps 4 through 7 until (Found is Yes) or (i > 10000)
4. If Name is equal to Ni, then
5. Print the telephone number Ti
6. Set the value of Found to Yes
Else
7. Add 1 to the value of i
8. If (Found is No) then
9. Print "Not found"
10. Stop.
Solution to Telephone Search Problem
(Using a while loop)
Get values for N1, N2, ..., N10000, T1, T2, ,…, T10000, and Name.
Set the value of i to 1;
Set the value of Found to “NO”;
While (Found = “No”) and (i <= 10000) do
If (Name = Ni ) then
Print the telephone number Ti ;
Set the value of Found to “Yes”;
Else Add 1 to the value of i;
Endwhile
If (Found = “No”) then
Print "Not found";
FIND LARGEST ALGORITHM
PROBLEM: Given n, the size of a list, and a list of n numbers, find
the largest number in the list.
Get a value for n and values A1, A2, ..., An for the list items.
Set the value of Largest-so-far to A1.
Set the Location to 1.
Set the value of i to 2.
While ( i <= n) do
If Ai > Largest-so-far then
Set Largest-so-far to Ai
Set Location to i
Add 1 to the value of i.
Endwhile
Print the values of Largest-so-far and Location.
Tips and tricks of pseudocode
There are many styles of pseudocode
Some programmers use an outline form
Some use a form that looks almost like a
programming language
55
Write down with Flowcharts
56
56
Flowcharts
Graphically depict the logical steps to carry out a task and show how the
steps relate to each other.
57
Flow Control
sequential branching loop
a a a
b b g b
c c c
d d d
e e h e
f f f
Flowcharts
When tracing a flowchart, start at the start symbol
and follow the flow lines to the end symbol
Testing an algorithm at the flowchart stage is known
as desk checking
Flowcharts, pseudocode are program planning tools
that are not dependent on the programming
language being used
59
Flowcharts
Flowcharts are time-consuming to write and
difficult to update
For this reason, professional programmers are more
likely to favor pseudocode
Because flowcharts so clearly illustrate the logical
flow of programming techniques,
60
Flowchart symbols
61
Flowchart example
62
Decision flow chart
63
Looping flow chart
64
Example
Problem: Given a street number of a one-way street in New York City, decide
the direction of the street, either eastbound or westbound
Discussion: in New York City even numbered streets are Eastbound, odd
numbered streets are Westbound
65
Pseudocode
Program: Determine the direction of a numbered NYC
street
Get street
If street is even Then
Display Eastbound
Else
Display Westbound
End If
66
Flowchart
67
Example
Problem: Calculate and report the grade-point
average for a class
Discussion: The average grade equals the sum
of all grades divided by the number of students
Input: Student grades
Processing: Find the sum of the grades; count the
number of students; calculate average
Output: Average grade
68
Pseudocode
Program: Determine the average grade of a class
Initialize Counter and Sum to 0
Do While there are more data
Get the next Grade
Add the Grade to the Sum
Increment the Counter
Loop
Computer Average = Sum / Counter
Display Average
69
Flowchart
70
While Repetition Structure
Repetition structure
Allows the programmer to specify that an action should be repeated, depending on
the value of a condition
true
product <= 1000 product = product * 2
false
71
while loop
Push the
acceleration Push the acceleration paddle;
paddle while (speed is less than 100mph)
{
Speed < push the acceleration paddle;
100mph? }
No Release the paddle;
Push the
acceleration
paddle Stop
pushing
Yes
72
Exercise
Problem: Write a program that reads and displays the
age of 10 people (one after another).
For this problem, we need a way to count how many
people whose age have been processed (read and
displayed). Therefore, we introduce a concept of counter,
a variable used to count the number of people whose
age have been processed by the program.
73
Exercise
Begin Counter initialisation
number of users giving his age = 1
while (number of users giving his age <= 10)
read the age from the user.
print the user age. Loop condition
number of user giving his age + 1
end_while
End Updating counter
Begin
users = 1
while (users <= 10)
read age
print age.
users = users + 1
end_while
End
Exercise
Begin
users = 1
NO
End users <= 10?
YES
read age
print age
users =users + 1
Subsequently..
Begin You can start the
counter with ZERO
number of users giving his age = 0
while (number of users giving his age < 10)
read the age from the user.
print the user age.
number of user giving his age + 1 The loop condition
end_while must less than the
value it requires to
End stop
Begin
users = 0
while (users < 10)
read age
print age. Be
users = users + 1 consistent
end_while
End
Little extra…
Now let us put together everything that you have learnt so far.
Problem:
Write a program that will calculate and print the age of 10 persons, given
their birth year. If the age of the person is above 55, then the program will
print “Hi”, otherwise, the program will print “Hello”.
Do Until/for Loop Repetition Structure
It tests a condition for falsity for repetition to continue.
false
product > 1000 product = product * 2
true
78
Example Start
totalAmount=0;
n=1;
Prompt the user for 10 input
(integer values). Stop and output TRUE n <= 10
the total amount if the total FALSE
amount is larger than 100. Prompt user
to input a
Output
value
totalAmount
Input: 1,2,3,4,…,10 n=n+1;
Complete 10 iterations inputValue
=nextInt()
Output: 55
totalAmount=
totalAmount+inputValue
Input: 50,40,30,20,… FALSE
Break the loop in iteration 3 totalAmount
>100
Output: 120
TRUE
break
Example
Start
int inputValue, n, totalAmount=0; totalAmount=0;
n=1;
for ( n=1; n<=10; n++)
{ TRUE n <= 10
FALSE
inputValue=keyboard.nextInt(); Prompt user
totalAmount=totalAmount+inputValue; to input a
Output
value
totalAmount
n=n+1;
if ( totalAmount > 100 ) inputValue
=nextInt()
{
break; totalAmount=
} totalAmount+inputValue
FALSE
} totalAmount
>100
System.out.println(totalAmount); TRUE
break