CS 112 Introduction to Programming

Similar documents
CS 112 Introduction to Programming

Lecture 4: Conditionals

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

CS 112 Introduction to Programming

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution

AP Computer Science. if/else, return values. Copyright 2010 by Pearson Education

Building Java Programs

Advanced if/else & Cumulative Sum

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

Building Java Programs

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Returns & if/else. Parameters and Objects

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Building Java Programs

H212 Introduction to Software Systems Honors

Fundamentals of Programming Data Types & Methods

Building Java Programs

Chapter 3. Selections

Introduction to Java Unit 1. Using BlueJ to Write Programs

CS 112 Introduction to Programming

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Flow of Control Branching 2. Cheng, Wei COMP May 19, Title

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

CS 112 Introduction to Programming

Computational Expression

Building Java Programs

CS 106 Introduction to Computer Science I

Topic 4 Expressions and variables

AP Computer Science Unit 1. Writing Programs Using BlueJ

Chapter 4: Control Structures I

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Programming with Java

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

Admin. CS 112 Introduction to Programming. Recap. Example: Nested Loop. Example: Rewrite

Topic 12 more if/else, cumulative algorithms, printf

2.2 - Making Decisions

ECE 122 Engineering Problem Solving with Java

4. Java Project Design, Input Methods

Chapter 4: Conditionals and Recursion

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Building Java Programs Chapter 4

Building Java Programs

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Using Java Classes Fall 2018 Margaret Reid-Miller

Lesson 7 Part 2 Flags

AP Computer Science Unit 1. Writing Programs Using BlueJ

Full file at

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

Following is the general form of a typical decision making structure found in most of the programming languages:

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Flow Control. Key Notion. Statement Categories. 28-Oct-10

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Boolean Expressions. So, for example, here are the results of several simple Boolean expressions:

Chapter 2: Basic Elements of Java

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Data Conversion & Scanner Class

CS 177 Recitation. Week 8 Methods

Building Java Programs

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

Primitive data, expressions, and variables

CMPT 125: Lecture 4 Conditionals and Loops

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Building Java Programs

CS-201 Introduction to Programming with Java

Object Oriented Programming. Java-Lecture 1

Chapter 2: Data and Expressions

COMP 202 Java in one week

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Java Coding 3. Over & over again!

Lecture Set 2: Starting Java

St. Edmund Preparatory High School Brooklyn, NY

FLOW CONTROL. Author: Boaz Kantor The Interdisciplinary Center, Herzliya Introduction to Computer Science Winter Semester

AP Computer Science A

Lecture Set 2: Starting Java

CS 112 Introduction to Programming

Sierpinski Valentine.

Chapter 3 Selection Statements

Course Outline. Introduction to java

A Quick and Dirty Overview of Java and. Java Programming

Transcription:

CS 112 Introduction to Programming Conditional Statements Boolean Expressions and Methods Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin. q Walkthrough of PS4 8 pm at DL 220 on Monday 6 pm at DL 220 on Tuesday q Office hour scheduling 2 1

Recap: Scanner q Some Scanner methods: Method nextint() Description Returns an int from source nextdouble() Returns a double from source next() nextline() Returns a one-word String from source Returns a one-line String from source q Java uses objects to remember the source of a scanner Scanner console = new Scanner(System.in); console.nextint(); Recap: Scanning Details q nextint(), nextdouble(), next() are token based scanning methods q nextline() collects any input character into a string until the first new line and discards the new line q When nextint(), nextdouble()parses a token, but cannot parse it correctly, the method throws an exception q A robust program will check condition before invoking nextint() or nextdouble() 2

Java Conditional Statements q Conditional statements, also called decision statements, decide whether or not to execute a particular sequence of statements The if Statement q 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 3

Recall: Basic Boolean Expression q A basic Boolean expression is to compare two values using a relational operator : Operator Meaning Example Value == equals 1 + 1 == 2 true!= does not equal 3.2!= 2.5 true < less than 10 < 5 false > greater than 10 > 5 true <= less than or equal to 126 <= 100 false >= greater than or equal to 5.0 >= 5.0 true q Note the difference between the equality operator (==) and the assignment operator (=) 7 Example: Basic Boolean Expression Flip.java 8 4

Outline: Conditional Program Flow Control q Our journey of introducing conditionals simple if (a <comp> b) nested if/else Motivation: Chaos Game q Play on equilateral triangle, with vertices R (node 0), G (node 1), B (node 2) B Start at R Repeat N times Pick a random vertex Move halfway between current point and vertex Draw a point in color of chosen vertex Chaos.java 10 5

Motivation: Chaos Game 11 Motivation: Chaos Game 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)? 12 6

Solution II: Nested Comparison 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 13 Grading Curve FIX: Using nested comparison to achieve mutual exclusion. q How is this code for grading based on percentiles? 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!"); else if (percent >= 80) { System.out.println("You got a B!"); else if (percent >= 70) { System.out.println("You got a C!"); else if (percent >= 60) { System.out.println("You got a D!"); else if (percent < 60) { System.out.println("You got an F!");... 14 7

Summary: Why nested if/else q Mutually exclusive test conditions => Reduces # of comparisons q Non-mutual exclusive test conditions => Achieves mutual exclusion if (percent >= 90) { // assigns A else if (percent >= 80) { // assigns B else if (percent >= 70) { // assigns C else if (percent >= 60) { // D else { // F a > b a < b a == b P >= 60 P >= 70 P >= 80 P >=90 15 Exercise: Barnsley Game q Play Chaos game with different rules Barnsley.java 16 8

Exercise: Barnsley Game 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(); // 0-1.0 if (rand <= 0.7) { // 0-0.7: 70% x =.78 * x +.03 * y +.11; y = -.03 * x +.74 * y +.27; else if (rand <= 0.7 + 0.15) { // 0.7-0.7+0.15: 15% // 15% x = -.14 * x +.26 * y +.57; y =.25 * x +.22 * y -.04; else if (rand < 0.7 + 0.15 + 0.13) { // 0.7+0.15 0.7+0.15+0.13: %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 17 Exercise: Barnsley Game q Questions to think about What does computation tell us about nature? What does nature tell us about computation? 18 9

Outline: Conditional Program Flow Control q Our journey of introducing conditionals simple if (a <comp> b) nested if/else Complexity of nested if/else: all path must return; mismatched else Matching Nested if Statements q Nested if statements may have a matching problem if (temperature < 50) if (temperature < 100) System.out.println( Cool! ); else System.out.println( Hot! ); 20 10

Nested if w/ Ambiguity 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! ); t < 50 Yes No t < 50 Yes No t < 100 Yes Hot! t < 100 Yes Hot! Cool! Cool! 50 100 50 100 Give a value of temperature to produce differentt results 21 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. 22 11

if/else with return q A method with a return requires that all paths through the code must reach a return statement. q The compiler analyzes this by considering the syntax only! if/else with return static int mymethod() { if (test1) { statement(s); return x; else if (test2) { statement(s); return y; else { statement(s); return z; // end of method else return else if if return return 12

if/else with return static int mymethod() { if (test1) { statement(s); return x; else if (test2) { statement(s); return y; else { statement(s); return z; return // end of method // ERROR: missing return in a path else if if return return 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 13

Outline: Conditional Program Flow Control q Our journey of introducing conditionals simple if (a <comp> b) nested if/else Complexity of nested if/else: all path must return; mismatched else <condition> combining multiple <comp>; Motivation: Testing Containment q We may need to check multiple conditions (x,y) (0,0) H W Test if point (x, y) is in the rectangle? (0 <= x <= W) and (0 <= y <= H) SYNTAX ERROR (0 <= x) && ( x <= W) && (0 <= y) && (y <= H) 28 14

Logical Operators q Tests can be combined using logical operators: Operator Description Example Result && and (2 == 3) && (-1 < 5) false or (2 == 3) (-1 < 5) true! not!(2 == 3) true q "Truth tables" for each, used with logical values p and q: p q p && q p q true true true true true false false true false true false true false false false false p!p true false false true Extension: Testing Containment q We may need to check multiple conditions (0,0) (x,y) h H w W Test if dark rectangle is in the bigger rectangle? 30 15

Exercise q Write a method to compute the number of days in a month public static int daysinmonth( int year, int month ) 31 Applying Boolean Exp. in daysinmonth q Use a logical OR to combine the cases if (m == 1 m == 3 m == 5 m == 7 m == 8 m == 10 m == 12) numdays = 31; 32 16

Applying Boolean Exp. in daysinmonth q 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 leap year or 4 year % 400 == 0 and 100 400 year % 4 == 0 year % 100!= 0 33 Testing Leap Year leap year or year % 400 == 0 and 4 100 400 year % 4 == 0 year % 100!= 0 y % 400 == 0 (y % 100!= 0 && y % 4 == 0) 34 17

Outline: Conditional Program Flow Control q Our journey of introducing conditionals simple if (a <comp> b) nested if/else Complexity of nested if/else: all path must return; mismatched else <condition> combining multiple <comp>; Boolean variables/expressions/methods Reuse Testing for Leap Year q How do we define a method to reuse the ability to test if a year is a leap year?? isleapyear(int year); 36 18

Recall: boolean Type q boolean: A primitive type whose values are true and false. 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 q Similar to arithmetic expressions, except that the operands are Boolean values, Boolean variables, or a test using a relational operator (e.g., <, >). 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"); 19

boolean Expressions: Example Boolean goodage = age >= 18 && age < 29; boolean goodheight = height >= 78 && height < 84; boolean rich = salary >= 100000.0; 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 q Example: boolean mystery = 5 * 7 >= 3 + 5 * (7 1) && 7 <= 11; q Precedence ordering of boolean expression Arithmetic operators Relations operators (==,!=, <, >, <=, >=) Note that equality and relational operators cannot be chained (e.g., 1 < x < 3 is invalid) NOT (!) AND (&&) OR ( ) Assignment operators (=) 20

Example boolean mystery = 5 * 7 >= 3 + 5 * (7 1) && 7 <= 11; 5 * 7 >= 3 + 5 * 6 && 7 <= 11 35 >= 3 + 30 && 7 <= 11 35 >= 33 && 7 <= 11 true && true true English vs boolean q OR vs Exclusive OR I ll either watch TV or go to gym: Exclusive OR watchtv gotogym can be both true q x is between 1 and 10 1 <= x <= 10 1 <= x && x <= 10 q x is either 1 or 2 or 3 x == 1 2 3 x ==1 x == 2 x == 3 21

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