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

Similar documents
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

1.3 Conditionals and Loops

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

1.3 Conditionals and Loops

1.3 Conditionals and Loops

1.3 Conditionals and Loops

CS 112 Introduction to Programming

3. Conditionals & Loops

3. Conditionals & Loops

3. Conditionals and loops

I/O (cont) and Program Development. Standard Audio. A Foundation for Programming. Crash Course in Sound

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

TESTING AND DEBUGGING

A Foundation for Programming

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

More on variables, arrays, debugging

Debugging [continued]

Debugging [continued]

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

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

Unit 1 Lesson 4. Introduction to Control Statements

CONDITIONAL EXECUTION

Chapter 4 Introduction to Control Statements

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

Java. Programming: Chapter Objectives. Why Is Repetition Needed? Chapter 5: Control Structures II. Program Design Including Data Structures

Computer Programming I - Unit 5 Lecture page 1 of 14

AP CS Unit 3: Control Structures Notes

CONDITIONAL EXECUTION

Lecture 2: Intro to Java

Debugging [continued]

Control Structures II. Repetition (Loops)

Conditionals, Loops, and Style

Repetition, Looping. While Loop

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

Chapter 7. Iteration. 7.1 Multiple assignment

You have seen abstractions in many places, lets consider them from the ground up.

Chapter 4: Control structures. Repetition

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

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

AP Programming - Chapter 6 Lecture

Chapter 4: Control structures

1.1 Your First Program

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

1.1 Your First Program

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Java Methods. Lecture 8 COP 3252 Summer May 23, 2017

Variables and data types

Lecture 2: Intro to Java

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

1.1 Your First Program

CS112 Lecture: Repetition Statements

CSC 1051 Data Structures and Algorithms I

2.3 Recursion. Overview. Mathematical Induction. What is recursion? When one function calls itself directly or indirectly.

1.1 Your First Program

Repetition with for loops

CS111: PROGRAMMING LANGUAGE II

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

Programming Basics and Practice GEDB029 Decision Making, Branching and Looping. Prof. Dr. Mannan Saeed Muhammad bit.ly/gedb029

LEC03: Decisions and Iterations

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

The keyword list thus far: The Random class. Generating "Random" Numbers. Topic 16

Topic 16. battle -they are strictly limited in number, they require fresh horses, and must only be made at decisive moments." -Alfred North Whitehead

Overview. What is recursion? When one function calls itself directly or indirectly.

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

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Example: Monte Carlo Simulation 1

Example. CS 201 Selection Structures (2) and Repetition. Nested if Statements with More Than One Variable

true false Imperative Programming III, sections , 3.0, 3.9 Introductory Programming Control flow of programs While loops: generally Loops

1.1 Your First Program

COMP 110 Programming Exercise: Simulation of the Game of Craps

COMP-202 Unit 4: Programming with Iterations

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Chapter 6. Repetition Statements. Animated Version The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

! New mode of thinking. ! Powerful programming paradigm. ! Mergesort, FFT, gcd. ! Linked data structures.

Iteration. # a and b are now equal # a and b are no longer equal Multiple assignment

Jerry Cain Handout #5 CS 106AJ September 30, Using JSKarel

1.1 Your First Program

Loops and Files. Chapter 04 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

1.1 Your First Program

While Loops CHAPTER 5: LOOP STRUCTURES. While Loops. While Loops 2/7/2013

CS112 Lecture: Loops

Introduction to the Java Basics: Control Flow Statements

Repetition, Looping CS101

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

STUDENT LESSON A12 Iterations

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

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Simple Java Programming Constructs 4

Transcription:

Control Flow 1.3 Conditionals and Loops 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 false statement 2 statement 3 statement 1 boolean 2 statement 2 false statement 4 statement 3 straight-line control flow control flow with conditionals and loops 2 If Statement Conditionals The if statement. A common branching structure.! Check boolean condition.! If, execute some statements.! If false, execute other statements. if (boolean expression) { statement T; can be any sequence of statements else { statement F; boolean expression false statement T statement F 4

If Statement If Statement The if statement. A common branching structure.! Check boolean condition.! If, execute some statements.! If false, execute other statements. Ex. Take different action depending on value of variable. public class Flip { if (Math.random() < 0.5) System.out.println("Heads"); elsemath.random() < 0.5) System.out.println("Tails"); 5 6 If Statement Examples The While Loop 7 8

While Loop While Loops: Powers of Two The while loop. A common repetition structure.! Check a boolean expression.! Execute a sequence of statements.! Repeat. Ex. Print first n powers of 2.! Increment i from 1 to n.! Double v each time. i v i <= N loop continuation condition statement 2 while (boolean expression) { statement 1; statement 2; loop body boolean expression statement 1 int i = 0; int v = 1; while (i <= N) { System.out.println(v); i = i + 1; v = 2 * v; 0 1 1 2 2 4 3 8 4 16 5 32 % java Powers 1 2 4 8 16 32 64 6 64 false 7 128 false n = 6 Click for demo 9 10 Powers of Two A Wonderful Square Root public class PowersOfTwo { // 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(v); i = i + 1; v = 2 * v; print ith power of two % java PowersOfTwo 4 1 2 4 8 % java PowersOfTwo 6 1 2 4 8 16 32 64 Copyright 2004, Sidney Harris, http://www.sciencecartoonsplus.com % java Sqrt 60481729 7777.0 11 12

While Loops: Square Root While Loops: Square Root Q. How might we implement Math.sqrt()? A. 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. Q. How might we implement Math.sqrt()? A. 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. t 0 = 2.0 t 1 = 1 (t + 2 0 t 2 0 ) = 1.5 t 2 = 1 2 1 + 2 t 1 ) = 1.416666666666665 t 3 = 1 (t 2 2 + 2 t 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 public class Sqrt { double EPS = 1E-15; double c = Double.parseDouble(args[0]); double t = c; while (Math.abs(t - c/t) > t*eps) { t = (c/t + t) / 2.0; error tolerance System.out.println(t); % java Sqrt 2.0 1.414213562373095 15 decimal digits of accuracy in 5 iterations 13 14 Newton-Raphson Method Square root method explained.! Goal: find root of function f(x).! Start with estimate t 0. f(x) = x 2 - c to compute!c! Draw line tangent to curve at x= t i.! Set t i+1 to be x-coordinate where line hits x-axis.! Repeat until desired precision. The For Loop Copyright 2004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/2003/10/03 15 16

For Loops For Loops: Subdivisions of a Ruler The for loop. Another common repetition structure.! Execute initialization statement.! Check boolean expression.! Execute sequence of statements.! Execute increment statement.! Repeat. loop continuation condition for (init; boolean expression; increment) { statement 1; statement 2; body init boolean expression increment statement 2 statement 1 Create subdivision of a ruler.! Initialize ruler to empty string.! For each value i from 1 to N: sandwich two copies of ruler on either side of i. public class Ruler { 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 " false 17 18 For Loops: Subdivisions of a Ruler Loop Examples % java Ruler 1 1 % java Ruler 2 1 2 1 % java Ruler 3 1 2 1 3 1 2 1 % java Ruler 4 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java Ruler 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 Ruler 100 Exception in thread "main" java.lang.outofmemoryerror Observation. Loops can produce a huge amount of output! 19 20

Nesting Conditionals and Loops Nesting Conditionals enable you to do one of 2 n sequences of operations with n lines. Loops enable you to do an operation n times using only 2 lines of code. if (a0 > 0) System.out.print(0); if (a1 > 0) System.out.print(1); if (a2 > 0) System.out.print(2); if (a3 > 0) System.out.print(3); if (a4 > 0) System.out.print(4); if (a5 > 0) System.out.print(5); if (a6 > 0) System.out.print(6); if (a7 > 0) System.out.print(7); if (a8 > 0) System.out.print(8); if (a9 > 0) System.out.print(9); double sum = 0.0; for (int i = 1; i <= 1024; i++) sum = sum + 1.0 / i; computes 1/1 + 1/2 +... + 1/1024 2 10 = 1024 possible results, depending on input More sophisticated programs.! Nest conditionals within conditionals.! Nest loops within loops.! Nest conditionals within loops within loops. 21 22 Nested If Statements Nested If Statements Ex. Pay a certain tax rate depending on income level. Ex. Pay a certain tax rate depending on income level. Income Rate Income Rate 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 174,700 311,950 33% 311,950-35% 5 mutually exclusive alternatives 0-47,450 22% 47,450 114,650 25% 114,650 174,700 28% 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 if (income < 311950) rate = 0.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; graduated income tax calculation wrong graduated income tax calculation 23 24

Gambler's Ruin Monte Carlo Simulation 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. 25 26 Gambler's Ruin Simulation and Analysis public class Gambler { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int trials = Integer.parseInt(args[2]); int wins = 0; // repeat experiment N times for (int i = 0; i < trials; i++) { // do one gambler's ruin experiment int t = stake; while (t > 0 && t < goal) { // flip coin and update if (Math.random() < 0.5) t++; else t--; if (t == goal) wins++; System.out.println(wins + " wins of " + trials); stake goal trials % 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 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. after a few hours of computing. Remark. Both facts can be proved mathematically; for more complex scenarios, computer simulation is often the best plan of attack. 27 28

Debugging a Program Debugging Factor. Given an integer N, compute its prime factorization. 3,757,208 = 2 3 " 7 " 13 2 " 397 3757208/8 http://www.history.navy.mil/photos/images/h96000/h96566kc.htm Admiral Grace Murray Hopper Application. Break RSA cryptosystem. 29 30 Debugging a Program: Syntax Errors Debugging a Program: Semantic Errors Syntax error. Illegal Java program.! Compiler error messages help locate problem.! Eventually, a file named Factors.class. Semantic error. Legal but wrong Java program.! Use "System.out.println" method to identify problem. Check if i is a factor. public class Factors1 { long N = Long.parseLong(args[0]) for (i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " ") N = N / i As long as i is a factor, divide it out. Check if i is a factor. public class Factors2 { long N = Long.parseLong(args[0]); for (long i = 2; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; no output (17) or infinite loop (49) As long as i is a factor, divide it out. Compile-time error Run-time error 31 32

Debugging a Program: Performance Errors Debugging a Program: Success Performance error. Correct program but too slow.! Use profiling to discover bottleneck.! Devise better algorithm. Fact. If N has a factor, it has one less than or equal to its square root. Impact. Many fewer iterations of for loop. Check if i is a factor. public class Factors3 { long N = Long.parseLong(args[0]); for (long i = 2; i <= N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; As long as i is a factor, divide it out. Check if i is a factor. public class Factors { long N = Long.parseLong(args[0]); for (long i = 2; i*i <= N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; As long as i is a factor, divide it out. too slow for large N (999,999,937) if (N > 1) System.out.println(N); else System.out.println(); Corner case: biggest factor occurs once. Performance error 33 34 Debugging a Program: Trace Debugging a Program: Analysis % java Factors 3757208 2 2 2 7 13 13 397 Q. How large an integer can I factor? % java Factors 168 2 2 2 3 7 % java Factors 3757208 2 2 2 7 13 13 397 % java Factors 9201111169755555703 9201111169755555703 after a few minutes of computing. 3757208/8 Digits (i <= N) (i*i <= N) largest factor 3 instant instant 6 0.15 seconds instant 9 77 seconds instant 12 21 hours 0.16 seconds 15 2.4 years 2.7 seconds 18 2.4 millennia 92 seconds estimated 35 36

Programming in Java Debugging a Program Programming in Java. [a slightly more realistic view] 1. Create the program. 2. Compile it.. Compiler says: That s not a legal program. Back to step 1 to fix your errors of syntax. Debugging. Cyclic process of editing, compiling, and fixing errors.! Always a logical explanation.! What would the machine do?! Explain it to the teddy bear. You will make many mistakes as you write programs. It's normal. 3. Execute it. Result is bizarrely (or subtly) wrong. Back to step 1 to fix your errors of semantics. 4. Enjoy the satisfaction of a working program! As soon as we started programming, we found out to our surprise that it wasn't as easy to get programs right as we had thought. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. - Maurice Wilkes If I had 8 hours to chop down a tree, I would spend 6 hours sharpening an axe. - Abraham Lincoln 37 38 Control Flow Summary U.S.S. Grace Murray Hopper Control flow.! Sequence of statements that are actually executed in a program.! Conditionals and loops: enables 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 39 40