1 problem solving we now have enough tools to start solving some problems. for any problem, before...

39
1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: What are the input values that are needed from the user? What results (outputs) do we need to determine? What other values are needed? • math constants: , e, etc. • physical constants What temporary values might need to be calculated? How do we calculate the results?

Upload: horatio-gray

Post on 03-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

1

Problem Solving

• We now have enough tools to start solving some problems.

• For any problem, BEFORE you start writing a program, determine:– What are the input values that are needed from

the user?– What results (outputs) do we need to

determine?– What other values are needed?

• math constants: , e, etc.• physical constants

– What temporary values might need to be calculated?

– How do we calculate the results?

Page 2: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

2

Example 1

• Calculate the area of a circle from its radius• what input values do we need?• what other values do we need?• what is our output?• how do we calculate the result?

Page 3: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

3

Example 2

• Calculate the distance travelled by an object under constant acceleration, given a specified time.– What input values do we need?– What other values do we need?– What is the result?– How do we calculate the result?

Page 4: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

4

Example 3:

• Carbon-14 dating– General radioactive decay equation:

• Q0: initial quantity of radioactive substance

• Q(t): quantity of radioactive substance at time t (in years)

: radioactive decay constant for a specific element

• Q(t) = Q0e–t is the rate of decay equation

– Carbon-14 is continuously taken in by a living organism, and the amount of material at death is assumed to be known.

– Once the intake stops, the carbon-14 decays at the above rate, where = 0.00012097 / year

– Measure the percentage of carbon-14 remaining

Page 5: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

5

Example 3 continued:

• Solve for t to determine the age:

• Another useful thing to know: if half of the Carbon-14 remains, the sample is about 5730 years old.

• Create a Java program to determine the age:– what are the inputs?– what are the outputs?– what other values do we need?– how do we calculate the formula?

0log

1

Q

Qtdecay

Page 6: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

6

Expressions with mixed data types

• [See text, sections 2.4.4 and 2.4.5]• In general, you cannot mix data types in Java for either

variables or constants.• However, for numeric data types (int, long, float,

double), there are some permitted exceptions.– Example:

double aVariable = 1 + 2.3;• The int constant 1 is temporarily converted to the double value 1.0, and aVariable is assigned the value of 1.0 + 2.3, namely 3.3.

– In a mixed expression, the value for a more restrictive data type (e.g. int) is temporarily converted to a less restrictive data type (e.g. double)

– You cannot assign a value from a less restrictive data type to a more restrictive data type (example: double to int is not permitted)

Page 7: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

7

Mixed expression examples

• Be careful! What are the values of the following, and what is the type of the result?

Expression Result Type

1 + 1/4 1 int

1.0 + 1/4 1.0 double

1.0 + 1.0/4 1.25 double

1 + 1.0/4 1.25 double

1.0 + 1/4.0 1.25 double

1 + 1/4.0 1.25 double

1 + 1.0/4.0 1.25 double

1.0 + 1.0/4.0 1.25 double

Page 8: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

8

Problem Solving and Program Design

• [now at chapter 3 in the text]1. Requirements2. Design3. Coding4. Testing and/or verification5. Maintenance• All of the above should be documented as you go

along.

Page 9: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

9

Requirements

• Requirements are the elements of the problem related to a user.

• Challenges with requirements:– Need to describe what is the problem, NOT

how to solve it.– Requirements are often described imprecisely,

or are incomplete.• Such requirements often lead to problems

later on because the program designer made an assumption that was different from the users.

• Often described using scenarios (sample user sessions)

Page 10: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

10

Requirements

• Two types of requirements:– Functional: requirements directly related to the problem

at hand • example: determine age of sample given carbon-14

percentage– Non-functional: other indirect requirements

• examples: requirements related to usability, performance, reliability, use of specific hardware

• Requirements should be verifiable: it should be possible to determine clearly whether or not the requirement has been met.– Bad example: program should be “fast”– Good example: program should run scenario X in no

more than 2 seconds.

Page 11: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

11

Design

• This is where the problem is solved.• The solution has to take into account:

– Data: structure and format of data related to the problem and solution

– Algorithm: sequencing of steps needed to solve the problem

– Events: occurrences to which the program must react– Constraints: limitations of resources that are available

(e.g. amount of memory, processor speed)

• Several potential solutions may be available, and the choice would be made in terms of memory efficiency, speed, ease of implementation, etc.

Page 12: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

12

Coding

• This is where the program is created.• Once you are familiar with a programming

language, only about 10-15% of the time involved in problem solving should be used for coding.

• The real thinking should be during the design phase and translating a design to program code should be almost mechanical.

Page 13: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

13

Testing and Verification

• Testing: running a set of experiments to see if the program works– Run the program with input data, and see if it

produces the expected output– Does not prove that the program always works

• Verification: determining that the program will run in all cases– Extremely difficult to do; usually only

attempted for small critical sections of software (e.g. nuclear plant control, flight control)

– Requires either a mathematical proof, or model-checking techniques

Page 14: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

14

Testing

• Can be a large part of time and cost of developing a program.

• Testing the program is separate from finding the actual cause of any errors that are found.– “Debugging”: determining what caused a

problem

• Two types of testing:– “Black-box”: the testing assumes no knowledge

of how the program works; inputs are given to the program and the output is checked.

– “White-box”: testing is based on knowledge of the program; objective is to ensure that all parts of the program have been used

Page 15: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

15

Maintenance

• Once a program has been developed, the program will often be modified.– Resolving problems found by users.– Additional features– Performance improvements– Moved to different system

• Difficulties with maintenance:– Often not done by original designer– Can be done in a hurry, when related to an urgent user

problem.– Care must be taken that changes made do not break

other parts of the program that were working.

Page 16: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

16

Selection of alternatives

• An important control structure in any programming language is the selection of alternatives.

• The selection is normally based on the result of a Boolean expression.– Example: Sell a person an adult movie ticket if

their age is at least 18 and less than 65.– A Boolean test will have two possible

outcomes: true or false. The program may have different statements to execute for each of the two alternatives.

Page 17: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

17

Branching Control Structure

• With a branch, you are choosing one of two alternatives.• After doing one of the alternatives, the flow of control of the

program comes back together.

program codeprogram code

truefalseTest

Page 18: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

18

Branches in Java

• Java : if ( /* put test here */ ) { // block2 } else { // block1 }

block 2block 1

truefalseTest

Page 19: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

19

Blocks

• Whenever we need to identify a group of statements in Java, the statements are enclosed in braces. This is called a “block”.

• A block can be used anywhere in Java where a single statement is appropriate.

• Blocks are particularly used as:– alternatives in branches– sections of code to repeat, when we see how to

do this.

Page 20: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

20

Indentation of block statements

• When starting a new block, the convention is to indent all code inside the block, so that the reader can easily identify which statements are included in the block:

if ( /* put test here */ ) { // block 1, statement 1 // block 1, statement 2 // block 1, statement 3 } else { // block 2, statement 1 // block 2, statement 2 }

Page 21: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

21

Expressions in Tests

• The TEST in a branch may be any Boolean expression:– Boolean variable– Negation of a Boolean expression

• NOT (Java: ! )– Comparison between two values

• Java operators: == != < > <= >=• The data being compared may not

necessarily be boolean, but the result of the comparison is boolean

– Join two Boolean expressions• AND (Java: && )• OR (Java: || )

Page 22: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

22

Expressions in Tests

• Watch out for– confusing = with ==– confusing AND with OR

• e.g. test if X is in the range 12-20:X >= 12 && X <= 20

Page 23: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

23

Example: Maximum of 2 values

• How would we write some code to find the maximum of two int values, x and y? The maximum value is to be stored in variable max.

int x;

int y;

int max;

System.out.println(“Enter value for x: “);

x = Keyboard.readInt();

System.out.println(“Enter value for y: “);

y = Keyboard.readInt();

Page 24: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

24

Example: Solution of Quadratic Equations

• We want to solve for real values of x, for given values of a, b, and c.

• The value of x can be determined from the “well-known” formula:

• Depending on the value of the discriminantwe have 3 cases:1. two real values for x2. one real value for x3. no real values for x

02 cbxax

a

acbbx

2

42

042 acb

042 acb

042 acb

acb 42

Page 25: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

25

Flow diagram

a

acbbx

2

42

2

b2 – 4ac > 0

b2 – 4ac < 0

x1 = –b/2a

False

False

No solutions

Truea

acbbx

2

42

1

True

Page 26: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

26

Flow diagram, version 2

a

dbx

22

d > 0

d < 0

x1 = –b/2a

False

False

No solutions

Truea

dbx

21

d = b2 – 4ac

True

Page 27: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

27

Adding the Complex case

• Suppose we now want to solve for real or complex values of x, for given values of a, b, and c.

• In this case, we can still use the formula

but when we have we will need to be careful to avoid taking a square root of a negative number.

• If we take the square root of the absolute value of the discriminant, we have the complex coefficient

02 cbxax

a

acbbx

2

42

042 acb

Page 28: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

28

Flow diagram

a

dbx

22

d > 0

d < 0

x1 = –b/2a

False

False

True

a

dbx

21

d = b2 – 4ac

ia

d

a

bx

221

ia

d

a

bx

222

True

Page 29: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

29

Example: Solution of Quadratic Equations

• We want to solve for real values of x, for given values of a, b, and c.

• The value of x can be determined from the “well-known” formula:

• Depending on the value of the discriminantwe have 3 cases:1. two real values for x2. one real value for x3. no real values for x

02 cbxax

a

acbbx

2

42

042 acb

042 acb

042 acb

acb 42

Page 30: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

30

Flow diagram

a

acbbx

2

42

2

b2 – 4ac > 0

b2 – 4ac < 0

x1 = –b/2a

False

False

No solutions

Truea

acbbx

2

42

1

True

Page 31: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

31

Flow diagram, version 2

a

dbx

22

d > 0

d < 0

x1 = –b/2a

False

False

No solutions

Truea

dbx

21

d = b2 – 4ac

True

Page 32: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

32

Structure of nested if statements

discriminant = b * b - 4.0 * a * c; if ( discriminant > 0 ) { // We have two real solutions } else { if ( discriminant < 0 ) { // We have no real solutions. } else { // We have one real solution. } }

Page 33: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

33

Adding the Complex case

• Suppose we now want to solve for real or complex values of x, for given values of a, b, and c.

• In this case, we can still use the formula

but when we have we will need to be careful to avoid taking a square root of a negative number.

• If we take the square root of the absolute value of the discriminant, we have the complex coefficient

02 cbxax

a

acbbx

2

42

042 acb

Page 34: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

34

Flow diagram

a

dbx

22

d > 0

d < 0

x1 = –b/2a

False

False

True

a

dbx

21

d = b2 – 4ac

ia

d

a

bx

221

ia

d

a

bx

222

True

Page 35: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

35

Testing for Equality withFloating Point Values

• Because of the possibility of round-off error, testing for equality (or inequality) of float or double values is NOT recommended.

• Instead, test that the value is “close enough” to the desired value by using a tolerance value, and checking that the absolute value of the difference is less than the tolerance:

double EPSILON = 1.0e-10; double x; ... if ( x == 37.0 ) // not recommended ... if ( Math.abs( x – 37.0 ) < EPSILON ) // better

Page 36: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

36

The switch statement

• Allows for multi-way branches• You can only use case statements when the test

is on an integer, Boolean, or character variable.• Idea:

– List various “cases” for specific values of the tested variable, plus one default case for when there is no match.

– Provide a statement block for each case.

• You MUST end each statement block with break; or the program will go to the next following case.

Page 37: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

37

The switch statement

case 1

case 2

case n

statement block 1true

statement block 2true

statement block ntrue

defaultstatement block

false

false

false

break;

break;

break;

Page 38: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

38

Example

System.out.println(“Enter an integer from 1 to 3: “);int a = Keyboard.readInt();switch( a ){ case 1: { System.out.println(“You entered a 1.”); break; } case 2: { System.out.println(“You entered a 2.”); break; } case 3: { System.out.println(“You entered a 3.”); break; } default: { System.out.println(“Incorrect input.”); break; } System.out.println(“After switch.”);}

Page 39: 1 Problem Solving We now have enough tools to start solving some problems. For any problem, BEFORE you start writing a program, determine: –What are the

39

Missing break statement

case 1

case 2

case n

statement block 1true

statement block 2true

statement block ntrue

defaultstatement block

false

false

false

break;

break;