CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University.

Slides:



Advertisements
Similar presentations
CS-1010 Dr. Mark L. Hornick 1 Selection Statements and conditional expressions.
Advertisements

BUILDING JAVA PROGRAMS CHAPTER 4 Conditional Execution.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-2: Advanced if/else ; Cumulative sum reading: 4.1, 4.3, 4.5; "Procedural.
1 BUILDING JAVA PROGRAMS CHAPTER 4 CONDITIONAL EXECUTION.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: Scanner ; if/else reading: , 4.2, 4.6.
Logical Operators and Conditional statements
C++ for Engineers and Scientists Third Edition
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 4: Conditional Execution.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
Topic 11 Scanner object, conditional execution Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Conditionals (Cont’d). 2 Nested if/else question Formula for body mass index (BMI): Write a program that produces output like the following: This program.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 3: Program Statements
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Building Java Programs
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Building Java Programs Chapter 5 Lecture 5-3: Boolean Logic and Assertions reading: 5.3 – 5.5.
Control Flow. Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and.
Flow of Control Unless indicated otherwise, the order of statement execution through a method is linear: one after the other in the order they are written.
Building Java Programs Chapter 4 Conditional Execution Copyright (c) Pearson All rights reserved.
Copyright 2008 by Pearson Education Building Java Programs Chapter 4 Lecture 4-1: if and if/else Statements reading: 4.2 self-check: #4-5, 7, 10, 11 exercises:
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CS-1010 Dr. Mark L. Hornick 1 Selection and Iteration and conditional expressions.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-2: Random Numbers; Type boolean reading: , 5.6.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright 2008 by Pearson Education 1 The if statement Executes a block of statements only if a test is true if ( test ) { statement ;... statement ; }
CompSci 230 S Programming Techniques
Building Java Programs
Building Java Programs Chapter 4
Boolean Expressions and If
Building Java Programs
SELECTION STATEMENTS (1)
Lecture 4: Conditionals
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Control Structure Chapter 3.
Lecture 6: Conditionals AP Computer Science Principles
Building Java Programs
Building Java Programs
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Building Java Programs
Chapter 4: Boolean Expressions, Making Decisions, and Disk Input and Output Prof. Salim Arfaoui.
Building Java Programs
CSC 1051 – Data Structures and Algorithms I
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs Chapter 4
Conditionals and Loops
Building Java Programs
Building Java Programs
Presentation transcript:

CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Admin.  Walkthrough of PS4 m 8 pm at DL 220 on Monday m 6 pm at DL 220 on Tuesday  Office hour scheduling 2

Recap: Scanner  Some Scanner methods:  Java uses objects to remember the source of a scanner MethodDescription nextInt() Returns an int from source nextDouble() Returns a double from source next() Returns a one-word String from source nextLine() Returns a one-line String from source Scanner console = new Scanner(System.in); console.nextInt();

Recap: Scanning Details  nextInt(), nextDouble(), next() are token based scanning methods  nextLine() collects any input character into a string until the first new line and discards the new line  When nextInt(), nextDouble() parses a token, but cannot parse it correctly, the method throws an exception  A robust program will check condition before invoking nextInt() or nextDouble()

Java Conditional Statements  Conditional statements, also called decision statements, decide whether or not to execute a particular sequence of statements

The if Statement  Example: int nA = 0; for (int i = 0; i < 100; i++) { double grade = console.nextDouble(); if (grade >= 90) { System.out.println("Welcome to Yale!"); nA ++; // This is called accumulative sum } }

7 Recall: Basic Boolean Expression  A basic Boolean expression is to compare two values using a relational operator :  Note the difference between the equality operator ( == ) and the assignment operator ( = ) OperatorMeaningExampleValue == equals == 2true != does not equal 3.2 != 2.5true < less than 10 < 5false > greater than 10 > 5true <= less than or equal to 126 <= 100false >= greater than or equal to 5.0 >= 5.0true

8 Example: Basic Boolean Expression Flip.java

Outline: Conditional Program Flow Control  Our “journey” of introducing conditionals simple if (a b) nested if/else

Motivation: Chaos Game  Play on equilateral triangle, with vertices R (node 0), G (node 1), B (node 2) m Start at R m Repeat N times Pick a random vertex Move halfway between current point and vertex Draw a point in color of chosen vertex 10 Chaos.java B

Motivation: Chaos Game 11

Motivation: Chaos Game 12 public static void main (String[] args) { for (int i = 0; i < 1000; i++) { int rand = getRand(0, 2); if (rand == 0) { // } if (rand == 1) { // … } if (rand == 2) { // … } Q: How many comparisons in each round (iteration)?

Solution II: Nested Comparison 13 public static void main (String[] args) { … for (int i = 0; i < 1000; i++) { int rand = getRand(0, 2); if (rand == 0) { // } else if (rand == 1) { // … } else if (rand == 2) { // … } Q: Average # of comparisons per iteration? Benefit of nested comparison: reduce # comparisons

Grading Curve  How is this code for grading based on percentiles? 14 Scanner console = new Scanner(System.in); System.out.print("What percentile? "); int percent = console.nextInt(); if (percent >= 90) { System.out.println("You got an A!"); } if (percent >= 80) { System.out.println("You got a B!"); } if (percent >= 70) { System.out.println("You got a C!"); } if (percent >= 60) { System.out.println("You got a D!"); } if (percent < 60) { System.out.println("You got an F!"); }... FIX: Using nested comparison to achieve mutual exclusion. else

Summary: Why nested if/else  Mutually exclusive test conditions => Reduces # of comparisons  Non-mutual exclusive test conditions => Achieves mutual exclusion 15 a > b a < ba == b P >= 60 P >= 70 P >= 80 P >=90 if (percent >= 90) { // assigns A } else if (percent >= 80) { // assigns B } else if (percent >= 70) { // assigns C } else if (percent >= 60) { // D } else { // F }

Exercise: Barnsley Game 16  Play Chaos game with different rules Barnsley.java

Exercise: Barnsley Game 17 public static void main(String[] args) { StdDraw.setPenRadius(0.002); StdDraw.setPenColor(Color.GREEN); int T = 40000; double x = 0.0, y = 0.0; for (int t = 0; t < T; t++) { double rand = Math.random(); // if (rand <= 0.7) { // : 70% x =.78 * x +.03 * y +.11; y = -.03 * x +.74 * y +.27; } else if (rand <= ) { // : 15% // 15% x = -.14 * x +.26 * y +.57; y =.25 * x +.22 * y -.04; } else if (rand < ) { // – : %13 x =.17 * x -.21 * y +.41; y =.22 * x +.18 * y +.09; } else { // 2% x = 0.5; y =.27 * y; } StdDraw.point(x, y); } // end of for } // end of main

Exercise: Barnsley Game 18  Questions to think about m What does computation tell us about nature? m What does nature tell us about computation?

Outline: Conditional Program Flow Control  Our “journey” of introducing conditionals simple if (a b) nested if/else Complexity of nested if/else: all path must return; mismatched else

20 Matching Nested if Statements  Nested if statements may have a matching problem if (temperature < 50) if (temperature < 100) System.out.println(“Cool!”); else System.out.println(“Hot!”);

21 Nested if w/ Ambiguity t < 50 t < 100 Cool!Hot! Yes No Yes t < 50 t < 100 Cool! Hot! Yes No Yes if (temperature < 50) if (temperature < 100) System.out.println(“Cool!”); else System.out.println(“Hot!”); if (temperature < 50) if (temperature < 100) System.out.println(“Cool!”); else System.out.println(“Hot!”); Give a value of temperature to produce differentt results

22 Nested if Statements if (temperature < 50) if (temperature < 100) System.out.println(“Cool!”); else System.out.println(“Hot!”); if (temperature < 50) if (temperature < 100) System.out.println(“Cool!”); else System.out.println(“Hot!”); - Rule: an else clause is matched to the last unmatched if (no matter what the indentation implies) - If you find such statements confusing, avoid writing such structures and always use block statements ({}) to make the structure clear.

if/else with return  A method with a return requires that all paths through the code must reach a return statement.  The compiler analyzes this by considering the syntax only!

if/else with return return if else if else static int myMethod() { if ( test1 ) { statement(s) ; return x; } else if ( test2 ) { statement(s) ; return y; } else { statement(s) ; return z; } } // end of method

if/else with return return if else if static int myMethod() { if ( test1 ) { statement(s) ; return x; } else if ( test2 ) { statement(s) ; return y; } else { statement(s) ; return z; } } // end of method // ERROR: missing return in a path

if/else with return public static int max(int a, int b) { if (a > b) { return a; } } // Error: not all paths return a value public static int max(int a, int b) { if (a > b) { return a; } else if (a <= b) { return b; } // Error: syntax analysis missing a path public static int max(int a, int b) { if (a > b) { return a; } else if (a <= b) { return b; } // OK public static int max(int a, int b) { int myMax = a; // default if (b > a) { myMax = b; } return myMax; } // OK public static int max(int a, int b) { if (b > a) { return b; } return a; } // OK

Outline: Conditional Program Flow Control  Our “journey” of introducing conditionals simple if (a b) nested if/else Complexity of nested if/else: all path must return; mismatched else combining multiple ;

Motivation: Testing Containment Test if point (x, y) is in the rectangle? 28 W H (x,y) (0 <= x <= W) and (0 <= y <= H) (0,0) SYNTAX ERROR  We may need to check multiple conditions (0 <= x) && ( x <= W) && (0 <= y) && (y <= H)

Logical Operators  Tests can be combined using logical operators:  "Truth tables" for each, used with logical values p and q: OperatorDescriptionExampleResult && and (2 == 3) && (-1 < 5)false || or (2 == 3) || (-1 < 5)true ! not !(2 == 3)true pqp && qp || q true false true falsetruefalsetrue false p !p!p truefalse true

Extension: Testing Containment Test if dark rectangle is in the bigger rectangle? 30 W H (x,y) (0,0)  We may need to check multiple conditions h w

Exercise  Write a method to compute the number of days in a month 31 public static int daysInMonth( )int year, int month

Applying Boolean Exp. in daysInMonth  Use a logical OR to combine the cases 32 if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) numDays = 31;

Applying Boolean Exp. in daysInMonth  Implement leap year condition: “… most years that are evenly divisible by 4 are leap years; However, there are some exceptions to this rule: Years that are evenly divisible by 100 are not leap years, unless they are also evenly divisible by 400”divisible 33 year % 400 == 0 or year % 4 == 0 year % 100 != 0 and leap year

Testing Leap Year 34 year % 400 == 0 or year % 4 == 0 year % 100 != 0 and y % 400 == 0 || (y % 100 != 0 && y % 4 == 0) leap year

Outline: Conditional Program Flow Control  Our “journey” of introducing conditionals simple if (a b) nested if/else Complexity of nested if/else: all path must return; mismatched else combining multiple ; Boolean variables/expressions/methods

Reuse Testing for Leap Year  How do we define a method to reuse the ability to test if a year is a leap year? 36 ? isLeapYear(int year);

Recall: boolean Type  boolean : A primitive type whose values are true and false. m Like other types, it is legal to: create a boolean variable and assign it values pass a boolean value as a parameter return boolean value as a method call a method that returns a boolean and use it as a test

boolean Expressions  Similar to arithmetic expressions, except that m the operands are Boolean values, Boolean variables, or a test using a relational operator (e.g., ). m the operators are || && !  Example boolean lovesCS = true; boolean student = age < 21; // allow only CS-loving students over 21 if (student && lovesCS) System.out.println(“Pass"); // an alternative if (age < 21 && lovesCS) System.out.println(“Pass");

boolean Expressions: Example Boolean goodAge = age >= 18 && age < 29; boolean goodHeight = height >= 78 && height < 84; boolean rich = salary >= ; if ((goodAge && goodHeight) || rich) { System.out.println("Okay, let's go out!"); } else { System.out.println("It's not you, it's me..."); }

Mixed Arithmetic, Relation, Logical, and Assignment Expression  Example: boolean mystery = 5 * 7 >= * (7 – 1) && 7 <= 11;  Precedence ordering of boolean expression m Arithmetic operators m Relations operators (==, !=,, =) Note that equality and relational operators cannot be chained (e.g., 1 < x < 3 is invalid) m NOT (!) m AND (&&) m OR (||) m Assignment operators (=)

Example boolean mystery = 5 * 7 >= * (7 – 1) && 7 <= 11; 5 * 7 >= * 6 && 7 <= >= && 7 <= >= 33 && 7 <= 11 true && true true

English vs boolean  OR vs Exclusive OR m I’ll either watch TV or go to gym: Exclusive OR m watchTV || gotoGym can be both true  x is between 1 and 10 m 1 <= x <= 10 m 1 <= x && x <= 10  x is either 1 or 2 or 3 m x == 1 || 2 || 3 m x ==1 || x == 2 || x == 3

43 Logical AND/OR Evaluation  Java uses shortcircuit when evaluating && and || m a && b shortcircuit: if a is false, b is not evaluated if ((count != 0) && (total / count > AVG_THRESHOLD)){ // … } m a || b shortcircuit: if a is true, b is not evaluated