1 Chapter 5 Branching and Method Algorithm Design.

Slides:



Advertisements
Similar presentations
Logic & program control part 2: Simple selection structures.
Advertisements

Chapter 4: Making Decisions.
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Flow of Control is Sequential unless a “control structure” is used to change that there are 2 general types of control structures: Selection (also called.
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Conditions, logical expressions, and selection Introduction to control structures.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
1 Chapter 4 Selection and Encapsulation. 2 Chapter 4 Topics l Java Control Structures l boolean Data Type l Using Relational and Logical Operators in.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Control Structures I (Selection)
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures.
Conditions, Logical Expressions, and Selection Control Structures Sumber dari :
Chapter 4 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
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)
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 J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, logical expressions, and selection Introduction to control structures.
1 Conditions Logical Expressions Selection Control Structures Chapter 5.
Flow of Control There are 5 general types of Java control structures: Sequence (by default) Selection (also called branch or decision) Loop (also called.
Chapter 3 More Flow Of Control.
Flow of Control Part 1: Selection
COSC175-Selection1 Decisions Given hours worked and pay rate, calculate total pay What if you work overtime? How do you indicate if your work overtime?
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
CSE 1301 Lecture 8 Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
1 Programming in C++ Dale/Weems/Headington Chapter 5 Conditions, Logical Expressions.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
1 Conditions, Logical Expressions, and Selection Control Structures.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
C++ Programming Control Structures I (Selection).
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 5 Topics Data Type bool
Chapter 3 Selection Statements
Decisions Given hours worked and pay rate, calculate total pay
Java Programming: Guided Learning with Early Objects
Decisions Given hours worked and pay rate, calculate total pay
Conditionals & Boolean Expressions
Conditionals & Boolean Expressions
Chapter 3: Program Statements
Topics Data Type bool Using Relational and Logical Operators to Construct and Evaluate Logical Expressions If-Then-Else Statements If-Then Statements Nested.
Control Structure Chapter 3.
Control Structure.
Presentation transcript:

1 Chapter 5 Branching and Method Algorithm Design

2 Knowledge Goals Understand the Boolean operators AND, OR, and NOT Understand the concept of control flow with respect to selection statements Understand how nested control flow works Understand the differences between the if- else and if-else-if selection structures

3 Knowledge Goals Understand the differences between a nested if structure and a series of if structures Know when each form of selection structure is appropriate Understand the functional decomposition process

4 Skill Goals Use the relational operators,, =, ==, and != Construct a simple logical (Boolean) expression to evaluate a given condition Construct a complex Boolean expression to evaluate a given condition Construct an if-else statement to perform a specific task

5 Skill Goals Construct an if statement to perform a specific task Construct a set of nested if statements to perform a specific task Apply functional decomposition to design a method algorithm Apply testing strategies for if structures Test and debug a Java application

6 Boolean Expressions boolean data type A primitive type consisting of just two values, the constants true and false We declare variables of type boolean just as we do any other type boolean hasFever; // true if has high temperature boolean isSenior; // true if age is at least 65

7 Boolean Expressions Logical expression An expression made up of Boolean values and logical operations that evaluates to true or false  A boolean variable or constant  An arithmetic expression followed by a relational operator followed by an arithmetic expression  A logical expression followed by a logical operator followed by a logical expression

8 Relational operators are used in expressions of the form ExpressionA Operator ExpressionB temperature > humidity B*B - 4.0*A*C >= 0.0 one + two < 0 two * three <= four number == 35 initial != ‘Q’ Boolean Expressions

9 int x, y; x = 4; y = 6; EXPRESSIONVALUE x < y ? x + 2 < y ? x != y ? x + 3 >= y ? y == x ? y == x+2 ?

10 Boolean Expressions Relational operators can compare values of type char char first, second; first second comes after in collating sequence ASCII collating sequence  Lowercase letters are in sequence  Uppercase letters are in sequence  Digits are in sequence  Uppercase letters precede lowercase letters

11 Left Digit(s) 3 ” ! “ # $ % & ‘ 4 ( ) * +, -. / : ; 6 A B C D E 7 F G H I J K L M N O 8 P Q R S T U V W X Y 9 Z [ \ ] ^ _ ` a b c 10 d e f g h I j k l m 11 n o p q r s t u v w 12 x y z { | } ~ Right Digit Partial ASCII Character Set

12 Boolean Expressions Remember that strings are reference types myString = “Today”; yourString = “Today”; myString == yourSring returns what?

13 Boolean Expressions of implicit type conversions of comparing floating-point values for equality and inequality of using relational operators with strings Why are these problems?

14 Boolean Expressions Method Parameter Returns Operation Performed Name Type equalsString boolean compareToString int Tests for equality of contents Returns a negative integer if the instance comes before the parameter, a 0 if they are equal, and a positive integer if the parameter comes before the instance String methods

15 Boolean Expressions Method Parameter Returns Operation Performed Name Type toLowerCase none String toUpperCase none String Returns a new identical string, with the characters all lowercase Returns a new identical string, with the characters all uppercase.

16 String myState; String yourState; myState = “Texas”; yourState = “Maryland”; myState.equals(yourState) ? 0 < myState.compareTo(yourState) ? myState.equals(“Texas”)? myState.equals("texas")? 0 > myState.compareTo(“texas”)? yourState.equals("Maryland ")? Boolean Expressions

17 Boolean Expressions Java exp. Logical exp.Meaning ! p NOT p ! p is false if p is true ! p is true if p is false p && q p AND q p && q is true if both p and q are true; false otherwise p || q p OR qp || q is true if either p or q or both are true; false otherwise Logical Operators

grade number hour (grade >= 60) ? (number > 0) ? (hour >= 0 && hour < 24) ? (hour == 12 || hour == 0) ? Boolean Expressions

19 int age; boolean isSenior, hasFever; double temperature; age = 20; temperature = 102.0; isSenior = (age >= 65); // isSenior is ? hasFever = (temperature > 98.6); // hasFever is ? isSenior && hasFever ? isSenior || hasFever ? !isSenior ? !hasFever ? hasFever && (age > 50) ? Boolean Expressions

20 Boolean Expressions int age, height; age = 25; height = 70; !(age < 10) ? !(height > 60) ?

21 Boolean Expressions Short-circuit evaluation Evaluation of a logical expression in left-to-right order with evaluation stopping as soon as the final Boolean value can be determined Java operators !, &&, and || use short-circuit evaluation Can you think of examples where short-circuit evaluation saves time?

22 Boolean Expressions int age, height; age = 25; height = 70; (age > 50) && (height > 60) false Evaluation can stop now because result of && is only true when both sides are true; it is already determined that the entire expression will be false

23 Boolean Expressions int age, height; age = 25; height = 70; (height > 60) || (age > 40) true Evaluation can stop now because result of || is true if one side is true; it is already determined that the entire expression will be true

24 Boolean Expressions int age, weight; age = 25; weight = 145; (weight = 20) true Must still be evaluated because truth value of entire expression is not yet known. Why?

25 Boolean Expressions int age, height; age = 25; height = 70; !(height > 60)||(age > 50) true false Does this part need to be evaluated?

26 Boolean Expressions Highest precedence () ! unary - unary (post) (pre) * / % + ‑ >= == != && || = Lowest precedence Operator Precedence Relational Logical

27 Branching Flow of control The order in which the computer executes statements Control structure A statement used to alter the normally sequential flow of control

28 Branching Normal flow of control Branching control structure (What is an assertion?)

29 Branching

30 Branching See how it matches the syntax template?

31 Branching Calculating pay

32 if (Expression) Statement1A else Statement1B Statement1A and Statement1B each can be a single statement, a null statement, or a block Branching

33 Branching if(Expression) { } else { } “if branch” “else branch” Book's formatting style

34 Branching int carDoors, driverAge; float premium, monthlyPayment;... if ((carDoors == 4) && (driverAge > 24)) { premium = ; System.out.println(“Low Risk”); } else { premium = ; System.out.println(“High Risk”); } monthlyPayment = premium / ;

35 What happens if you omit braces? if ((carDoors == 4) && (driverAge > 24)) premium = ; System.out.println(“Low Risk”); else premium = ; System.out.println(“High Risk”); monthlyPayment = premium / ; COMPILE ERROR OCCURS The “if branch” is the single statement following the if Branching

36 Branching Problem Calculate totalBill where discountRate is.25 and shipCost is if purchase is over Otherwise, discountRate is.10 and shipCost is 5.00 Can you write the code?

37 Branching if (purchase > ) { discountRate =.25; shipCost = 10.00; } else { discountRate =.15; shipCost = 5.00; } totalBill = purchase *(1.0 - discountRate) + shipCost; Did you get it right?

38 Branching No braces if branch is a single statement if (lastInitial <= ‘K’) volume = 1; else volume = 2; System.out.println(“Look it up in volume # “ + volume + “ of NYC phone book”);

39 Branching "Execute or skip"

40 Branching If taxCode has value ‘T’, increase price by adding taxRate times price to it if (taxCode == ‘T’) price = price + taxRate * price; Statement can be null statement, single statement, or block

41 Branching Block can contain another control structure

42 if (Expression1 ) Statement1 else if (Expression2 ) Statement2... else if (ExpressionN ) StatementN else Statement N+1 Branching Nested if statements One and only one of these statements will be executed

43 if (creditsEarned >= 90) { System.out.print(“Congratulations ”); System.out.println("Senior Status"); } else if (creditsEarned >= 60) System.out.println(“Junior Status”); else if (creditsEarned >= 30) System.out.println(“Sophomore Status”); else System.out.println(“Freshman Status”); Branching Remember, each statement can be a compound statement

44 Branching What is the output double average; average = 100.0; if (average >= 60.0) if (average < 70.0) System.out.println(“Marginal PASS”); else System.out.println(“FAIL”); The output is "FAIL". Can you tell why?

45 Branching Corrected Version double average; average = 100.0; if (average >= 60.0) { if(average < 70.0) System.out.println(“Marginal PASS”); } else System.out.println(“FAIL”);

46 Branching Compare floating-point values for near equality double myNumber; double yourNumber;... if (Math.abs(myNumber - yourNumber) < ) System.out.println(“Close enough!”);

47 Branching Grading scheme A B C D below 60F Can you write the if statement?

48 Branching if (grade >= 90) letterGrade = 'A'; else if (grade >= 80) letterGrade = 'B'; else if (grade >= 70) letterGrade = 'C'; else if (grade >= 60) letterGrade = 'D'; else letterGrade = 'F'; Why don't we have to ask if grade < 90 ?

49 Branching Remember our old friend the Scanner class… hasNextLine()true if scanner has another line hasNextInt()true if next token is an int hasNextDouble()true if next token is a double We can use these Boolean methods to guard against bad data if (in.hasNextInt()) value = in.nextInt(); else System.out.println("bad data");

50 Branch Testing Minimum complete coverage Execute each branch at least once Code coverage (white box) Test data are designed by looking at the code Data coverage (black box) Test data chosen without seeing code; based on all possible values for expression Mixed coverage Combines code and data coverage

51 Branch Testing if (grade >= 90) letterGrade = 'A'; else if (grade >= 80) letterGrade = 'B'; else if (grade >= 70) letterGrade = 'C'; else if (grade >= 60) letterGrade = 'D'; else letterGrade = 'F'; Code coverage

52 Branch Testing if (grade >= 90) letterGrade = 'A'; else if (grade >= 80) letterGrade = 'B'; else if (grade >= 70) letterGrade = 'C'; else if (grade >= 60) letterGrade = 'D'; else letterGrade = 'F'; Data coverage all possible values for grade ! Impossible!! Mixed coverage Code coverage + < 0 >100

53 Method Design Top-Down Design Problem-solving technique in which the problem is divided into subproblems; the process is applied to each subproblem Modules Self-contained collection of steps, that solve a problem or subproblem Abstract Step An algorithmic step containing unspecified details Concrete Step An algorithm step in which all details are specified

54 Method Design 1. How would you solve the problem by hand? 2. Write down the major steps 3. If you can write step in Java, it is a concrete step 4. If a module needs a series of smaller steps, it is abstract 5. Give each non-concrete step a name; it becomes a module 6. Repeat process for each abstract module 7. If you are overwhelmed by detail, you have missed a level of abstraction; back up

55 Method Design

56 Method Design Object-Oriented design (for overall problem) –Focus is on the entities (objects) in a problem –Begins by identifying the classes of objects in the problem and choosing appropriate operations on those objects –Programs are collections of objects that communicate with (send messages to) each other –Data plays a leading role; algorithms are used to implement operations on the objects and to enable interaction of objects with each other

57 Method Design Functional Decomposition (for methods)  Focus is on the sequence of actions (algorithms) required to solve the problem  Begins by breaking the responsibility into a series of major steps. This process continues until each subproblem cannot be divided further or has an obvious solution  Methods are collections of modules that solve subproblems; a module structure chart (hierarchical solution tree) is often created  Data plays a secondary role as the algorithm is applied to an instance of itself

58 Extras All the world knows my name What is it and why do people know it?

59 Extras - GUI Track Output from JOptionPane.showMessageDialog

60 Extras - GUI Track More output