CS 112 Introduction to Programming

Similar documents
1.3 Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops. 1.3 Conditionals and Loops. Conditionals and Loops

! Sequence of statements that are actually executed in a program. ! Conditionals and loops: enable us to choreograph control flow.

1.3 Conditionals and Loops

Lecture 3: Loops. While Loops. While Loops: Newton-Raphson Method. While Loops: Powers of Two

2.3 Flow Control. Flow-Of-Control. If-Else: Leap Year. If-Else

Lecture 3: Loops. While Loops. While Loops: Powers of Two. While Loops: Newton-Raphson Method

3. Conditionals & Loops

3. Conditionals and loops

3. Conditionals & Loops

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

Learning Outcomes for this week. Inf1-OP. A Foundation for Programming. A Foundation for Programming

Condi(onals and Loops

Tutorials. Inf1-OP. Learning Outcomes for this week. A Foundation for Programming. Conditionals and Loops 1

1/16/12. CS 112 Introduction to Programming. A Foundation for Programming. (Spring 2012) Lecture #4: Built-in Types of Data. The Computer s View

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 112 Introduction to Programming

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

CONDITIONAL EXECUTION

CONDITIONAL EXECUTION

CS 112 Introduction to Programming

Conditionals, Loops, and Style

CS 112 Introduction to Programming

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

1.1 Your First Program

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

1.1 Your First Program

CS 112 Introduction to Programming

AP CS Unit 3: Control Structures Notes

2/15/12. CS 112 Introduction to Programming. Lecture #16: Modular Development & Decomposition. Stepwise Refinement. Zhong Shao

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Variables and data types

CSC 1051 Data Structures and Algorithms I

CS 112 Introduction to Programming

1.1 Your First Program

1.1 Your First Program

Introduction to Computer Science Unit 2. Notes

A Foundation for Programming

Department of Computer Science Yale University Office: 314 Watson Closely related to mathematical induction.

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

2.1 Functions. 2.1 Functions. A Foundation for Programming. Functions (Static Methods) x y. f (x, y, z)

Lecture 6: While Loops and the Math Class

CS 112 Introduction to Programming

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

Recap: Structure of a Java program CS 112 Introduction to Programming. A Foundation for Programming Why Introduce Static Methods?

CS 112 Introduction to Programming

Michele Van Dyne Museum 204B CSCI 136: Fundamentals of Computer Science II, Spring

Introduction to Computer Science Unit 2. Notes

2.1 Functions. f (x, y, z)

1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

1.1 Your First Program

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Lecture 2: Intro to Java

1.1 Your First Program

CS 112 Introduction to Programming

CS 112 Introduction to Programming

1.1 Your First Program

Functions (or Static Methods) (Spring 2012)

CMSC 150 LECTURE 7 RECURSION

Repetition, Looping. While Loop

CS 112 Introduction to Programming. (Spring 2012)

CS1150 Principles of Computer Science Loops (Part II)

Unit 1 Lesson 4. Introduction to Control Statements

2.1 Functions. x y. f (x, y, z) A Foundation for Programming. Functions (Static Methods)

2.1, 2.2 Functions and Libraries

CS110D: PROGRAMMING LANGUAGE I

Chapter 4 Introduction to Control Statements

CS111: PROGRAMMING LANGUAGE II

2.3 Recursion 7/23/2015 3:06:35 PM

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

! Widely available. ! Widely used. ! Variety of automatic checks for mistakes in programs. ! Embraces full set of modern abstractions. Caveat.

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

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

CT 229 Java Syntax Continued

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

1.00 Lecture 32. Integration. Reading for next time: Numerical Recipes Packaging Functions in Objects

Object-Oriented Programming

2.2 Libraries and Clients

Algorithms COMBINATORIAL SEARCH. permutations backtracking counting subsets paths in a graph

2.4 Modular Programming

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

2.3 Recursion. Overview. Greatest Common Divisor. Greatest Common Divisor. What is recursion? When one function calls itself directly or indirectly.

1.1 Your First Program

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write

Quiz 1: Functions and Procedures

Common Errors double area; 3 if (r > 0); 4 area = r r 3.14; 5 System.out.println(area); 6... Zheng-Liang Lu Java Programming 101 / 141

Combinatorial Search. permutations backtracking counting subsets paths in a graph. Overview

Chapter 4 Loops. Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

CMSC 150 INTRODUCTION TO COMPUTING LAB WEEK 3 STANDARD IO FORMATTING OUTPUT SCANNER REDIRECTING

Motivations. Chapter 5: Loops and Iteration. Opening Problem 9/13/18. Introducing while Loops

Lecture 2: Intro to Java

CSC 1051 Data Structures and Algorithms I

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

Program Development. Program Development. A Foundation for Programming. Program Development

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

Transcription:

CS 112 Introduction to Programming (Spring 2012) Lecture #5: Conditionals and Loops Zhong Shao Department of Computer Science Yale University Office: 314 Watson http://flint.cs.yale.edu/cs112 Acknowledgements: some slides used in this class are taken directly or adapted from those accompanying the textbook: Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and Kevin Wayne (Copyright 2002-2010)

A Foundation for Programming any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops Math primitive data types text I/O assignment statements last lecture: equivalent to a calculator 2

A Foundation for Programming any program you might want to write objects functions and modules graphics, sound, and image I/O arrays conditionals and loops to infinity and beyond! Math primitive data types text I/O assignment statements 3

Control Flow Control flow. Sequence of statements that are actually executed in a program. Conditionals and loops: enable us to choreograph control flow. statement 1 boolean 1 true false statement 2 statement 3 statement 1 boolean 2 true statement 2 false statement 4 statement 3 straight-line control flow control flow with conditionals and loops 4

Conditionals

If Statement The if statement. A common branching structure. Evaluate a boolean expression. If true, execute some statements. If false, execute other statements. if (boolean expression) { statement T; else { statement F; can be any sequence of statements boolean expression true false statement T statement F 6

If Statement The if statement. A common branching structure. Evaluate a boolean expression. If true, execute some statements. If false, execute other statements. 7

If Statement Ex. Take different action depending on value of variable. public class Flip { public static void main(string[] args) { if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); % java Flip Heads % java Flip Heads % java Flip Tails % java Flip Heads 8

If Statement Examples 9

The While Loop 10

While Loop The while loop. A common repetition structure. Evaluate a boolean expression. If true, execute some statements. Repeat. loop continuation condition while (boolean expression) { statement 1; statement 2; statement 2 loop body true boolean expression statement 1 false 11

While Loop: Powers of Two Ex. Print powers of 2 that are 2 N. Increment i from 0 to N. Double v each time. i v i <= N int i = 0; int v = 1; while (i <= N) { System.out.println(i + " " + v); i = i + 1; v = 2 * v; 0 1 1 2 2 4 3 8 4 16 5 32 true true true true true true 0 1 1 2 2 4 3 8 4 16 5 32 6 64 6 64 true 7 128 false N = 6 Click for demo 12

Powers of Two public class PowersOfTwo { public static void main(string[] args) { // last power of two to print int N = Integer.parseInt(args[0]); int i = 0; // loop control counter int v = 1; // current power of two while (i <= N) { System.out.println(i + " " + v); i = i + 1; v = 2 * v; print i and ith power of two % java PowersOfTwo 3 0 1 1 2 2 4 3 8 % java PowersOfTwo 6 0 1 1 2 2 4 3 8 4 16 5 32 6 64 13

While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? int i = 0; int v = 1; while (i <= N) System.out.println(i + " " + v); i = i + 1; v = 2 * v; 14

While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? int i = 0; int v = 1; while (i <= N) System.out.println(i + " " + v); i = i + 1; v = 2 * v; A. Need curly braces around statements in while loop; otherwise it enters an infinite loop, printing "0 1". Moment of panic. How to stop infinite loop? 15

While Loops: Square Root Goal. Implement Math.sqrt(). % java Sqrt 2.0 1.414213562373095 Newton-Raphson method to compute the square root of c: Initialize t 0 = c. Repeat until t i = c / t i, up to desired precision: set t i+1 to be the average of t i and c / t i. 15 decimal digits of accuracy in 5 iterations t 0 = 2.0 t 1 = 1 (t 2 0 + t 2 0 ) = 1.5 t 2 = 1 2 1 + t 2 1 ) = 1.416666666666665 t 3 = 1 (t + 2 2 t 2 2 ) = 1.4142156862745097 t 4 = 1 (t 2 3 + t 2 3 ) = 1.4142135623746899 t 5 = 1 2 (t 4 + 2 t 4 ) = 1.414213562373095 computing the square root of 2 Copyright 2004, Sidney Harris www.sciencecartoonsplus.com 16

While Loops: Square Root Goal. Implement Math.sqrt(). % java Sqrt 2.0 1.414213562373095 Newton-Raphson method to compute the square root of c: Initialize t 0 = c. Repeat until t i = c / t i, up to desired precision: set t i+1 to be the average of t i and c / t i. 15 decimal digits of accuracy in 5 iterations public class Sqrt { public static void main(string[] args) { double epsilon = 1e-15; double c = Double.parseDouble(args[0]); double t = c; while (Math.abs(t - c/t) > t*epsilon) { t = (c/t + t) / 2.0; System.out.println(t); relative error tolerance 17

Newton-Raphson Method Square root method explained. Goal: find root of any function f(x). Start with estimate t 0. Draw line tangent to curve at x= t i. f(x) = x 2 - c to compute c Set t i+1 to be x-coordinate where line hits x-axis. Repeat until desired precision. Technical conditions. f(x) is smooth; t 0 is good estimate. 18

The For Loop Copyright 2004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/2003/10/03 19

For Loops The for loop. Another common repetition structure. Execute initialization statement. Evaluate a boolean expression. If true, execute some statements. And then the increment statement. Repeat. loop continuation condition for (init; boolean expression; increment) { statement 1; statement 2; body init boolean expression true increment statement 2 statement 1 false 20

Anatomy of a For Loop shorthand for i = i +1 Q. What does it print? A. 21

For Loops: Subdivisions of a Ruler Create subdivision of a ruler. Initialize ruler to " ". For each value i from 1 to N: sandwich two copies of ruler on either side of i. public class RulerN { public static void main(string[] args) { int N = Integer.parseInt(args[0]); String ruler = " "; for (int i = 1; i <= N; i++) { ruler = ruler + i + ruler; System.out.println(ruler); i ruler " " 1 " 1 " 2 " 1 2 1 " 3 " 1 2 1 3 1 2 1 " 22

For Loops: Subdivisions of a Ruler % java RulerN 1 1 % java RulerN 2 1 2 1 % java RulerN 3 1 2 1 3 1 2 1 % java RulerN 4 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java RulerN 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java RulerN 100 Exception in thread "main" java.lang.outofmemoryerror Observation. Loops can produce a huge amount of output! 23

Loop Examples 24

Nesting 25

Nested If Statements Ex. Pay a certain tax rate depending on income level. Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 5 mutually exclusive alternatives 174,700 311,950 33% 311,950-35% double rate; if (income < 47450) rate = 0.22; else if (income < 114650) rate = 0.25; else if (income < 174700) rate = 0.28; else if (income < 311950) rate = 0.33; else rate = 0.35; graduated income tax calculation 26

Nested If Statements Use nested if statements to handle multiple alternatives. if (income < 47450) rate = 0.22; else { if (income < 114650) rate = 0.25; else { if (income < 174700) rate = 0.28; else { if (income < 311950) rate = 0.33; else rate = 0.35; 27

Nested If Statements Need all those braces? Not always. if (income < 47450) rate = 0.22; else if (income < 114650) rate = 0.25; else if (income < 174700) rate = 0.28; else if (income < 311950) rate = 0.33; else rate = 0.35; is shorthand for if (income < 47450) rate = 0.22; else { if (income < 114650) rate = 0.25; else { if (income < 174700) rate = 0.28; else { if (income < 311950) rate = 0.33; else rate = 0.35; but be careful when nesting if-else statements. [See Q+A on p. 75.] 28

Nested If Statement Challenge Q. What's wrong with the following for income tax calculation? Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% double rate = 0.35; if (income < 47450) rate = 0.22; if (income < 114650) rate = 0.25; if (income < 174700) rate = 0.28; if (income < 311950) rate = 0.33; wrong graduated income tax calculation 29

Monte Carlo Simulation 30

Gambler's Ruin Gambler's ruin. Gambler starts with $stake and places $1 fair bets until going broke or reaching $goal. What are the chances of winning? How many bets will it take? One approach. Monte Carlo simulation. Flip digital coins and see what happens. Repeat and compute statistics. 31

Gambler's Ruin public class Gambler { public static void main(string[] args) { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int T = Integer.parseInt(args[2]); int wins = 0; // repeat experiment T times for (int t = 0; t < T; t++) { // do one gambler's ruin experiment int cash = stake; while (cash > 0 && cash < goal) { // flip coin and update if (Math.random() < 0.5) cash++; else cash--; if (cash == goal) wins++; System.out.println(wins + " wins of " + T); 32

Digression: Simulation and Analysis stake goal T % java Gambler 5 25 1000 191 wins of 1000 % java Gambler 5 25 1000 203 wins of 1000 % java Gambler 500 2500 1000 197 wins of 1000 after a substantial wait. Fact. Probability of winning = stake goal. Fact. Expected number of bets = stake desired gain. Ex. 20% chance of turning $500 into $2500, but expect to make one million $1 bets. 500/2500 = 20% 500 * (2500-500) = 1 million Remark. Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best (only) plan of attack. 33

Control Flow Summary Control flow. Sequence of statements that are actually executed in a program. Conditionals and loops: enable us to choreograph the control flow. Control Flow Description Examples straight-line programs conditionals loops all statements are executed in the order given certain statements are executed depending on the values of certain variables certain statements are executed repeatedly until certain conditions are met if if-else while for do-while 34