Algorithm Design: COMP101: Introduction To Programming in JAVA
Algorithm Design: COMP101: Introduction To Programming in JAVA
Lecture 10
Algorithm Design
Algorithm Design 1 / 81
Lecture 10 Lecture 11 Lecture 12
Introduction
Algorithm Design 2 / 81
Lecture 10 Lecture 11 Lecture 12
Describing Computations
Algorithm Design 3 / 81
Lecture 10 Lecture 11 Lecture 12
Pseudocode standards
Algorithm Design 4 / 81
Lecture 10 Lecture 11 Lecture 12
Pseudocode conventions
Each textbook and each individual designer may have their own
personal style of pseudocode.
Algorithm Design 5 / 81
Lecture 10 Lecture 11 Lecture 12
Pseudocode conventions
There are three main ways of doing things:
sequence a process described as a sequence of steps
occurring one after the other.
“I do this, then that, then that”.
selection a process described in terms of alternatives.
“If this happens then I do this otherwise I do that”
iteration a process described in terms of repeated
executions of particular actions, sometimes
subject to a termination condition
“While there is still a coin in my purse, I pick one,
remove it from the purse and add its value to a
running total”
Sequence
A sequential process is indicated by writing one action after
another, each action on a line by itself, and all actions aligned
with the same indentation. The actions are performed in the
sequence (top to bottom) that they are written.
Example (non-computer)
Brush teeth
Wash face
Comb hair
Smile in mirror
Example
READ height of rectangle
READ width of rectangle
COMPUTE area as height multiplied by width
Algorithm Design 7 / 81
Lecture 10 Lecture 11 Lecture 12
Algorithm Design 8 / 81
Lecture 10 Lecture 11 Lecture 12
Object Interactions
Algorithm Design 9 / 81
Lecture 10 Lecture 11 Lecture 12
Method definition
Algorithm Design 10 / 81
Lecture 10 Lecture 11 Lecture 12
Golden Rules
Algorithm Design 11 / 81
Lecture 10 Lecture 11 Lecture 12
Approaches
How do we find out what computation is needed to
solve a particular programming task?
Problem
Write a program to input the length, width and depth of a
rectangular swimming pool of uniform depth and calculate the
time it takes to fill it. Assume the rate of flow of water into the
pool is 50 litres per minute and that 1 cubic metre has a
capacity of 1,000 litres of water.
SwimmingPool
- RATEOFFLOW: double = 50.0
SwimmingPoolUser - UNITCAPACITY: double = 1000.0
✲ - length: double
+ main(String[]) - width: double
- depth: double
+timeToFill(): double
Algorithm Design 13 / 81
Lecture 10 Lecture 11 Lecture 12
Initial Analysis
Algorithm Design 14 / 81
Lecture 10 Lecture 11 Lecture 12
Responsibilities
Algorithm Design 15 / 81
Lecture 10 Lecture 11 Lecture 12
Scenarios
x * UNITCAPACITY / RATEOFFLOW
Technical Issue
Conceptually X is the volume of the pool.
As length, width and depth are all doubles, given the calculation
involved, we probably want timeToFill also to output a double.
Here’s the full specification of the required method:
METHOD timeToFill
INPUT
OUTPUT double
COMPUTE the volume of the pool poolVolume as length x
width x depth
RETURN (poolVolume x UNITCAPACITY) / RATEOFFLOW
METHOD main
INPUT args
OUTPUT
LOCAL DATA lth, wth and dth (all real numbers)
READ lth, wth and dth from the keyboard
SET up an instance myPool of Swimming Pool setting length=lth,
width=wth and depth=dth
PRINT the result of calling timeToFill() on myPool.
Problem
Write a program to input the cost of fuel put in the car each day
of the (working) week, then compute the total cost and the
average cost, and display the results of the two computations.
FuelCost
- monCost: double
- tuesCost: double
FuelCostUser
- wedCost: double
✲
- thursCost: double
+ main(String[])
- friCost: double
+totalCost(): double
+averageCost(): double
Behaviours
Write a program to input the cost of fuel put in the car each day of
the (working) week, then
compute the total cost and the average cost , and display the
results of the two computations.
Summary
Lecture 11
More About Methods
Overview
Methods
Methods: Example
We could add a method to the Rectangle class that prints out the
rectangle’s length and width.
// Print out rectangle’s length and width
public void printDimensions() { System.out.println("Length: " +
getLength() +
" Width: " + getWidth());
System.out.println();
}
Running it!
The first statement in the main method will print the
message starting Execution starts... to the screen.
Then Java executes display(). It does so by jumping inside the
body of the method display at the bottom of the listing and
running the method’s single statement.
The sentence method [display] is then called; appears on the
screen.
Then execution of the method ends, and the next
statement that is executed is the one immediately following
the call to display. The final line back to the [main] method. will
appear on the screen.
$ java TestMethodsControlFlow
Execution starts in [main] method;
method [display] is then called;
back to the [main] method.
$
Remarks
$ java TestMethodsWithReturnValue
First number? 10
Second number? 5
The sum is 15
$
The invocation to sum() in the main program creates a new
execution environment with its own memory, allocates space
in this memory for the variables defined inside the method
and starts executing the method’s code.
The statement “return expression” is used to assign a value to the
method and return the control to the calling method. If the
method type is void there is no need to use a return statement,
but one may be used to force the control back
to the calling method.
It is syntactically legal to have many return statements inside
a method ... but not a very good practice for maintenance as
it may become difficult to trace all of them.
Clare Dixon More About Methods 32 / 81
Lecture 10 Lecture 11 Lecture 12
Parameters
Remarks
Method Parameters
// program to demonstrate calling a method that receives its
// data through a parameter list.
import java.util.Scanner;
Remarks
Reference Parameters I
Note that for items of data that are stored by reference (e.g.
objects or arrays) the parameter mechanism has slightly
different effects.
Reference Parameters II
Reference Parameters IV
theRect
length = 100
bigRect
width =35
length = 50
theRect bigRect
width = 35
newRect
Remarks
Scope of Identifiers
class TestMethodsWithParameterPassing {
private static int first, second; // numbers to input
Lifetime
METHOD timeToFill
INPUT
OUTPUT double
COMPUT the volume of the pool poolVolume as
E length x width x depth
RETUR (poolVolume x UNITCAPACITY) / RATEOFFLO
N W
/**
* Compute the pool’s volume as the result of
* volume x UNITCAPACITY / RATEOFFLOW
* and return double
*/
public double timeToFill( ) {
double myPool;
METHOD totalCost
INPUT
OUTPUT double
COMPUTE the total fuel cost as
monCost + tuesCost + wedCost + thursCost + friCost
RETURN the computed value
METHOD averageCost
INPUT
OUTPUT double
CALL totalCost() to obtain the total cost of fuel
COMPUTE totalCost() /5
RETURN the computed value
Summary
Lecture 12
Arithmetic and the Math Class
Overview
Expressions
Operator Precedence
Operator Precedence
Operators Precedence
postfix expr++ expr--
unary ++expr --expr
multiplicative * / %
additive + -
assignment = += -= *= /= %=
Dividing by Zero
will result in
5.0 / 0.0 Infinity
0.0 / 0.0 NaN
Approximation Functions
double ceil(double a)
Returns the smallest double value that is greater than or
equal to the argument and is equal to a mathemat- ical
integer. Eg Math.ceil(10.2) returns 11.0
double floor(double a)
Returns the greatest double value that is less than or
equal to the argument and is equal to a mathematical
integer. Eg Math.floor(10.2) returns 10.0
long round(double a)
(int) Returns the integer closest to its argument. Eg
long
Math.round(10.2) returns 10
double rint(double a)
Returns the double value that is closest in value to the
argument and is equal to a mathematical integer. Eg
Math.rint(10.2) returns 10.0
double abs(double a)
It returns the absolute value of its input.
Eg Math.abs(-43.433) returns 43.433 and
Math.abs(743.97) returns 743.97.
double max(double a, double b)
Returns the greater of a and b.
Eg Math.max(543.2,532.0) returns 543.2.
double min(double a, double b)
Returns the smaller of a and b.
Eg Math.min(543.2,532.0) returns 532.0.
Note abs, max, min also have versions for int, long and float
which take and return parameters all of the same type.
Trigonometric functions
double sin(double a)
Returns the trigonometric sine of its argument (con-
sidered as an angle measured in radians).
double cos(double a)
Returns the trigonometric cosine of its argument
(considered as an angle measured in radians).
double tan(double a)
Returns the trigonometric tangent of its argument
(considered as an angle measured in radians).
double toDegrees(double angrad)
Converts an angle measured in radians to an approx-
imately equivalent angle measured in degrees.
double toRadians(double angdeg)
Converts an angle measured in degrees to an approx-
imately equivalent angle measured in radians.
docs.oracle.com/javase/7/docs/api/java/lang/Math.html
Problem
Write a program that calculates and outputs the circumference
and area of a circle given its radius.
radius
Hints:-
assume that the radius is input by the user as a double;
the area of a circle = π x radius2 ; Circumference
= π x diameter = 2 x π x radius; Use the constant
PI from the Math class.
Clare Dixon Arithmetic and the Math Class 71 / 81
Lecture 10 Lecture 11 Lecture 12
Class Analysis
Class Diagram
Circle
CircleUser
✲
- radius: double
+circumference(): double
+ main(String[])
+area(): double
Processing
The main method has the usual simple task of setting up all
relevant variables, then calling the area and circumference
methods and finally displaying the result of the computation.
METHOD main
INPUT args
OUTPUT
LOCAL DATA rad
READ rad from the keyboard
SET up an instance myCircle of Circle using rad as
radius of the structure
PRINT the result of calculating the circumference
and area of myCircle
Active Behaviours
/**
* CircleUser.java - michele
* Fri Oct 19 2007 11:35:59
* Edited by Clare Dixon June 2010
**/
import java.util.Scanner;
rad = input.nextDouble();
myCircle = new Circle(rad);
System.out.println("Circumference = " +
myCircle.circumference());
System.out.println("Area = " + myCircle.area());
}
}
Arithmetic Testing
$ java CircleUser
What’s the circle radius? 0.0
Circumference = 0.0
Area = 0.0
$ java CircleUser
What’s the circle radius? -10.0
Circumference = -62.83185307179586
Area = 314.1592653589793
$
Summary