Chapter 4: Conditionals and Recursion

Similar documents
Chapter 4. Conditionals and recursion. 4.1 The modulus operator. 4.2 Conditional execution

Chapter 3: Decision Structures

Chapter 3: Decision Structures

Chapter 3: Decision Structures

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

Basic Computation. Chapter 2

A+ Computer Science -

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

Repetition, Looping. While Loop

CS 302: Introduction to Programming

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Full file at

Evaluating the Style of your programs

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Basic Computation. Chapter 2

Control Structures: if and while A C S L E C T U R E 4

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Section 2: Introduction to Java. Historical note

Lecture Set 2: Starting Java

Oct Decision Structures cont d

CMSC131. Introduction to your Introduction to Java. Why Java?

Lecture Set 2: Starting Java

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Building Java Programs

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

A+ Computer Science -

Algorithms and Conditionals

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

What did we talk about last time? Examples switch statements

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

Java Coding 3. Over & over again!

Chapter 7. Iteration. 7.1 Multiple assignment

Programming with Java

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

CS 106 Introduction to Computer Science I

Topic 11 Scanner object, conditional execution

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Object Oriented Programming. Java-Lecture 1

Data Conversion & Scanner Class

AP Computer Science Unit 1. Programs

Introduction to Computer Programming

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Example Program. public class ComputeArea {

CS 112 Introduction to Programming

CS 112 Introduction to Programming

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Data Structure and Programming Languages

CONDITIONAL EXECUTION

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

Input. Scanner keyboard = new Scanner(System.in); String name;

Chapter 2. Elementary Programming

Chapter 1 Lab Algorithms, Errors, and Testing

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

Lecture 8 " INPUT " Instructor: Craig Duckett

Building Java Programs

Basic Operations jgrasp debugger Writing Programs & Checkstyle

CS 112 Introduction to Programming

Condi(onals and Loops

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Building Java Programs

Java I/O and Control Structures

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

Anatomy of a Java Program: Comments

CEN 414 Java Programming

Algorithms and Programming I. Lecture#12 Spring 2015

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

Task #1 The if Statement, Comparing Strings, and Flags

Introduction to Java Applications

Lecture 2: Operations and Data Types

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

1 Short Answer (10 Points Each)

COMP 202 Java in one week

Chapter 3. Selections

PRG PROGRAMMING ESSENTIALS. Lecture 2 Program flow, Conditionals, Loops

Over and Over Again GEEN163

AP Computer Science A

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

4. Java Project Design, Input Methods

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

4. Java language basics: Function. Minhaeng Lee

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

1. An operation in which an overall value is computed incrementally, often using a loop.

Conditional Programming

Computational Expression

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

Java I/O and Control Structures Algorithms in everyday life

Assignment 2.4: Loops

Reading Input from Text File

Topic 12 more if/else, cumulative algorithms, printf

Using Java Classes Fall 2018 Margaret Reid-Miller

Introduction to Computer Science Unit 2. Notes

1 Short Answer (5 Points Each)

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Building Java Programs

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Topic 11 Scanner object, conditional execution

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Transcription:

Chapter 4: Conditionals and Recursion Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals: the return statement Recursion 2

Calculate leftover inches In assignment 3 we wanted to convert: inches feet and leftover inches. For example, 40 inches = 3 feet, 4 inches We used these formulae: feet = inches/12 (using integer division) leftover_inches = inches feet*12 feet = 3 40 3*12 = 4 There's a better way to calculate leftover_inches: Modulus operator (%) leftover_inches = inches % 12 ;

Modulus Operator The modulus operator ONLY works on integers yields the remainder of first divided by second. In Java, the modulus operator is % int quotient = 7 / 3; // 2 int remainder = 7 % 3; // 1 Thus, 7 divided by 3 is 2 with 1 left over. Use to check if one number divisible by another if x % y is zero, then x is divisible by y. Solve these on your lab4 handout: 25 % 8 = 37 % 10 = 4 % 7 = 125 % 25 = 8 % 4 = 7 % 4 = 4

Modulus Operator The modulus operator ONLY works on integers yields the remainder of first divided by second. In Java, the modulus operator is % int quotient = 7 / 3; // 2 int remainder = 7 % 3; // 1 Thus, 7 divided by 3 is 2 with 1 left over. Use to check if one number divisible by another if x % y is zero, then x is divisible by y. For example: 25 % 8 = 1 37 % 10 = 7 4 % 7 = 4 125 % 25 = 0 8 % 4 = 0 7 % 4 = 3

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 6

Random Number Generation Java's Math library has a method random generates a random number between 0 and 1 0 <= x < 1 Here's how to use it: double x = Math.random(); System.out.println( x ) Each time you run the program, different x: 0.4523 0.0001 0.8214 0.5149 Useful for computer games, coin toss, etc.

Modeling a Coin Toss Pick a random number, mynumber If mynumber is less than 0.5, print "heads" If mynumber is larger than 0.5, print "tails" We need a new programming structure that lets us print a different message depending on the value of mynumber!

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 9

Which way to go? Conditional statements allow execution of certain statements only if a particular condition is satisfied Consider these statements as some kind of a gate keeper that allows entry only if a condition is satisfied 10

Conditional Execution The if statement decides whether a section of code executes or not. changes the behavior of the program accordingly. if (expression is true) execute statement block if the expression is false, nothing happens 11

Flowcharts If statements can be modeled as a flow chart. if (temp < 32){ wearcoat(); Is it cold outside? Yes Wear a coat. 12

Relational Operators In most cases, the condition of the if statement is written using relational operators. Relational Operator Meaning > is greater than < is less than >= is greater than or equal to <= is less than or equal to == is equal to!= is not equal to 13

Relational Operators A condition is a relational expression formed from one of the 6 relational operators. results in a true or false value. Expression Meaning x > y Is x greater than y? x < y Is x less than y? x >= y Is x greater than or equal to y? x <= y Is x less than or equal to y. x == y Is x equal to y? x!= y Is x not equal to y? 3-14

Conditional examples: This if statement assigns 0 to x when y is equal to 20 if (y == 20) { x = 0; If hours is larger than 40, then pay gets the value payrate times 1.5 times hours if (hours > 40) { pay = payrate*1.5*hours

Example: Modeling a Coin Toss, Version 1 double mynumber = Math.random(); //Decide the outcome of a coin flip if (mynumber <.5) { System.out.println("heads"); if (mynumber >=.5) { System.out.println("tails"); Every time we run the program, we get a different mynumber (between 0 and 1) The first if prints "heads" if mynumber < 0.5 The second if prints "tails" if mynumber >= 0.5

Caution with Conditionals Syntax differs from math symbols: =, and. common error: single = instead of a double == = is the assignment operator == is a comparison operator. no such thing as =< or =>. Two sides of a condition must be same type. Only compare ints to ints and doubles to doubles. == and!= don't work with Strings like you expect. Comparing strings is in chapter 8

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 18

Alternative Execution The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementblockiftrue; else statementblockiffalse; 3-19

if-else Statement Flowcharts No Is it cold outside? Yes Wear shorts. Wear a coat. if (temp < 32){ wearcoat(); else { wearshorts(); 3-20

Example: Modeling a Coin Toss, Version 2 double x = Math.random(); if (x < 0.5) { System.out.println("heads"); else { System.out.println("tails"); Every time we run the program, we get a different x (between 0 and 1) The if statement prints "heads" if x < 0.5 Note: else handles the case that x is NOT < 0.5 do not say else (x >= 0.5) { ERROR

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 22

Chained Conditionals if (expression_1) { statement; statement; etc. else if (expression_2) { statement; statement; etc. If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. Insert as many else if clauses as necessary else { statement; statement; etc. These statements are executed if none of the expressions above are true. 3-23

Chained Conditionals (if-else-if) Chained conditionals using the if-else-if statement makes it possible to handle more than two possible outcomes handle as many as you like Continue to add else-if blocks until you run out of possibilities Last else means "none of the above" were true Care must be used since else statements match up with the immediately preceding unmatched if statement. 3-24

Chained Conditional (if-else-if) Flowchart 3-25

Chained Conditional (if-else-if) Example if (x > 0) { System.out.println("x is positive"); else if (x < 0) { System.out.println("x is negative"); else { System.out.println("x is zero"); keep all the statements and squiggly-brackets lined up less likely to make syntax errors more likely to find them if you do 3-26

What if our Coin could fall off the table? double x = Math.random(); if (x < 0.45) { System.out.println("heads"); else if (x < 0.9) { System.out.println("tails"); else { System.out.println("fell off table!"); Prints "heads": 0.0 <= x < 0.45 Prints "tails": 0.45 <= x < 0.9 Prints "fell off table": 0.90 <= x < 1.0

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 28

Nested Conditonals If an if statement appears inside another if statement block it is called a nested conditional The nested if is executed only if the outer if statement results in a true condition. Nesting allows for unlimited variation of structure in selecting possible outcomes. Can also be harder to read 3-29

Nested if Statement Flowcharts No Is it cold outside? Yes Wear shorts. No Is it snowing? Yes Wear a jacket. Wear a parka. 3-30

Nested Conditional Example if (coldoutside){ if (snowing){ wearparka(); else{ wearjacket(); else{ wearshorts(); 3-31

Style helps clarify logic proper indentation makes it much easier to match up else statements with their corresponding if statement. Bad example: if (coldoutside){ if (snowing) { wearparka(); else { wearjacket(); else { wearshorts(); 3-32

Alignment and Nested if Statements This if and else go together. This if and else go together. if (coldoutside) { if (snowing) { wearparka(); else { wearjacket(); else { wearshorts(); 3-33

Do Lab 4 Part A finish PennyChanger debug AgeInsult we'll cover Scanner in next lecture used to input data from keyboard write CoinFlip program If you finish early, start doing drills in Assignment 4 Please do not do Part B until after next lecture

Agenda The modulus operator Random Number Generation Conditional Execution Alternative Execution Chained Conditionals Nested Conditionals Scanner Class for Input from Keyboard Methods with conditionals Recursion 35

The Scanner Class To read input from the keyboard we can use the Scanner class. The Scanner class is defined in java.util, so we will use the following statement at the top of our programs: import java.util.scanner; 2-36

The Scanner Class Scanner objects work with System.in To create a Scanner object: Scanner keyboard = new Scanner (System.in); The following Scanner class methods are useful next read the next word (til whitespace) as String nextline read to the end of line as a String nextint read the next number as an int nextdouble read the next number as a double See example on next slide 2-37

import java.util.scanner; // Needed for the Scanner class /** This program demonstrates the Scanner class. */ public class Payroll { public static void main(string[] args) { String name; // To hold a name int hours; // Hours worked double payrate; // Hourly pay rate double grosspay; // Gross pay // Create a Scanner object to read input. Scanner keyboard = new Scanner(System.in); // Get the user's name. System.out.print("What is your name? "); name = keyboard.nextline(); Read 1 line of text name = keyboard.next( ); // reads one word of text

// Get the number of hours worked this week. System.out.print("Number of hours worked this week? "); hours = keyboard.nextint(); // Get the user's hourly pay rate. System.out.print("What is your hourly pay rate? "); payrate = keyboard.nextdouble(); // Calculate the gross pay. grosspay = hours * payrate; Read 1 integer value Read 1 double // Display the resulting information. System.out.println("Hello " + name); System.out.println("Your gross pay is $" + grosspay);

Adding Conditionals to other methods This code checks whether x is divisible by 2 if (x%2 == 0) { System.out.println("x is even"); else { System.out.println("x is odd");

If you want to use it a lot, write a method This method checks whether x is divisible by 2 public static void printparity(int x){ if (x%2 == 0) { System.out.println("x is even"); else { System.out.println("x is odd"); This code invokes (calls) the method above printparity(15); printparity(24);

Reminder: do not declare variables in method calls printparity(7); int number = 35; printparity(number); printparity(int number); // WRONG

Return Statement lets you terminate the execution of a method early such as if you detect an error condition: public static void printsquareroot(double x) { if (x < 0.0) { System.out.println("Positive numbers only, please."); return; double result = Math.sqrt(x); System.out.println("The square root of x is " + result); checks whether x is less than zero, if so it prints an error message and then exits method. flow of execution returns to the caller remaining lines are not executed. 3-43

Automatic Type Conversion How does this work? "The square root of x is " + result one of the operands is a String, the other is a double. Java automatically converts the double to a String then joins them using string concatenation. What do you think would happen when adding an integer and a floating-point value? 3 + 4.5 =??? 3-44

Recursion it is legal for one method to invoke another it is also legal for a method to invoke itself one of the most magical and interesting things program can do. public static void countdown(int n) { if (n == 0) { System.out.println("Blastoff!"); else { System.out.println(n); countdown(n-1); countdown takes a single integer as a parameter. If the parameter is zero, prints Blastoff. Otherwise, prints the number, & invokes countdown again, passing n-1 as an argument 3-45

Running a recursive countdown if we invoke this method, in main: countdown(3); it prints 3, then invokes itself on 2... it prints 2, then invokes itself on 1... it prints 1, then invokes itself on 0... it prints Blastoff!, then returns The countdown that got n=1 returns. The countdown that got n=2 returns. The countdown that got n=3 returns. And then you re back in main. Displays: 3 2 1 Blastoff! 3-46

Another Recursive example recall newline and threelines from chapter 3 not very helpful if we want to print 2 lines or 106 a better alternative would be public static void nlines(int n) { if (n > 0) { System.out.println(""); nlines(n-1); if n is greater than zero, prints 1 newline then invokes itself to print n-1 newlines. The total number of newlines that get printed is 1 +(n-1), which usually comes out to roughly n! Recursion: when a method invokes itself 3-47

Stack Diagram for Recursive Methods stack diagrams can help interpret a recursive method. every time a method is called, get a new frame frame contains new method parameters and vars stack diagram for countdown, called with n = 3 public static void countdown(int n) { if (n == 0) { System.out.println("Blastoff!"); else { System.out.println(n); countdown(n-1); base case

Do Lab 4 Part B