1 3 Conditionals and Loops With notes by

1. 3 Conditionals and Loops With notes by Ron Cytron shown like this. Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002– 2010 · 6/14/2021 6: 56: 04 AM

WUTexter Poll Please pick the response that most resembles your situation • A: I have finished Lab 1 (Nutrition) • B: I am almost done with Lab 1 • C: I have started Lab 1 but have not gotten very far • D: I have not started Lab 1 • E: I am not aware that we have an assignment called Lab 1 2

WUTexter Quiz Which of the following is NOT a Java keyword used in expressing loops? • • • A: B: C: D: E: while loop for until All of the above are keywords for expressing loops 3

A Foundation for Programming any program you might want to write objects functions and modules In fact, an extension is available for Module 1 in which you fill in the missing pieces of a calculator. 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 4

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 to infinity and beyond! text I/O assignment statements 5

Control Flow Control flow. Sequence of statements that are actually executed in a program. Conditionals and loops: enable us to choreograph control flow. n n boolean 1 statement 1 true false statement 2 statement 1 statement 3 boolean 2 true statement 2 false statement 4 statement 3 straight-line control flow with conditionals Figure on right credit: http: //www. saynotocrack. com/wp-content/uploads/2007/01/flowchart. jpg 6

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

Conditionals

If Statement The if statement. A common branching structure. Evaluate a boolean expression. If true, execute some statements. If false, execute other statements. n n n if (boolean expression) { statement T; can be any sequence } of statements else { statement F; } boolean expression true statement T false statement F Although there are many ways to format the code you see above, the above formatting is considered the best style. 9

If Statement The if statement. A common branching structure. Evaluate a boolean expression. If true, execute some statements. If false, execute other statements. n Code and its corresponding flow chart n n These are 3 different examples int max; What is the effect of the sequence in the braces? It exchanges the values of x and y. Teaser: can you exchange x and y without using another variable such as t? You’ll need a boolean operation we have not studied. 10

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 Remember: all of these code samples are in your repositories, so you can run them. % java Flip Heads % java Flip Tails % java Flip Heads 11

If Statement Examples 12

The While Loop 13

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

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

Powers of Two In your repo…. public class Powers. Of. Two { public static void main(String[] args) { // last power of two to print N = Integer. parse. Int(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 % 0 1 2 3 java Powers. Of. Two 3 1 2 4 8 % 0 1 2 3 4 5 6 java Powers. Of. Two 6 1 2 4 8 16 32 64 } } 16

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; Use WUTexter message to say what’s wrong 17

While Loop Challenge Q. Anything wrong with the following code for printing powers of 2? Eclipse is pretty good about indenting automatically for you and avoiding these kinds of problems. int i = 0; int v = 1; while (i <= N) System. out. println(i + " " + v); i = i + 1; The while loop affects only this v = 2 * v; statement, even though the indentation makes us think otherwise. 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? When your program is running, eclipse shows a red square button. Pusing it will terminate your application, even if it is running in an infinite loop. Why doesn’t eclipse warn you that your program has an infinite loop? Because this problem is in general undecidable, which means there is no way to answer that question definitively for every program. 18

While Loops: Square Root Goal. Implement Math. sqrt(). You are welcome to look at this on your own. I do not find it particuarly instructive. Another example is coming up that I think is better. Skip % java Sqrt 2. 0 1. 414213562373095 Newton-Raphson method to compute the square root of c: Initialize t 0 = c. Repeat until ti = c / ti, up to desired precision: set ti+1 to be the average of ti and c / ti. n 15 decimal digits of accuracy in 5 iterations n computing the square root of 2 Copyright 2004, Sidney Harris www. sciencecartoonsplus. com 19

While Loops: Square Root Goal. Implement Math. sqrt(). Skip % java Sqrt 2. 0 1. 414213562373095 Newton-Raphson method to compute the square root of c: Initialize t 0 = c. Repeat until ti = c / ti, up to desired precision: set ti+1 to be the average of ti and c / ti. n 15 decimal digits of accuracy in 5 iterations n public class Sqrt { public static void main(String[] args) { double epsilon = 1 e-15; double c = Double. parse. Double(args[0]); double t = c; while (Math. abs(t - c/t) > t*epsilon) { t = (c/t + t) / 2. 0; } relative error System. out. println(t); tolerance } } This is a numerical recipe or algorithm. An explanation appears in a few slides as to why this algorithm works. You do not need to know the details for this class. A course in numerical methods covers material like this. 20

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

The For Loop This code is written in the C programming language. C is a predecessor of Java, and Java borrows from C’s syntax. The “for” loop is an example of this. “printf” is like “System. out. println”. What other parts of C look like Java? Copyright 2004, Fox. Trot by Bill Amend www. ucomics. com/foxtrot/2003/10/03 22

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. n n n loop continuation condition init increment for (init; boolean expression; increment) { statement 1; statement 2; body } statement 2 boolean expression true statement 1 false 23

Anatomy of a For Loop shorthand for i = i +1 So is ++i and I like that better than i++. It is much more common to see i < N here, especially when i starts at 0. Q. What does it print? A. Do you see why? (How many times does this loop actually iterate as written? ) 24

Which to use, while or for loops? The “for” looop packages the initialization, termination, and iteration of i all in one statement. The “while” loop spreads this around and makes the gesture harder to see. 25

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. n n public class Ruler. N { public static void main(String[] args) { int N = Integer. parse. Int(args[0]); String ruler = " "; for (int i = 1; i <= N; i++) { ruler = ruler + i + ruler; } System. out. println(ruler); } } i ruler " " 1 " 2 " 1 2 1 " 3 " 1 2 1 3 1 2 1 " This one is not in your repo 26

For Loops: Subdivisions of a Ruler % java Ruler. N 1 1 % java Ruler. N 2 1 % java Ruler. N 3 1 2 1 % java Ruler. N 4 1 2 1 3 1 2 1 % java Ruler. N 5 1 2 1 3 1 2 1 4 1 2 1 3 1 2 1 % java Ruler. N 100 Exception in thread "main" java. lang. Out. Of. Memory. Error Observation. Loops can produce a huge amount of output! 27

Loop Examples It’s bad practice and bad style to leave out the curly braces. When you use elipse, type the opening one and it will complete the block for you. Shorthand for sum = sum + i Shorthand for product = product * i 28

Nesting 29

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% 174, 700 – 311, 950 33% 311, 950 - 35% double rate; if (income else < 47450) rate = < 114650) rate = < 174700) rate = < 311950) rate = 5 mutually exclusive alternatives Notice how easy it is to read this code because of the way it is formatted, but……. 0. 22; 0. 25; 0. 28; 0. 33; 0. 35; graduated income tax calculation 31

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; } } } ……. A strict interpretation of the CSE 131 Style Guide tells you to write the code this way. 32

Nested If Statements Need all those braces? Not always. So which of these should you use? is shorthand for Mistakes in formatting are often revealed (and then easily solved) by having eclispe format your whole file. Use control (apple)-A and then control (apple) -I 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; 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; } } These Q+A sections are } very useful! but be careful when nesting if-else statements. [See Q+A on p. 75. ] 33

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) if (income < 114650) if (income < 174700) if (income < 311950) rate = = 0. 22; 0. 25; 0. 28; 0. 33; Do you see a clever way to fix this without resorting to “else”? Would that be a prefered way to express this idea? Why or why not? wrong graduated income tax calculation 34

Monte Carlo Simulation 35

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? n n One approach. Monte Carlo simulation. Flip digital coins and see what happens. Repeat and compute statistics. n n 36

Digression: Simulation and Analysis stake goal T Code in repo, fun to run actually. Gambler’s ruin: No matter how much you start with, as long as there is some chance of losing, if you gamble long enough, you eventually lose everything. % java Gambler 5 25 1000 191 wins of 1000 So, 1000 -191 = 809 ruins! % java Gambler 5 25 1000 203 wins of 1000 % java Gambler 500 2500 1000 197 wins of 1000 after a substantial wait…. Fact. [see ORF 309] Probability of winning = stake goal. Fact. [see ORF 309] Expected number of bets = stake desired gain. Ex. 20% chance of turning $500 into $2500, 500/2500 = 20% but expect to make one million $1 bets. 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. 37
![Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake](http://slidetodoc.com/presentation_image_h2/71b47a388f65eac2e628d24051ee8b0d/image-37.jpg)
Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake = Integer. parse. Int(args[0]); int goal = Integer. parse. Int(args[1]); int T = Integer. parse. Int(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++; } } We next look at how to think about this System. out. println(wins + the " computation wins of " + T); part, from a story about to the necessary code. } 38

Gambler’s Ruin This section of slides by RKC. This is not in the book but it’s important to have strategies for creating code, other than mimicking already-written code. How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 while (/* still have cash left and I have not reached my goal */) { // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar What are the as-yetunamed “concepts” needed in this program? } System. out. println(“I was able to make this number of bets: “); 39

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 while (/* still have cash left and I have not reached my goal */) { // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar What are the as-yetunamed “concepts” needed in this program? } System. out. println(“I was able to make this number of bets: “); 40

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; Give the concept a name and an initial value. while (/* still have cash left and I have not reached my goal */) { // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar What are the as-yetunamed “concepts” needed in this program? } System. out. println(“I was able to make this number of bets: “); 41

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; Give the concept a name and an initial value. Now you can use it. while (/* still have cash left and I have not reached my goal */) { // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar What are the as-yetunamed “concepts” needed in this program? } System. out. println(“I was able to make this number of bets: “ + bets); 42

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; Give the concept a name and an initial value. Adjust the value as needed while (/* still have cash left and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar } System. out. println(“I was able to make this number of bets: “ + bets); 43

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; What other concepts are needed? while (/* still have cash left and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar } System. out. println(“I was able to make this number of bets: “ + bets); 44

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 What other concepts are int bets = 0; needed? int cash = stake; Name and initialize the value while (/* still have cash left and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar } System. out. println(“I was able to make this number of bets: “ + bets); 45

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 What other concepts are int bets = 0; needed? int cash = stake; How do we express this now? while (/* still have cash left and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar } System. out. println(“I was able to make this number of bets: “ + bets); 46

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 What other concepts are int bets = 0; needed? int cash = stake; Use the name. while (cash > 0 /* and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, increase my cash by 1 dollar // If I lose, decrease my cash by 1 dollar } System. out. println(“I was able to make this number of bets: “ + bets); 47

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 What other concepts are int bets = 0; needed? int cash = stake; Use the name. while (cash > 0 /* and I have not reached my goal */) { bets = bets + 1; // Flip a (fair) coin. // If I win, cash = cash + 1; // If I lose, cash = cash – 1; } System. out. println(“I was able to make this number of bets: “ + bets); 48

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; int cash = stake; while (cash > 0 && cash < goal) { bets = bets + 1; // Flip a (fair) coin. // If I win, cash = cash + 1; // If I lose, cash = cash – 1; } What other concepts are needed? Use the name. System. out. println(“I was able to make this number of bets: “ + bets); 49

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; Coin flip via random number int cash = stake; generator while (cash > 0 && cash < goal) { bets = bets + 1; if (Math. random() < 0. 5) // flip a fair coin cash = cash + 1; // I won else cash = cash – 1; // I lost } System. out. println(“I was able to make this number of bets: “ + bets); 50

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; int cash = stake; while (cash > 0 && cash < goal) { bets = bets + 1; if (Math. random() < 0. 5) // flip a fair coin cash = cash + 1; // I won else cash = cash – 1; // I lost } The loop continues execution until this predicate becomes false We thus arrive here under one of two conditions: • Out of cash <= 0 • Reached goal cash >= goal System. out. println(“I was able to make this number of bets: “ + bets); 51

Gambler’s Ruin How do we think about writing loops? From pseudocode to code…. Gambler’s ruin simulation excerpted from Gambler. java: int stake = 25; // start with 25 dollars int goal = 500; // would like to make it to $500 int bets = 0; int cash = stake; The loop continues execution until this predicate becomes while (cash > 0 && cash < goal) { false bets = bets + 1; if (Math. random() < 0. 5) // flip a fair coin cash = cash + 1; // I won else cash = cash – 1; // I lost We thus arrive here under one of two conditions: } • Out of cash <= 0 • Reached goal cash >= goal System. out. println(“You won? “ + (cash >= goal) ); System. out. println(“I was able to make this number of bets: “ + bets); 52
![Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake](http://slidetodoc.com/presentation_image_h2/71b47a388f65eac2e628d24051ee8b0d/image-52.jpg)
Gambler's Ruin public class Gambler { public static void main(String[] args) { int stake = Integer. parse. Int(args[0]); int goal = Integer. parse. Int(args[1]); int T = Integer. parse. Int(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); } } 53

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. n n Control Flow Description Examples straight-line programs all statements are executed in the order given conditionals certain statements are executed depending on the values of certain variables if if-else loops certain statements are executed repeatedly until certain conditions are met while for do-while 54

Extra Slides

Oblivious Sorting Sort. Read in 3 integers and rearrange them in ascending order. public class Sort 3 { public static void main(String[] args) { int a = Integer. parse. Int(args[0]); int b = Integer. parse. Int(args[1]); int c = Integer. parse. Int(args[2]); read in 3 integers from command-line swap b and c if (b > c) { int t = b; b = c; c = t; } if (a > b) { int t = a; a = b; b = t; } if (b > c) { int t = b; b = c; c = t; } swap a and b swap b and c System. out. println(a + " " + b + " " + c); } } Puzzle 1. Sort 4 integers with 5 compare-exchanges. % java Sort 3 9 8 7 7 8 9 % java Sort 3 2 1 7 1 2 7 Puzzle 2. Sort 6 integers with 12. 56

Do-While Loop The do-while loop. A less common repetition structure. Execute sequence of statements. Check loop-continuation condition. Repeat. n n n true do { statement 1; statement 2; } while (boolean expression); do-while loop syntax statement 1 boolean expression statement 2 false 57

Do-While Loop Ex. Find a point (x, y) that is uniformly distributed in unit disc. Pick a random point in unit square. Check if point is also in unit disc. Repeat. n n n do { x = 2. 0 * Math. random() - 1. 0; y = 2. 0 * Math. random() - 1. 0; } while (x*x + y*y > 1. 0); between – 1 and 1 58
- Slides: 57