A Foundation for Programming 1.3 Conditionals and Loops 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 Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright 00 010 19 May 01 1:45:09 A Foundation for Programming Control Flow any program you might want to write Control flow Sequence of statements that are actually executed in a program Conditionals and loops: enable us to choreograph control flow objects boolean 1 functions and modules graphics, sound, and image I/O arrays statement statement 3 boolean statement conditionals and loops to infinity and beyond! Math text I/O statement 4 primitive data types assignment statements straight-line control flow statement 3 control flow with conditionals and loops 3 4 If Statement Conditionals The if statement A common branching structure If, execute some statements If, execute other statements if (boolean expression) { statement T; can be any sequence of statements statement F; boolean expression statement T statement F 6 1
If Statement If Statement The if statement A common branching structure If, execute some statements If, execute other statements Ex. Take different action depending on value of variable. public class Flip { if (Math.random() < 0.5) System.out.println("Heads"); else System.out.println("Tails"); Heads Heads Tails Heads 7 8 If Statement Examples The For Loop Copyright 004, FoxTrot by Bill Amend www.ucomics.com/foxtrot/003/10/03 9 10 For Loops Anatomy of a For Loop The for loop A common repetition structure Execute initialization statement If, execute some statements And then the increment statement Repeat loop continuation condition for (init; boolean expression; increment) { ; statement ; body init increment statement shorthand for i = i +1 boolean expression Q. What does it print? A. 11 1
For Loop: Powers of Two For Loops: Subdivisions of a Ruler Ex. Print powers of that are Increment i from 0 to N Double v each time N Create subdivision of a ruler Initialize ruler to " " For each value i from 1 to N: i v i <= N sandwich two copies of ruler on either side of i 1 4 5 3 7 18 1 4 5 3 public class RulerN { 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 " " 1 1 " 3 " 1 1 3 1 1 " N = 6 Click for demo 13 14 For Loops: Subdivisions of a Ruler % java RulerN 1 1 The While Loop % java RulerN 1 1 % java RulerN 3 1 1 3 1 1 % java RulerN 4 1 1 3 1 1 4 1 1 3 1 1 % java RulerN 5 1 1 3 1 1 4 1 1 3 1 1 5 1 1 3 1 1 4 1 1 3 1 1 % java RulerN 100 Exception in thread "main" java.lang.outofmemoryerror Observation Loops can produce a huge amount of output! 15 16 While Loop While Loop: Powers of Two The while loop. Another common repetition structure If, execute some statements Repeat Ex. Print powers of that are Increment i from 0 to N Double v each time N i v i <= N loop continuation condition statement while (boolean expression) { ; loop body statement ; boolean expression int i = 0; int v = 1; while (i <= N) { i++; v = * v; 1 4 5 3 1 4 5 3 7 18 N = 6 Click for demo 17 18 3
Powers of Two While Loop Challenge Q. Anything wrong with the following code for printing powers of? 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) { i = i + 1; v = * v; print i and ith power of two % java PowersOfTwo 3 1 4 % java PowersOfTwo 6 1 4 5 3 int i = 0; int v = 1; while (i <= N) i = i + 1; v = * v; 19 0 While Loop Challenge While Loops: Square Root Q. Anything wrong with the following code for printing powers of? Goal. Implement Math.sqrt() % java Sqrt.0 1.4141356373095 int i = 0; int v = 1; while (i <= N) i = i + 1; v = * v; 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 A. Need curly braces around statements in while loop; otherwise it enters an infinite loop, printing "". Moment of panic. How to stop infinite loop? t 0.0 t 1 1 0 t 1 1 t 3 1 t 4 1 3 t 5 1 4 t 0 ) 1.5 t 1 ) 1.416666666666665 t ) 1.41415686745097 t 3 ) 1.41413563746899 t 4 ) 1.4141356373095 computing the square root of Copyright 004, Sidney Harris www.sciencecartoonsplus.com 1 While Loops: Square Root Newton-Raphson Method Goal. Implement Math.sqrt(). % java Sqrt.0 1.4141356373095 Square root method explained Goal: find root of any function f(x) 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 Start with estimate t 0 f(x) = x - 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 public class Sqrt { 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) /.0; relative error System.out.println(t); tolerance Technical conditions. f(x) is smooth; t 0 is good estimate 3 4 4
Loop Examples Nesting 5 6 Nested If Statements Nested If Statements Ex. Pay a certain tax rate depending on income level Use nested if statements to handle multiple alternatives Income Rate 0-47,450 % 47,450 114,650 5% 114,650 174,700 8% 174,700 311,950 33% 311,950-35% double rate; if (income < 47450) rate = 0.; else if (income < 114650) rate = 0.5; else if (income < 174700) rate = 0.8; else if (income < 311950) rate = 0.33; 5 mutually exclusive alternatives if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; graduated income tax calculation 8 9 Nested If Statements Nested If Statement Challenge Need all those braces? Not always Q. What's wrong with the following for income tax calculation? if (income < 47450) rate = 0.; else if (income < 114650) rate = 0.5; else if (income < 174700) rate = 0.8; else if (income < 311950) rate = 0.33; Income Rate 0-47,450 % 47,450 114,650 5% is shorthand for if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; 114,650 174,700 8% 174,700 311,950 33% 311,950-35% double rate = 0.35; if (income < 47450) rate = 0.; if (income < 114650) rate = 0.5; if (income < 174700) rate = 0.8; if (income < 311950) rate = 0.33; but be careful when nesting if-else statements. [See Q+A on p. 75.] wrong graduated income tax calculation 30 31 5
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 3 33 Gambler's Ruin Digression: Simulation and Analysis public class Gambler { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[1]); int T = Integer.parseInt(args[]); 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); stake goal T % java Gambler 5 5 1000 191 wins of 1000 % java Gambler 5 5 1000 03 wins of 1000 % java Gambler 500 50000 197 wins of 1000 after a substantial wait. Fact Probability of winning = stake goal Fact Expected number of bets = stake desired gain Ex. 0% chance of turning $500 into $500, 500/500 = 0% but expect to make one million $1 bets 500 * (500-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 35 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 36 6