Unit 3
Algorithm design with flowcharts
and pseudocode ... and some Java
1
Algorithm design with flowcharts and pseudocode
-2-
Algorithm design with flowcharts and pseudocode
1. Introduction.
In this Unit we will learn how to design algorithms using two different techniques:
flowcharts and pseudocode, and will use some Java in order to program some of the
algorithms and see them working on a real computer.
Although we will not use flowcharts in the upcoming themes, they are very useful to learn
some of the control structures and to follow the execution flow of some algorithms. So, we
will learn to use them along with pseudocode which we will use more often when we
design algorithms in the future.
2. Structure of an algorithm
In the design and development of algorithms, we can distinguish different types of
instructions.
We will deal with them in detail and see its application solving certain problems.
• Data declaration instructions.
• Simple and Compound instructions.
• Control structures.
2.1. Data declaration instructions.
Are those instructions that indicates the computer the space that should be reserved in
main memory in order to store the information that the program will handle:
<type> <identifier>
This declaration, although convenient both in flowcharts and pseudocode, in general when
designing flowcharts we don’t declare them.
Simple Instructions
The simple instructions are: assignment, input and output.
Assignment
Assignment instructions: are instructions that store data from an expression
and place it in a variable previously defined and declared in the algorithm. We use the
equal symbol =
-3-
Algorithm design with flowcharts and pseudocode
2.2. Simple and compound instructions
Pseudocode Flowchart
LONG = 3.51
counter = 10
name = “Antonio”
sentence = “Good morning“
Pseudocode Flowchart
counter = 10 + 1
counter = counter +1
Input
Input Instructions are those who collect the data from one device or input
device and stores it in the memory in a previously defined variable in the algorithm.
-4-
Algorithm design with flowcharts and pseudocode
Pseudocode Flowchart
read LONG //Expects a Real Numeric
read counter //Expects an Intger Numeric
read name //Expects an alphanumeric
read sentence //Expects an alphanumeric
-5-
Algorithm design with flowcharts and pseudocode
Output
Output instructions: are used to send the data contained in variables or the
results of any expression to an output device.
Pseudocode Flowchart
write LONG * LONG
//Displays the result of the expresion
//on the screen
write “Good morning ” + name
//Displays “Good morning” and then
//the content of the variable name
Compound Instructions
The compound instructions are those that forms a block of actions grouped into
subroutines, subprograms, functions or modules.
Pseudocode Flowchart
subroutine
//Just the name of the subroutine
-6-
Algorithm design with flowcharts and pseudocode
Flowcharts always start with the symbol at the top most place of the flowchart
And end with the symbol at the bottom of the flowchart
Lineal examples:
e.g. 1: Design an algorithm that displays “Good morning”:
Pseudocode Flowchart
write “Good morning”
In Java:
class Example1 {
public static void main (String argv[]) {
[Link](“Good morning”);
}
}
Create a Java project Example1 in IntelliJ IDEA and upload it to Github (complete the
activity on the virtual class)
NOTE: Don’t worry at this point what Java instructions
mean. You will learn them later. Now just learn the
algorithm part of the Java program.
-7-
Algorithm design with flowcharts and pseudocode
e.g. 2: Design an algorithm that calculates and displays the area of a square whose
side measures 5.
Pseudocode Flowchart
int squareArea
squareArea = 5 * 5
write squareArea
class Example2 {
public static void main (String argv[]) {
int squareArea = 5 * 5;
[Link](squareArea);
}
}
Create a Java project Example2 in IntelliJ IDEA and upload it to Github (complete the
activity on the virtual class)
-8-
Algorithm design with flowcharts and pseudocode
e.g. 3: Design an algorithm that calculates and displays the area of a square whose
side is entered by keyboard
Pseudocode Flowchart
int squareArea
int x
write “Enter the side:”
read x
squareArea = x * x
write squareArea
import [Link];
class Example3 {
public static void main (String argv[]) {
float x;
float squareArea;
[Link]("Enter the side:");
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
x = [Link]();
squareArea = x * x;
[Link](squareArea);
}
-9-
Algorithm design with flowcharts and pseudocode
Exercises for you to do:
4.- Design an algorithm that reads two numbers and displays the result of summing,
subtracting, multiplying and dividing them.
5.- Design an algorithm that reads the radius of a circle and displays its length and area.
e.g. 6: Design an algorithm that reads the retail price of an article and its real price and
calculates the discount as a %.
Pseudocode Flowchart
float retailPrice
float realPrice
float discount
write “Enter the retail price:”
read retailPrice
write “Enter the real price:”
read realPrice
discount = (retailPrice - realPrice) /
retailPrice * 100
write “The discount is: “ + discount
-10-
Algorithm design with flowcharts and pseudocode
import [Link];
class Example6 {
public static void main (String argv[]) {
float retailPrice;
float realPrice;
float discount;
[Link]("Enter the retail price:");
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
retailPrice = [Link]();
[Link]("Enter the real price:");
realPrice = [Link]();
discount = (retailPrice - realPrice) / retailPrice * 100;
[Link]("The discount is: “ + discount + “%");
}
}
Exercise for you to do:
7.- Design an algorithm that reads the value of a distance in nautical miles and displays
the distance in meters. 1 nautical mile = 1.852 meters
-11-
Algorithm design with flowcharts and pseudocode
2.3. Control structures
Control instructions are used to control the flow sequence of a program. They can be
classified as:
• Sequence structure
• Decision structures (simple, double and multiple)
• Repetition structures (while, until and for).
2.3.1. Sequence structure.
Sequence structure
You have already been using it. It consists in a series of
instructions that are performed in order one after another.
In this case the instruction SquareArea=5*5 is performed in
the first place and then the next instruction: write SquareArea
class Example2 {
public static void main (String argv[]) {
int squareArea = 5 * 5;
[Link](squareArea);
}
-12-
Algorithm design with flowcharts and pseudocode
2.3.2. Decision structures
Decision structures
Decision structures control the execution or not of a set of instructions
depending on the fulfilment of a certain condition.
Simple decision
In this structure a condition is evaluated to be TRUE or FALSE and a set of instructions
are executed depending on this value (true or false)
Pseudocode Flowchart
if condition
instruction 1
instruction 2
...
instruction n
endif
-13-
Algorithm design with flowcharts and pseudocode
e.g. 8: Design an algorithm that reads your age and displays a message “you have the
legal age” if the age is >= 18
Pseudocode Flowchart
int age
write “Enter your age:”
read age
if age >= 18
write “You have the legal age”
endif
import [Link];
class Example8 {
public static void main (String argv[]) {
int age;
[Link]("Enter your age:");
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
age = [Link]();
if (age >= 18) {
[Link]("You have the legal age");
}
}
}
-14-
Algorithm design with flowcharts and pseudocode
Double decision
In this structure a condition is evaluated to be TRUE or FALSE and a set of instructions
are executed if the result is true and another set is executed if the result is false.
Pseudocode Flowchart
if condition
instruction 1.1
instruction 1.2
...
instruction 1.n
else
instruction 2.1
instruction 2.2
...
instruction 2.m
endif
or
-15-
Algorithm design with flowcharts and pseudocode
e.g. 9: Design an algorithm that reads your age and displays a message “you have the
legal age” if the age is >= 18 and “you are under legal age” otherwise.
Flowchart
Pseudocode
int age
write “Enter your age:”
read age
if age >= 18
write “You have the legal age”
else
write “You are under legal age”
endif
-16-
Algorithm design with flowcharts and pseudocode
import [Link];
class Example9 {
public static void main (String argv[]) {
int age;
[Link]("Enter your age:");
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
age = [Link]();
if (age >= 18) {
[Link]("You have the legal age:");
} else {
[Link]("You are under legal age:");
}
}
}
Exercises for you to do:
10.- Design an algorithm that reads a value and displays if it is positive or negative (0 is
positive)
11.- Design an algorithm that reads two values and displays them in ascending order.
12.- Design an algorithm that reads two values and displays the biggest of them.
13.- Design an algorithm that reads three values and displays the biggest of them.
14.- Design an algorithm that reads three values and displays them in ascending order.
15.- Design an algorithm that reads an integer numeric value corresponding to an exam
marks and displays its Spanish alphanumeric value:
• from 0 to <3 Muy Deficiente.
• from 3 to <5 Insuficiente.
• from 5 to <6 Suficiente.
• from 6 to <7 Bien
• from 7 to <9 Notable
• from 9 to 10 Sobresaliente
-17-
Algorithm design with flowcharts and pseudocode
Multiple alternative decision
In the multiple alternative decision structure one expression is validated and a set of
instructions is executed depending on the resulting value of that expression.
If the result of the expression is equal to value 1 --> A set of instructions is executed
If the result of the expression is equal to value 2 --> Another set of instructions is
executed
...
If the result of the expression is equal to value n --> Another set of instructions is
executed
And if the result does not coincide with any of the values, the set of instructions
assigned to “default” are executed. This default clause is optional.
Flowchart
Pseudocode
case expression
value 1:
set of instructions 1
value 2:
set of instructions 2
...
value n:
set of instructions n
default:
instruction n
endcase
-18-
Algorithm design with flowcharts and pseudocode
e.g. 16: Design an algorithm that reads an integer grade from 0 to 10 and display that
value in textual form: “one”, “two”, .... “ten”.
Flowchart
-19-
Algorithm design with flowcharts and pseudocode
Pseudocode
int grade
write “Enter a number from 1 to 10:”
read grade
case grade
1: write “one”
2: write “two”
3: write “three”
4: write “four”
5: write “five”
6: write “six”
7: write “seven”
8: write “eight”
9: write “nine”
10: write “ten”
default: write “error”
endcase
-20-
Algorithm design with flowcharts and pseudocode
import [Link];
class Example16 {
public static void main (String argv[]) {
int grade;
Scanner inputValue;
[Link]("Enter a number from 1 to 10:");
inputValue = new Scanner([Link]);
grade = [Link]();
switch(grade) {
case 1: [Link]("one");
break;
case 2: [Link]("two");
break;
case 3: [Link]("three");
break;
case 4: [Link]("four");
break;
case 5: [Link]("five");
break;
case 6: [Link]("six");
break;
case 7: [Link]("seven");
break;
case 8: [Link]("eight");
break;
case 9: [Link]("nine");
break;
case 10: [Link]("ten");
break;
default: [Link]("ERROR");
}
}
}
-21-
Algorithm design with flowcharts and pseudocode
Exercises for you to do:
17.- Design an algorithm that receives hours, minutes and seconds and displays hours,
minutes and seconds resulting from adding one second.
18.- Design an algorithm that calculates the net pay for a worker depending on the number
of working hours and the taxes according to the following rules:
• First 35 hours are paid at the normal price per hour
• The hours that exceed those 35 hours are paid at 1.5 times the normal price.
• Tax rates are:
• First 500 € are tax free.
• next 400 € have a taxation of 25%
• And the rest a 45% tax rate.
Input data is:
* € price per hour
* number of hours.
Output data:
* Gross pay
* Net pay
* Taxes
-22-
Algorithm design with flowcharts and pseudocode
e.g. 19: A certain commerce makes a discount depending on the price of every product.
If the price is less than 6 euros there is no discount. If it is bigger or equal to 6 euros
and less than 60 €, then a 5% off is applied, and if ti is bigger or equal to 60 € we apply
a 10% off. Design the algorithm to calculate the final price.
Flowchart
-23-
Algorithm design with flowcharts and pseudocode
Pseudocode
float price, discount, total
write “Enter the price:”
read price
if price < 6
discount = 0
else
if price < 60
discount = price * 0.05
else
discount = price * 0.1
endif
endif
total = price - discount
write “Final price is “ total
import import [Link];
class Example19 {
public static void main (String argv[]) {
float price, discount, total;
[Link]("Enter the price:");
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
price = [Link]();
if (price < 6) {
discount = 0;
} else {
if (price < 60) {
discount = price * 0.05f;
} else {
discount = price * 0.1f;
}
}
total = price - discount;
[Link]("Final price is "+total);
}
}
Exercises for you to do:
20.- Design an algorithm that reads a year as input data and displays if it is a leap year. All
multiples of 4, except those which are multiple of 100 and not from 400 are leap years.
(Eg. Leap years: 1600, 2000, 2400. Not leap years: 1700, 1800, 1900 ..)
-24-
Algorithm design with flowcharts and pseudocode
Iterative structures alter the normal flow of execution of an algorithm,
making it possible that a block of actions or instructions get executed a
certain number of times, depending on the fulfilment of a condition. We
will see 3 kind of of iterations:
• While
• Until
• For
-25-
Algorithm design with flowcharts and pseudocode
2.4. Iterative structures (loops).
2.4.1. While structure
While structure: a block of actions is executed while a condition evaluates to true. The
condition is always evaluated before entering the loop, which make it possible that the
block of actions never get executed if the condition is evaluated to false at the
beginning.
We don’t know beforehand the number of times the loop ill be executed.
Pseudocode Flowchart
while condition do
instruction 1
instruction 2
...
instruction n
endwhile
-26-
Algorithm design with flowcharts and pseudocode
2.4.2. until structure.
Until structure: a block of actions is executed until a condition evaluates to true. The
condition is always evaluated at the end of the loop, which makes that the block of
actions get executed at least once.
We don’t know beforehand the number of times the loop ill be executed.
Pseudocode Flowchart
do
instruction 1
instruction 2
...
instruction n
until condition
-27-
Algorithm design with flowcharts and pseudocode
2.4.3. For structure.
For structure: In this kind of loop the number of times the block of instructions will be
executed is known beforehand. It is a particular case of a While structure.
• A variable called counter is assigned an initial value.
• The condition is evaluated using that counter such as: counter <= final_value
• In every iteration the counter variable is incremented by a fixed value
(increment).
Flowchart
Pseudocode
for counter from initial_value to final_value step by increment
actions
endfor
2.4.4. Ending a loop
One of the dangers when implementing a loop is that it never ends. This is called infinite
loop, which would make the algorithm or program to be executing for ever. In order to not
commiting this error we must remember that the conditions of the loops have to be
changed into the block of the loop. So, if we use a variable to evaluate its value in the
-28-
Algorithm design with flowcharts and pseudocode
condition of the loop, we have to change its value into the block executed in every
iteration.
There are different approaches to make a loop finish:
1.- When we know the exact number of times the loop has to be executed, we use a
counter:
counter = 1
while counter <= 10
...
counter = counter + 1
endwhile
Note: We could have used a for loop.
2.- Asking if we want to remain into the loop.
while ((again == ”s”) or (again == ”S”)) do
...
write “Go on entering data?”
read again
endwhile
3.- Using a sentinel
do
...
read grade
until grade == -1
4.- Using a switch
while switch == true
...
// somewhere into the loop we will assign false to switch
endwhile
2.5. Variables of control
Are variables used by a program that carry out a specific function and that receive a name
because of their habitual use. We have already seen some of them.
2.5.1. Counters.
Are used to count the number of times that an event happens. They usually increment its
value in 1 and most of the times start in 0 or 1, although there may be different increments
or decrements.
We perform 2 kinds of operations on a counter:
-29-
Algorithm design with flowcharts and pseudocode
• Initialization: we initialize it to 0 if we perform a natural count, or an initial value
if we want to carry out another kind of counting. Or final value if we want to make
a reverse counting.
• Increment: Every time the we perform the event we want to count we have to
increment the value of the counter by 1 if we carry out a natural counting or
increment_value if we perform another kind of counting. Or -1 if we are doing a
reverse counting.
e.g. 21: Design an algorithm that reads 10 numbers and counts how many of them a re
positive (>=0)
Flowchart
-30-
Algorithm design with flowcharts and pseudocode
Pseudocode
int positives, i, num
positives = 0
i = 0
while i < 10 do
read num
if num >= 0
positives = positives + 1
endif
i = i + 1
endwhile
write “positives: “ + positives
import [Link];
class Example21 {
public static void main (String argv[]) {
int positives, i, num;
//Reading the value
Scanner inputValue;
inputValue=new Scanner([Link]);
i = 0;
positives = 0;
while (i < 10) {
num = [Link]();
if (num >= 0) {
positives = positives + 1;
}
i = i + 1;
}
[Link](positives + " positives");
}
}
Using the equivalent For structure.
-31-
Algorithm design with flowcharts and pseudocode
import [Link];
class Example21 {
public static void main (String argv[]) {
int positives, num;
//Reading the value
Scanner inputValue;
inputValue = new Scanner([Link]);
positives = 0;
for (int i = 0; i < 10; i++) {
num = [Link]();
if (num >= 0) {
positives = positives + 1;
}
}
[Link](positives + " positives");
}
}
2.5.2. Accumulators
Accumulators are used in a program to accumulate successive elements with the same
operation. They are usually used to calculate sums and products, although there are other
less common types of accumulations with different operations.
As it happens with counters, to use them we have to carry out two basic operations:
• Initialization: We usually initialize an accumulator with the neutral element of the
operation used to accumulate. 0 for the sum and 1 for the product.
• Accumulation: Every time the we get an element to accumulate we perform the
operation performing the operation using the new value to accumulate and the so
far accumulated value.
-32-
Algorithm design with flowcharts and pseudocode
e.g. 22: Design an algorithm that writes the sum of the first 10 natural numbers and the
product of the 10 first natural numbers
Flowchart
Pseudocode
int sum, product
sum = 0
product = 1
for i from 1 to 10 do
sum = sum + i
product = product * i
endfor
write “sum from 1 to 10:” + sum
write “product from 1 to 10:” + product
-33-
Algorithm design with flowcharts and pseudocode
class Example22 {
public static void main (String argv[]) {
int sum, product;
sum = 0;
product = 1;
for (int i = 1; i <= 10; i++) {
sum = sum + i;
product = product * i;
}
[Link]("Sum from 1 to 10:” + sum);
[Link]("Product from 1 to 10:” +
product);
}
}
Exercise for you to make:
Write the pseudocode using the equivalent While structure.
2.5.3. Switches.
Switches are boolean variables. They only can contain the values true or false (Yes/No,
1/0). They take information from one place to another into the program. they act as
remainders of something that happened during the execution of the program.
-34-
Algorithm design with flowcharts and pseudocode
e.g. 23: Design an algorithm that reads a set of grades form the keyboard until a -1 is
entered and it writes the average grade and if there was a 10 or not.
Flowchart
-35-
Algorithm design with flowcharts and pseudocode
Pseudocode
float grade, sum
boolean wasTen
int i
sum = 0
i = 0
grade = 0
wasTen = false
while grade != -1 do
read grade
if grade != -1
sum = sum + grade
i = i + 1
if grade == 10
wasTen = true
endif
endif
endwhile
write “average:” + sum / i
if wasTen
write “There was a ten”
else
write “There was not a ten”
endif
-36-
Algorithm design with flowcharts and pseudocode
import [Link];
class Example23 {
public static void main (String argv[]) {
float grade = 0, sum = 0;
boolean wasTen = false;
int i = 0;
Scanner inputValue;
inputValue = new Scanner([Link]);
while (grade != -1) {
grade = [Link]();
if (grade != -1) {
sum = sum + grade;
i = i + 1;
if (grade == 10) {
wasTen = true;
}
}
}
[Link]("Average: “ + sum / i);
if (wasTen) {
[Link]("There was a 10");
} else {
[Link]("There was not a 10");
}
}
}
Examples:
24.- Design an algorithm to calculate the factorial for a number
25.- Design an algorithm that reads a natural number and writes all its multiplication table.
26.- Design an algorithm that reads a natural number and writes its divisors.
27.- Design an algorithm that writes the first 40 terms of the Fibonacci series.
28.- Design an algorithm that calculates a product of 2 numbers > 0 using successive
sums.
29.- Algorithm that calculates the remainder of the integer division using successive
subtractions.
-37-
Algorithm design with flowcharts and pseudocode
30.- Design an algorithm that reads a number n and then prints this:
1
1 2
1 2 3
…
1 2 3 4 5 … n
31.- Design an algorithm that reads a number n and then prints this (Example with n = 5):
/ / / / 1 / / / /
/ / / 2 1 2 / / /
/ / 3 2 1 2 3 / /
/ 4 3 2 1 2 3 4 /
5 4 3 2 1 2 3 4 5
32.- Calculate the square root value for a number n using the iterative solution:
Given x as an estimated value (you can set x = n at the beginning), each iteration is
calculated as:
Then you can make x = y and make another iteration.
Calculate square root of n for 10 iterations. ([Link]
33.- Now modify the previous exercise and stop iterating when | x - y | < 0.000001. You
can not use the [Link]( ) function.
34.- Calculate e value using Newton’s series. The input data is a number n. Use a value
like 10 for the infinite (try several numbers):
[Link]
Tip for ex. 34: e = 1/1 + 1/1 + 1/2 + 1/6 + 1/24 + 1/120 + …
-38-