1 / 39

Problem Solving

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?

germainer
Télécharger la présentation

Problem Solving

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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?

  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?

  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?

  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

  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?

  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)

  7. Mixed expression examples • Be careful! What are the values of the following, and what is the type of the result?

  8. Problem Solving and Program Design • [now at chapter 3 in the text] • Requirements • Design • Coding • Testing and/or verification • Maintenance • All of the above should be documented as you go along.

  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)

  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.

  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.

  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.

  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

  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

  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.

  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.

  17. Branching Control Structure Test false true program code program code • 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.

  18. Test false true block 1 block 2 Branches in Java • Java : if ( /* put test here */ ) { // block2 } else { // block1 }

  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.

  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 }

  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 beboolean, but the result of the comparison isboolean • Join two Boolean expressions • AND (Java: && ) • OR (Java: ||)

  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

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

  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: • two real values for x • one real value for x • no real values for x

  25. Flow diagram b2 – 4ac > 0 True False b2 – 4ac < 0 False True x1 = –b/2a No solutions

  26. Flow diagram, version 2 d = b2 – 4ac False True d > 0 d < 0 False True x1 = –b/2a No solutions

  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

  28. Flow diagram d = b2 – 4ac False d > 0 True d < 0 True False x1 = –b/2a

  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: • two real values for x • one real value for x • no real values for x

  30. Flow diagram b2 – 4ac > 0 True False b2 – 4ac < 0 False True x1 = –b/2a No solutions

  31. Flow diagram, version 2 d = b2 – 4ac False True d > 0 d < 0 False True x1 = –b/2a No solutions

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

  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

  34. Flow diagram d = b2 – 4ac False d > 0 True d < 0 True False x1 = –b/2a

  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

  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.

  37. The switch statement true case 1 statement block 1 break; false true case 2 statement block 2 break; false true case n statement block n break; false defaultstatement block

  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.”); }

  39. Missing break statement true case 1 statement block 1 false true case 2 statement block 2 break; false true case n statement block n break; false defaultstatement block

More Related