0% found this document useful (0 votes)
45 views

Algorithm Design: COMP101: Introduction To Programming in JAVA

This document provides an overview of algorithm design and pseudocode standards from Lecture 10 of a course on Introduction to Programming in Java. It discusses describing computations as sequences of steps, using pseudocode to describe processes without language syntax, and conventions for pseudocode including common actions, object interactions, and method definitions. It also provides examples of pseudocode for computing the time to fill a swimming pool.

Uploaded by

Kani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Algorithm Design: COMP101: Introduction To Programming in JAVA

This document provides an overview of algorithm design and pseudocode standards from Lecture 10 of a course on Introduction to Programming in Java. It discusses describing computations as sequences of steps, using pseudocode to describe processes without language syntax, and conventions for pseudocode including common actions, object interactions, and method definitions. It also provides examples of pseudocode for computing the time to fill a swimming pool.

Uploaded by

Kani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Lecture 10 Lecture 11 Lecture 12

Lecture 10
Algorithm Design

COMP101: Introduction to Programming in JAVA

Reading: Morelli Chapter 0, Chapter 2, Chapter 3, Cohoon and


Davidson Chapter 1. For pseudocode see
users.csc.calpoly.edu/∼jdalbey/SWE/pdl_std.html

Algorithm Design 1 / 81
Lecture 10 Lecture 11 Lecture 12

Introduction

We are describing a process that should be used when solving


a given programming problem in Java.

First we talked about problem decomposition into classes and


their attributes and representing these using class diagrams.

Several questions are still unanswered:

How do we find out what computation is needed to solve a


particular problem?

How do we describe such computation?

How do we translate such description into working Java code?

Algorithm Design 2 / 81
Lecture 10 Lecture 11 Lecture 12

Describing Computations

The underlying assumption in our approach is that any


computation (in fact almost any process you can think of) can be
described by a sequence of steps each being, in turn, a (simpler)
computation.
Thus processes like:
Go to the local shop to buy milk
Prepare spaghetti carbonara
Search through a list of items to find a particular one
Write a book
Create the best video-game ever
Write a Java program

can all be described in terms of a sequence of steps that need


to be completed to achieve the particular goal.

Algorithm Design 3 / 81
Lecture 10 Lecture 11 Lecture 12

Pseudocode standards

The pseudocode language is a kind of structured English for


describing processes.
It allows the designer to focus on the logic of the process
without being distracted by details of language syntax.

A pseudocode description needs to be complete: it should


describe the entire logic of the particular process so that
implementation becomes a mechanical task of translating line
by line into source code.
The vocabulary used should be that of the problem domain,
not of Java. The pseudocode is a narrative for someone who
knows the requirements (problem domain) and is trying to
learn how the solution is organised.

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.

There is no universal standard.

Remember it is intended to be read by humans not computers.

The format below inspired by


http://users.csc.calpoly.edu/∼ jdalbey/SWE/pdl_std.html
is recommended for COMP101.

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”

We will look at pseudocode for selection and iteration in later


weeks when we cover these issues in Java.
Algorithm Design 6 / 81
Lecture 10 Lecture 11 Lecture 12

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

Common Action Keywords

Several keywords are often used to indicate common input,


output, and processing operations.

Input: READ , OBTAIN , GET


Output: PRINT , DISPLAY , SHOW
Compute: COMPUTE , CALCULATE ,
DETERMINE
Initialize: SET
Add one: INCREMENT

Algorithm Design 8 / 81
Lecture 10 Lecture 11 Lecture 12

Object Interactions

Method invocation and message exchanging is achieved by


specifying, in plain English, the name of the object that is called
into action, the service (method, operation, functionality) asked
from the named object and the data needed to carry out the
particular task.
Examples.
The Swimming Pool object myPool computes the volume of
the pool

[The current object is to] Generate an instance of the Swimming


Pool of length 5, width 4 and depth 2.

Debit the Client account with ChequeAmount

Algorithm Design 9 / 81
Lecture 10 Lecture 11 Lecture 12

Method definition

Methods are defined by specifying their name, their input data


and the type of result they produce.
Example. Carrying on from one of the examples on the
previous slide one may define
METHODDebit Account
INPUT ChequeAmount : double
OUTPU None
T
...
<pseudocode describing the processing>
...

Algorithm Design 10 / 81
Lecture 10 Lecture 11 Lecture 12

Golden Rules

The main purpose of using pseudocode is to describe the


system processing at an abstract level (!)
Rule 1 As mentioned before, one should avoid language
specific constructs. The description should be in
the language of the problem domain.
Rule 2 If a pseudocode description is about the same
length as the corresponding actual code it is
probably too long!

A pseudocode description for a method involving essentially a


single Java statement is NOT NEEDED! Carefully chosen
names for the method and its parameter list give enough
information about its purpose.

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?

For relatively simple programming tasks (similar to those that


we will consider) one possible approach is to perform a
two-level step-wise refinement process:
1 Decompose the task at hand in a number (usually much
less than ten) of sub-tasks
2 Reduce the sub-tasks to Java instructions
For complex tasks (these are not the type of problems we will
consider in this module) usually people apply patterns. A number
of computational problems have been studied in the literature.
Given a new programming task it is often possible to reduce it to
a combination of well-known tasks that are then solved by
applying standard well-known techniques.
Algorithm Design 12 / 81
Lecture 10 Lecture 11 Lecture 12

Examples: Computing timeToFill()

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

From our verb analysis we decided we needed the calculation


of the time it takes to fill the pool.
This will be a number, resulting from some calculations. We
need to:
1 decide who’s going to have responsibility of computing this;
2 think about its input data, return value and their types;
3 define a method that will perform such computation (let’s
call it timeToFill).

Algorithm Design 14 / 81
Lecture 10 Lecture 11 Lecture 12

Responsibilities

The responsibility for computing this could be either given to the


SwimmingPoolUser class, in which case the method needs to get the
values for length, width, and depth from somewhere else as the
attributes in the SwimmingPool class are private to that class.

Alternatively the operation could be assigned to the SwimmingPool


class, in which case the pool sizes would be available to the
operation and no additional input data is needed.
This looks like part of the behaviour of SwimmingPool so we will put
it there. Thus if SwimmingPool is re-used in other programs all the
relevant methods will be provided.

Algorithm Design 15 / 81
Lecture 10 Lecture 11 Lecture 12

Scenarios

1 If the swimming pool contained 1 cubic metre of water its


capacity would be 1,000 litres (this is in the problem statement!).
If it takes a minute to pour 50 litres of water in the pool it would
take
1,000
50
= 20 minutes to fill such a pool.
2 By a similar argument, if the swimming pool contained 5 cubic
metres of water it would take
5× 1,000
50
= 100 minutes to fill it.
3 Generalising, if the swimming pool contained x cubic metres of
water this number should be multiplied by the unit capacity and
divided by the rate of flow to give the correct answer. Thus we
get the answer (in minutes) from the Java expression

x * UNITCAPACITY / RATEOFFLOW

Clare Dixon Algorithm Design 16 / 81


Lecture 10 Lecture 11 Lecture 12

Technical Issue
Conceptually X is the volume of the pool.

Since the problem statement talks of a rectangular swimming


pool of uniform depth x is the volume of a cuboid.
Instead of x lets use poolVolume

poolVolume = length * width * depth

We assume that input lengths are in metres.


Clare Dixon Algorithm Design 17 / 81
Lecture 10 Lecture 11 Lecture 12

Pseudocode for timeToFill()

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

Remark. It is arguable whether the given pseudocode is


actually needed. In effect timeToFill is formed by a single line
of code. A pseudocode description is a bit of an overkill. (It was
given here for pedagogical reasons.)

Clare Dixon Algorithm Design 18 / 81


Lecture 10 Lecture 11 Lecture 12

The main method

Assuming SwimmingPool gets the responsibility of running the


method timeToFill, the pseudocode for the main method is as
follows.

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.

Clare Dixon Algorithm Design 19 / 81


Lecture 10 Lecture 11 Lecture 12

Another Example: Average Fuel Consumption

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

Clare Dixon Algorithm Design 20 / 81


Lecture 10 Lecture 11 Lecture 12

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.

We decided that we needed two methods totalCost and


averageCost.

Where are these located?–For similar reasons as with


timeToFill() we will put them in the FuelCost class.

What is their return type?–Probably double as we need to


perform calculations on values that are doubles.
What pseudocode is needed for these methods? What
pseudocode is needed for the main method?
Clare Dixon Algorithm Design 21 / 81
Lecture 10 Lecture 11 Lecture 12

Summary

We have shown how to use pseudocode to write down the


behaviour of parts of the program.
We have applied this to examples.

Clare Dixon Algorithm Design 24 / 81


Lecture 10 Lecture 11 Lecture 12

Lecture 11
More About Methods

COMP101: Introduction to Programming in JAVA

Reading: Morelli Chapter 3, Cohoon and Davidson Chapters 2


and 4

Clare Dixon More About Methods 25 / 81


Lecture 10 Lecture 11 Lecture 12

Overview

In this lecture we have a closer look at methods.


We look at the flow of control when using methods and
how to pass information to the methods.
We also discuss the scope and lifetime of identifiers.
We give the implementation of the timeToFill() method
from the SwimmingPool class.

Clare Dixon More About Methods 26 / 81


Lecture 10 Lecture 11 Lecture 12

Methods

One of the core features of the objects in an object-oriented


system is that they should be able to “do things”.
Methods specify the “things” that objects in a given class can
do.

A method is a group of self-contained declarations and


executable statements that performs a specific task or
operation.

As we have already seen Java methods have the following


format.
Modifiers ReturnType Name (ParamList) { StatementList }

Clare Dixon More About Methods 27 / 81


Lecture 10 Lecture 11 Lecture 12

Methods: Example

The following was a method in the Rectangle class to calculate


the area of the rectangle.
// Method that returns the area of the rectangle.
public int calculateArea() {
return length *width;
}

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();
}

Clare Dixon More About Methods 28 / 81


Lecture 10 Lecture 11 Lecture 12

Methods Control Flow

// program to demonstrate how to call a


// programmer-defined method
public class TestMethodsControlFlow {

public static void main(String [] args) {


System.out.println("Execution starts in [main] method;");
display();
System.out.println("back to the [main] method.");
}

// method to display a message


public static void display() {
System.out.println(" method [display] is then called;");
}
}

>>>How does it work?<<<

Clare Dixon More About Methods 29 / 81


Lecture 10 Lecture 11 Lecture 12

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.
$

Clare Dixon More About Methods 30 / 81


Lecture 10 Lecture 11 Lecture 12

The return Keyword

// program to demonstrate calling a method that returns


// a value
import java.util.Scanner;

public class TestMethodsWithReturnValue {

public static void main(String[] args) {


System.out.println("The sum is " + sum());
}

public static int sum() {


int first, second; // numbers to input
Scanner input = new Scanner(System.in);
System.out.print("First number? ");
first = input.nextInt();
System.out.print("Second number? ");
second = input.nextInt();
return first+second;
}
}

Clare Dixon More About Methods 31 / 81


Lecture 10 Lecture 11 Lecture 12

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

Methods can receive data from the calling method in several


ways.

We will comment on each of the available possibilities by


referring to the same basic piece of code.

Clare Dixon More About Methods 33 / 81


Lecture 10 Lecture 11 Lecture 12

Class or Instance Variables


// program to demonstrate calling a method that
// uses class or instance variables.
import java.util.Scanner;

public class TestMethodsWithClassVars {


private static int first, second; // numbers to input

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("First number? ");
first = input.nextInt();
System.out.print("Second number? ");
second = input.nextInt();
System.out.println("Sum of numbers is " + sum());
System.out.println("First number is now " + first);
}

public static int sum() {


first = first + second;
return first;
}
}
Clare Dixon More About Methods 34 / 81
Lecture 10 Lecture 11 Lecture 12

Remarks

As first and second are class variables they are accessible


throughout the class, even in the method sum().
Assigning first + second to first in sum() means the value of first will
have changed in the main method.
What is output if we input 10 and 5?
The static modifier was added to the declarations of first
and second otherwise Java would complain as follows:
TestMethodsWithReturnValue.java:12: non-static variable first cannot be
referenced from a static context
first = input.nextInt();
ˆ

What happens if the declarations of first and second are


moved inside main?

Clare Dixon More About Methods 35 / 81


Lecture 10 Lecture 11 Lecture 12

Method Parameters
// program to demonstrate calling a method that receives its
// data through a parameter list.
import java.util.Scanner;

public class TestMethodsWithParameterPassing {


public static int first, second; // numbers to input

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
System.out.print("First number? ");
first = input.nextInt();
System.out.print("Second number? ");
second = input.nextInt();
System.out.println("Sum of numbers is " +
sum(first, second));
System.out.println("First number is now " + first);
}

public static int sum( int f, int s) {


f = f+s;
return f;
}
} Clare Dixon More About Methods 38 / 81
Lecture 10 Lecture 11 Lecture 12

Remarks

How do things work in this case?


Here parameters are variables of primitive data type.
The parameter list in the method call must contain the
same number of elements, in the same order and of the
same type as the parameter list in the method definition.
When sum(first, second) is called from the main method the values
of the actual parameters (first and second) are evaluated and
copied as values for the formal parameters (f and s). This is
known as passing by value.
Any changes to the formal parameters (assigning f+s to f) will
not affect the actual parameters, i.e. here first and second are
not affected by the method call.
Question: what would happen if the parameters were
called first and second?
Clare Dixon More About Methods 39 / 81
Lecture 10 Lecture 11 Lecture 12

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.

In such cases the actual address of the variable is passed to


the calling method. Consequently, any change that happens to the
parameters inside the called method will remain after the control
is returned to the caller.

This is similar to what happens when we assign one object to


another.
Rectangle rect2 = new Rectangle(); Rectangle bigRect =
new Rectangle(100,35); rect2 = bigRect;

both bigRect and rect2 will refer to the same object.


Clare Dixon More About Methods 41 / 81
Lecture 10 Lecture 11 Lecture 12

Reference Parameters II

public class TestMethodsWithObjectParameters {


// ---------------METHODS-------------
/* Main Method */
public static void main(String[] args) {
// Instantiate up bigRect
Rectangle bigRect = new Rectangle(100,35);

// Print out its length and width


System.out.println("The Big Rectangle’s dimensions");
bigRect.printDimensions();

// Call changeRectangle using bigRect as parameter and print


Rectangle newRect = changeRectangle(bigRect);
System.out.println("After calling changeRectangle(bigRect) ");
newRect.printDimensions();

Clare Dixon More About Methods 42 / 81


Lecture 10 Lecture 11 Lecture 12

Reference Parameters III


// Print out the Big Rectangle’s length and width again
System.out.println("The Big Rectangle’s dimensions ");
bigRect.printDimensions();
}

public static Rectangle changeRectangle(Rectangle theRect) {


theRect.setLength(50);
return theRect;
}
}

This has the following output


$ java TestMethodsWithObjectParameters
The Big Rectangle’s dimensions
Length: 100 Width: 35

After calling changeRectangle(bigRect)


Length: 50 Width: 35

The Big Rectangle’s dimensions


Length: 50 Width: 35
$
Clare Dixon More About Methods 43 / 81
Lecture 10 Lecture 11 Lecture 12

Reference Parameters IV

length = 100 length = 50


bigRect bigRect
width =35 width =35

theRect
length = 100
bigRect
width =35

length = 50
theRect bigRect
width = 35

newRect

Clare Dixon More About Methods 44 / 81


Lecture 10 Lecture 11 Lecture 12

Scope and Lifetime of Identifiers

1 The scope of an identifier refers to the region of a


program in which an identifier can be used.
2 An identifier with class scope is accessible throughout the
entire class and anywhere in the program where an object X
of the given class is defined, prefixed by “X.” (dependent on
modifiers eg public).
3 A block is any segment of code beginning with a { and
ending with a }.
4 An identifier with block or local scope is accessible from its
point of declaration throughout the entire block in which it
is defined.

Clare Dixon More About Methods 45 / 81


Lecture 10 Lecture 11 Lecture 12

Remarks

Method parameters can be thought of as having block or


local scope. They are only accessible within the body of
the method they refer to.
Class attributes are examples of variables having class
scope.
Method names give another example of identifiers having
class scope.

Clare Dixon More About Methods 46 / 81


Lecture 10 Lecture 11 Lecture 12

Scope of Identifiers

// program to demonstrate calling a method that receives its


// data through a parameter list.
import java.util.Scanner;

class TestMethodsWithParameterPassing {
private static int first, second; // numbers to input

public static void main(String[] args) {


System.out.print("First number? ");
first = new Scanner(System.in).nextInt();
System.out.print("Second number? ");
second = new Scanner(System.in).nextInt();
System.out.println("Sum of numbers is " + first, second and sum()
sum1(first, second)); have class scope
System.out.println("First number is now " + first);
}

public static int sum( int f, int s) {


f = f+s; f, s have local or
return f; block scope
}
}

Clare Dixon More About Methods 47 / 81


Lecture 10 Lecture 11 Lecture 12

Lifetime

The lifetime of an identifier is the period during which the


value of the identifier exists in the computer memory.

identifiers with block scope only exist during the execution


of the particular block.
When an object goes out of scope garbage collection takes
place.

Clare Dixon More About Methods 48 / 81


Lecture 10 Lecture 11 Lecture 12

Back to the Swimming Pool

Recall we had the following pseudocode for the method


timeToFill located in the SwimmingPool class.

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

Clare Dixon More About Methods 49 / 81


Lecture 10 Lecture 11 Lecture 12

Implementation of the method TimeToFill()

/**
* Compute the pool’s volume as the result of
* volume x UNITCAPACITY / RATEOFFLOW
* and return double
*/
public double timeToFill( ) {
double myPool;

myPool = length * width * depth;


return myPool UNITCAPACITY
* / RATEOFFLOW;
}

Clare Dixon More About Methods 50 / 81


Lecture 10 Lecture 11 Lecture 12

FuelCost: Pseudocode for totalCost and averageCost

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

How can we implement these?

Clare Dixon More About Methods 51 / 81


Lecture 10 Lecture 11 Lecture 12

Summary

We had a closer look at methods with respect to flow of


control and parameter passing.
We mentioned scope of lifetime of identifiers.
We gave the implementation of the timeToFill() method from
the SwimmingPool class.

Clare Dixon More About Methods 53 / 81


Lecture 10 Lecture 11 Lecture 12

Lecture 12
Arithmetic and the Math Class

COMP101: Introduction to Programming in JAVA

Morelli chapter 5, Cohoon and Davidson Chapter 2

Clare Dixon Arithmetic and the Math Class 54 / 81


Lecture 10 Lecture 11 Lecture 12

Overview

We introduce some of the features of the Math Class.


We consider the analysis and design, implementation and
testing of a program to calculate area and circumference of a
circle given its radius.
We discuss arithmetic testing with respect to this program.

Clare Dixon Arithmetic and the Math Class 55 / 81


Lecture 10 Lecture 11 Lecture 12

Expressions

Java supports the standard binary algebraic operators “+”, “-”,


“×” and “/” (plus the remainder operator).

Recall that Java expressions may look different from their


algebraic counterpart:

Operator Java Algebra


+ x+2 x+2
- m-2 m−2
× m * 2m or 2 × m
/ 2 /y
x x ÷y or xy
remainder x % y x mod
y

Clare Dixon Arithmetic and the Math Class 56 / 81


Lecture 10 Lecture 11 Lecture 12

Division and Remainder

Recall when applied to two integers / uses integer division.


The result is the integer part of the usual division result.
In Java 11/2 evaluates to 5, 6/2 evaluates to 3 as does 7/2.

x % y gives the remainder after dividing x by y.


In Java 11 % 2 evaluates to 1, 6 % 2 evaluates to 0, and
7 % 2 evaluates to 1.

What is the result of 12/6 and 13/6?

What is the result of 12 % 6 and 13 %


6?

Clare Dixon Arithmetic and the Math Class 57 / 81


Lecture 10 Lecture 11 Lecture 12

Abbreviations: The Increment Operators

Java provides a number of unary operators that are used to


increment or decrement an integer variable. So k++ (or, resp. k--)
has the effect of adding (resp. subtracting) one to (from) the
variable k and assigning the resulting value to k.
Both ++k and k++ (or --k and k--) are valid increment expressions, but
with different meanings: here’s the explanation in the case of
positive increment,

The expression j = ++k corresponds to an increment of k


and then the assignment of the resulting value to j. On the
other hand in j = k++ the initial value of k is assigned to
variable jfirst and then k is increased.

Be careful when using these.

Clare Dixon Arithmetic and the Math Class 58 / 81


Lecture 10 Lecture 11 Lecture 12

Other Shortcut Operators

Similarly Java supplies a number of “shortcut” assignment


operators. Their format and interpretation is given in the
following table:

concise form equivalent verbose expression


a += b a = a + b
a -= b a a = a- b
*= b a a = a * b
/= b a a = a /b
%= b a = a % b

Note that expressions such as a =* b are not allowed.

Clare Dixon Arithmetic and the Math Class 60 / 81


Lecture 10 Lecture 11 Lecture 12

Operator Precedence

In the next table the operators we have seen so far are


listed according to precedence order, the closer to the top of
the table, the higher its precedence.
Operators with higher precedence are evaluated before
operators with lower precedence.
Operators on the same line have equal precedence.
When operators of equal precedence appear in the same
expression all binary operators, except for the assignment
operators, are evaluated from left to right; assignment
operators are evaluated right to left.

Clare Dixon Arithmetic and the Math Class 61 / 81


Lecture 10 Lecture 11 Lecture 12

Operator Precedence

Operators Precedence
postfix expr++ expr--
unary ++expr --expr
multiplicative * / %
additive + -
assignment = += -= *= /= %=

Thus result = 3 * 8 + 2 will evaluate to the same as


result = ((3 * 8) + 2).

To ensure clarity and prevent errors use brackets.

Clare Dixon Arithmetic and the Math Class 62 / 81


Lecture 10 Lecture 11 Lecture 12

Dividing by Zero

When programming always take care to avoid dividing by zero.


In Java
System.out.println("5 /0 " + 5/ 0);

will result in the following run-time error.


Exception in thread "main" java.lang.ArithmeticException: / by zero at
TestNaN.main(TestNaN.java:41)

System.out.println("5.0 / 0.0 " + 5.0 / 0.0);


System.out.println("0.0 / 0.0 " + 0.0 / 0.0);

will result in
5.0 / 0.0 Infinity
0.0 / 0.0 NaN

NaN is short for is not a number.

Clare Dixon Arithmetic and the Math Class 63 / 81


Lecture 10 Lecture 11 Lecture 12

The Math class

More advanced mathematical computations can be achieved


using operations defined in the Math class.
This class is contained in the java.lang package, included
implicitly in all Java programs (no explicit import needed!).
The class Math contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square
root, and trigonometric functions.
The class cannot be instantiated and all its methods are
Math
static class
methods. Hence they are invoked through the class
name eg Math.round(34.2) to call the method round.
For more details see
docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Clare Dixon Arithmetic and the Math Class 64 / 81


Lecture 10 Lecture 11 Lecture 12

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

Clare Dixon Arithmetic and the Math Class 65 / 81


Lecture 10 Lecture 11 Lecture 12

Abs, Max, Min

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.

Clare Dixon Arithmetic and the Math Class 67 / 81


Lecture 10 Lecture 11 Lecture 12

Powers, Square Roots etc

double pow(double a, double b)


The expression Math.pow(a,b) computes and returns the
value ab (as a double).
double sqrt(double a)
Returns the square root of its argument. Eg
Math.sqrt(25.0) returns 5.0
double cbrt(double a)
Returns the cube root of its argument.
Eg Math.cbrt(8.0) returns 2.0.

Clare Dixon Arithmetic and the Math Class 68 / 81


Lecture 10 Lecture 11 Lecture 12

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.

Clare Dixon Arithmetic and the Math Class 69 / 81


Lecture 10 Lecture 11 Lecture 12

More About the Math class


Many other trigonometric functions eg the inverse functions
asin, acos, and atan are also provided.

The following useful numbers are denoted by the constants in the


Math class:
e = 2.718281828459045 . . . is Math.E; and
π = 3.141592653589793 . . . is Math.PI.
This is only a very short review of the Math class. We
did not cover all its methods and
even when we did cover a method we only provided a very
short description of its behaviour.

For more details read the full description available from

docs.oracle.com/javase/7/docs/api/java/lang/Math.html

Clare Dixon Arithmetic and the Math Class 70 / 81


Lecture 10 Lecture 11 Lecture 12

Example: Circle Calculation

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

Very little analysis needed. The statement talks of a Circle (a


class) which has a radius (an attribute).

The system is supposed to calculate the circumference and the


area of the circle. The use of the word “calculate” should lead us
to believe that we will need to define methods for doing this.

We assume that Circle does the relevant calculations and we


have a CircleUser class that allows the input of the circumference,
instantiates Circle and displays the results of the calculations.

A possible class diagram is on the next slide.

Clare Dixon Arithmetic and the Math Class 72 / 81


Lecture 10 Lecture 11 Lecture 12

Class Diagram

Circle
CircleUser

- radius: double
+circumference(): double
+ main(String[])
+area(): double

Note that we are assigning the responsibility of computing


circumference and area of the circle to the Circle class.

Clare Dixon Arithmetic and the Math Class 73 / 81


Lecture 10 Lecture 11 Lecture 12

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

Clare Dixon Arithmetic and the Math Class 74 / 81


Lecture 10 Lecture 11 Lecture 12

Active Behaviours

The class Circle is responsible for computing the circumference


and the area of the circle
Recall that the circumference of a circle having radius r is
2 × π × r , whereas the area of the circle is πr 2 .
We will not need to write any pseudocode for this.
When this will become Java code we may use the constant
Math.PI to get an (approximate) value for π = 3.141592... and we
may use Math.pow to compute r 2 needed in the formula for the
area of the circle, or we could just use the expression radius
radius.

Clare Dixon Arithmetic and the Math Class 75 / 81


Lecture 10 Lecture 11 Lecture 12

The Circle Class


/**
* Circle.java - michele
* Fri Oct 19 2007 11:36:59
* Edited by Clare Dixon June 2010
**/
public class Circle {
// attributes
private double radius;
// constructors
public Circle(double r) {
radius = r;
}
// calculates the circumference of a circle given radius
public double circumference() {
return 2*Math.PI*radius;
}
// calculates the area of a circle given radius
public double area() {
return Math.PI*radius*radius;
}
}

Clare Dixon Arithmetic and the Math Class 76 / 81


Lecture 10 Lecture 11 Lecture 12

The CircleUser Class

/**
* CircleUser.java - michele
* Fri Oct 19 2007 11:35:59
* Edited by Clare Dixon June 2010
**/
import java.util.Scanner;

public class CircleUser {


public static void main(String [] args) { Circle myCircle;
Scanner input = new Scanner(System.in);
double rad;
System.out.print("What’s the circle radius? ");

rad = input.nextDouble();
myCircle = new Circle(rad);
System.out.println("Circumference = " +
myCircle.circumference());
System.out.println("Area = " + myCircle.area());
}
}

Clare Dixon Arithmetic and the Math Class 77 / 81


Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing

Given an arithmetic statement it is always a good idea to


test the effect that negative, positive and zero sample
values will have on the outcome.
In this case there is only one numeric input, we should
therefore test negative and positive inputs as well as zero.
If there is more than one input we should test every
possible combination of positive, negative and zero input.
Thus if we have two inputs we would have 3x3 possible
combinations, with three inputs 3x3x3 possible combinations
(and so on).
This form of testing is known as arithmetic testing.

Clare Dixon Arithmetic and the Math Class 78 / 81


Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing: The Circle

Test Case Expected Result


Radius Circumference Area
10.0 62.832 314.159
0.0 0.000 0.000
-10.0 -62.832 314.159

Note that when we input a negative number we produce a


negative circumference - this is probably not the desired result.
We should return to the requirements phase and determine
what action we should take in the event of a negative radius.
What might this be?
However with our current level of programming skills we will just
have to ”live with this undesirable result”.
Clare Dixon Arithmetic and the Math Class 79 / 81
Lecture 10 Lecture 11 Lecture 12

Arithmetic Testing: Output

The following is the actual output.


$ java CircleUser
What’s the circle radius? 10.0
Circumference = 62.83185307179586
Area = 314.1592653589793

$ 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
$

How could we improve on the presentation of this output?

Clare Dixon Arithmetic and the Math Class 80 / 81


Lecture 10 Lecture 11 Lecture 12

Summary

We introduced some of the features of the Math Class


We considered the analysis and design of a program to
calculate some values of a circle given its radius.
We gave the implementation of these classes.
We discussed arithmetic testing with respect to our
program.

Clare Dixon Arithmetic and the Math Class 81 / 81

You might also like