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.

Slides:



Advertisements
Similar presentations
ITEC113 Algorithms and Programming Techniques
Advertisements

Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
C++ for Engineers and Scientists Third Edition
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Implementing Control Logic in C# Svetlin Nakov Telerik Corporation
Fundamentals of Python: From First Programs Through Data Structures
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CHAPTER 4: CONDITIONAL STRUCTURES Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
1 Relational Expressions Relational expressions: –Expressions that compare operands –Sometimes called conditions –Evaluated to yield a result –Typically.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
Problem Solving Techniques. Compiler n Is a computer program whose purpose is to take a description of a desired program coded in a programming language.
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
1 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 McGraw-Hill Companies, 2006 Chapter 2 Selection.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
1 Interactive Applications (CLI) and Math Interactive Applications Command Line Interfaces The Math Class Flow of Control / Conditional Statements The.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 If’s – The Basic Idea “Program” for hubby: take out garbage.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
 Software Development Life Cycle  Software Development Tools  High Level Programming:  Structures  Algorithms  Iteration  Pseudocode  Order of.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Evolution of C and C++ n C was developed by Dennis Ritchie at Bell Labs (early 1970s) as a systems programming language n C later evolved into a general-purpose.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Program Control: Selection Subject: T0016 – ALGORITHM AND PROGRAMMING Year: 2013.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
CNG 140 C Programming (Lecture set 3)
Chapter 4: Making Decisions.
The Selection Structure
Chapter 4: Making Decisions.
UNIT-4 BLACKBOX AND WHITEBOX TESTING
CMSC 202 Java Primer 2.
Coding Concepts (Basics)
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Controlling Program Flow
UNIT-4 BLACKBOX AND WHITEBOX TESTING
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: Q 0 : 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) = Q 0 e – 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 = / 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 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 = ; The int constant 1 is temporarily converted to the double value 1.0, and aVariable is assigned the value of , 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? ExpressionResultType 1 + 1/41int /41.0double /41.25double /41.25double / double 1 + 1/ double / double / double

8 Problem Solving and Program Design [now at chapter 3 in the text] 1.Requirements 2.Design 3.Coding 4.Testing and/or verification 5.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 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 code truefalse Test

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

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 be boolean, but the result of the comparison is boolean –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 discriminant we have 3 cases: 1. two real values for x 2. one real value for x 3. no real values for x

25 Flow diagram b 2 – 4ac > 0 b 2 – 4ac < 0 x 1 = – b/2a False No solutions True

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

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 > 0 d < 0 x 1 = – b/2a False True d = b 2 – 4ac True

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 discriminant we have 3 cases: 1. two real values for x 2. one real value for x 3. no real values for x

30 Flow diagram b 2 – 4ac > 0 b 2 – 4ac < 0 x 1 = – b/2a False No solutions True

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

32 Structure of nested if statements discriminant = b * b * 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 > 0 d < 0 x 1 = – b/2a False True d = b 2 – 4ac True

35 Testing for Equality with Floating 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 case 1 case 2 case n statement block 1 true statement block 2 true statement block n true default statement block false break;

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 case 1 case 2 case n statement block 1 true statement block 2 true statement block n true default statement block false break;