Question? Leave a message!




Conditionals and Loops

Conditionals and Loops
1.3 Conditionals and Loops Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/6/11 12:44 PM 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 text I/O last lecture: equivalent primitive data types assignment statements 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 to infinity conditionals and loops and beyond Math text I/O primitive data types 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. boolean 1 statement 1 true false statement 2 statement 1 true boolean 2 statement 2 statement 3 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) boolean expression statement T; can be any sequence of statements false true else statement F; 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"); elseMath.random() 0.5) 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 statement 2 while (boolean expression) statement 1; loop body statement 2; true boolean expression statement 1 false 11 While Loop: Powers of Two N Ex. Print powers of 2 that are 2 .   Increment i from 0 to N.   Double v each time. i v i = N 0 1 true 0 1 1 2 1 2 true int i = 0; 2 4 int v = 1; 3 8 2 4 true 4 16 while (i = N) 5 32 System.out.println(i + " " + v); 3 8 true 6 64 i = i + 1; 4 16 true v = 2 v; 5 32 true 6 64 true 7 128 false N = 6 Click for demo 12 Powers of Two % java PowersOfTwo 3 public class PowersOfTwo 0 1 public static void main(String args) 1 2 2 4 // last power of two to print 3 8 int N = Integer.parseInt(args0); % java PowersOfTwo 6 int i = 0; // loop control counter 0 1 1 2 int v = 1; // current power of two 2 4 while (i = N) 3 8 System.out.println(i + " " + v); 4 16 i = i + 1; 5 32 v = 2 v; 6 64 print i and ith power of two 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 Loops: Square Root Goal. Implement Math.sqrt(). % java Sqrt 2.0 1.414213562373095 Newton-Raphson method to compute the square root of c: 15 decimal digits of   Initialize t = c. 0 accuracy in 5 iterations   Repeat until t = c / t , up to desired precision: i i set t to be the average of t and c / t . i+1 i i t = 2.0 0 1 2 t = (t + ) = 1.5 1 0 2 t 0 1 2 t = (t + ) = 1.416666666666665 2 1 2 t 1 1 2 t = (t + ) = 1.4142156862745097 3 2 2 t 2 1 2 t = (t + ) = 1.4142135623746899 4 3 2 t 3 1 2 t = (t + ) = 1.414213562373095 5 4 2 t 4 computing the square root of 2 Copyright 2004, Sidney Harris http://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: 15 decimal digits of   Initialize t = c. 0 accuracy in 5 iterations   Repeat until t = c / t , up to desired precision: i i set t to be the average of t and c / t . i+1 i i public class Sqrt public static void main(String args) double epsilon = 1e-15; double c = Double.parseDouble(args0); double t = c; while (Math.abs(t - c/t) tepsilon) t = (c/t + t) / 2.0; relative error System.out.println(t); tolerance 17 Newton-Raphson Method Square root method explained.   Goal: find root of any function f(x). 2   Start with estimate t . f(x) = x - c to compute "c 0   Draw line tangent to curve at x= t . i   Set t to be x-coordinate where line hits x-axis. i+1   Repeat until desired precision. Technical conditions. f(x) must be smooth; t must be good estimate. 0 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 init increment for (init; boolean expression; increment) statement 1; statement 2; statement 2 body true boolean expression statement 1 false 20 Anatomy of a For Loop 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. i ruler public class RulerN " " public static void main(String args) int N = Integer.parseInt(args0); 1 " 1 " String ruler = " "; for (int i = 1; i = N; i++) 2 " 1 2 1 " ruler = ruler + i + ruler; 3 " 1 2 1 3 1 2 1 " System.out.println(ruler); 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% 5 mutually exclusive alternatives 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; graduated income tax calculation 27 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; 28 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. 29 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 30 Monte Carlo Simulation 31 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. 32 Gambler's Ruin public class Gambler public static void main(String args) int stake = Integer.parseInt(args0); int goal = Integer.parseInt(args1); int T = Integer.parseInt(args2); 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); 33 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 after a substantial wait…. % java Gambler 500 2500 1000 197 wins of 1000 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. 34 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 all statements are programs executed in the order given certain statements are if conditionals executed depending on the if-else values of certain variables certain statements are while executed repeatedly until for loops certain conditions are met do-while 35
Website URL
Comment
sharer
Presentations
Free
Document Information
Category:
Presentations
User Name:
Dr.AlexanderTyler
User Type:
Teacher
Country:
India
Uploaded Date:
21-07-2017