While Loops Lecture : Loops The while loop is a common repetition structure. Check loop-continuation condition. Execute a sequence of statements. Repeat. while (boolean expression) statement; while loop syntax loop-continuation condition boolean expression false statement body Introduction to Computer Science Robert Sedgewick and Kevin Wayne http://www.princeton.edu/~cs6 while loop flow chart While Loops: Powers of Two While Loops: Newton-Raphson Method While loop example: print powers of. Increment i from to 6 by. How are functions like Math.sqrt implemented? Goal: compute the square root of c. Double N each time. Initialize t = c. Replace t with the average of t and c / t. int i = 0; int N = ; while (i <= 6) { System.out.println(N); i = i + ; N = * N; a block statement Click for demo i 0 5 6 7 N 8 6 6 8 i <= 6 false % java Powers 8 6 6 Repeat until t = c / t, up to desired precision. public class Sqrt { double c = Double.parseDouble(args[0]); double t = c; while (t - c/t > 0.00000000000000) { t = (c/t + t) /.0; error tolerance System.out.println(t); % java Sqrt.0.567095 Accurate to 5 decimal places in 5 iterations.
While Loops: Newton-Raphson Method For Loops Newton-Raphson method explained. The for loop is another common repetition structure. Goal: find root of function f(x). Initialize variable. Ex: f(x) = x - c Start with estimate t 0. Draw line tangent to curve at x= t i. Set t i+ to be x-coordinate where line hits x-axis. Repeat until desired precision. Check loop-continuation condition. Execute sequence of statements. Increment variable. Repeat. for (init; boolean; update) statement; initialization update Applications and extensions. for loop syntax Find the roots of any differentiable function of a single variable. Find the roots of a function of several variables. Optimize a twice differentiable function: find where derivative = 0. Optimize a function subject to constraints. loop-continuation condition boolean expression false statement body for loop flow chart 5 6 For Loops: Subdivisions of a Ruler For Loops: Subdivisions of a Ruler Create subdivision of a ruler. Initialize ruler to the empty string. For each value i = to N. Sandwich two copies of the ruler on either side of i. Observation. Program produces N integers. Loops can produce a huge amount of output! String ruler = " "; for (int i = ; i <= N; i++) { ruler = ruler + i + ruler; i ruler % java Ruler % java Ruler % java Ruler System.out.println(ruler); Java code N = % java Ruler % java Ruler 00 Exception in thread "main" java.lang.outofmemoryerror 7 8
Nesting Conditionals and Loops Nested If-Else Conditional statements enable you to perform one of N sequences of operations with N lines of code. Loops enable you to do something N times using only lines of code. Nesting conditionals within conditionals. Pay a certain tax rate depending on income level. if (a0 > 0) System.out.print(0); if (a > 0) System.out.print(); if (a > 0) System.out.print(); if (a > 0) System.out.print(); if (a > 0) System.out.print(); 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); 0 possible results, depending on input sum = 0.0; for (int i = ; i <= 0; i++) ans +=.0 / i; computes / + / +... + /0 if (income < 750) rate = 0.; else if (income < 650) rate = 0.5; else if (income < 7700) rate = 0.8; else if (income < 950) rate = 0.; else rate = 0.5; graduated income tax calculation Income 0-750 750,650,650 7,700 7,700 950,950 Rate % 5% 8% % 5% More sophisticated programs. Nest conditionals within conditionals. Nest loops within loops. Nest conditionals within loops within loops. 9 0 Gambler's Ruin Library Functions: Math.random Gambler starts with $stake and places $ even bets until going broke or reaching $goal. What are the chances of winning? How many bets will it take? Cash One approach: numerical simulation. Flip digital coins and see what happens. Repeat and compute statistics. goal = stake = 6 Math.random generates number between 0 and. How is Math.random implemented? Linear feedback shift register? Cosmic rays? User doesn't need to know details. User doesn't want to know details. Caveats. "Random" numbers are not really random. Don't use for crypto or Internet gambling! Check assumptions about library function before using. Time One simulation of the gambler's ruin problem. $0
Gambler's Ruin Simulation and Analysis a complicated block statement public class Gambler { int stake = Integer.parseInt(args[0]); int goal = Integer.parseInt(args[]); int N = Integer.parseInt(args[]); int wins = 0; // do N simulations for (int i = 0; i < N; i++) { // do one simulation int t = stake; while (t > 0 && t < goal) { if (Math.random() > 0.5) t++; else t--; if (t == goal) wins++; flip one coin System.out.println(wins + " wins of " + N); Gambler starts with $stake and places $ even bets until going broke or reaching $goal. What are the chances of winning? How many bets will it take? stake goal N % java Gambler 0 0 000 5 wins of 000 % java Gambler 0 0 000 9 wins of 000 % java Gambler 500 500 00 wins of 00 takes a few minutes Fact: Probability of winning is ratio of stake to goal. Fact: Expected number of bets is product of stake and desired gain. Ex: You have a 0% chance of turning $500 into $500, but you should expect to make one million $ bets. Debugging a Program: Syntax Errors Debugging a Program: Semantic Errors Given an integer N, compute its prime factorization. Application: break RSA cryptosystem. 68 = 7 Semantic error: legal but wrong Java program. Use "System.out.println" method to identify problem. Syntax error: illegal Java program. Compiler error messages help locate problem. Eventually, a file named Factors.class. public class Factors { long N = Long.parseLong(args[0]) for (i = 0; i < N; i++) { while (N % i == 0) System.out.print(i + " ") N = N / i Check if i is a factor. public class Factors { long N = Long.parseLong(args[0]); for (long i = ; i < N; i++) { while (N % i == 0) System.out.print(i + " "); N = N / i; Check if i is a factor. Does not compile No output (7) or infinite loop (9) 5 6
Debugging a Program: Performance Errors Debugging a Program: Success Performance error: correct program but too slow. Use profiling to discover bottleneck. Devise better algorithm. If N has a factor, it has one less than or equal to its square root. Many fewer iterations of for loop. public class Factors { long N = Long.parseLong(args[0]); public class Factors { long N = Long.parseLong(args[0]); for (long i = ; i <= N; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; Too slow for large N Check if i is a factor. Check if i is a factor. for (long i = ; i <= N / i; i++) { while (N % i == 0) { System.out.print(i + " "); N = N / i; if (N > ) System.out.println(N); else System.out.println(); Special case. 7 8 Debugging a Program: Analysis Debugging a Program How big of an integer can I factor? % java Factors 68 7 % java Factors 6065007 009 00 00 Debug: cyclic process of editing, compiling, and fixing errors. Always a logical explanation. What would the machine do? Say it to the teddy bear. biggest factor Dec Digits 6 9 5 8 % java Factors 906975555570 906975555570 minutes i <= N i <= N / i i * i <= N 0.5 seconds 77 seconds hours 0. seconds 0.6 seconds. years.5 seconds.7 seconds. millennia 57 seconds 9 seconds estimated You will make many mistakes as you write programs. It's normal. "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 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, 99 9 0
Etymology and Entomology of Computer "Bug" Flow Of Control Summary Flow of control. Sequence of statements that are actually executed in a program. Flow-of-Control Straight-line programs Conditionals Loops Description 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. Examples if if-else while for do-while Grace Hopper Admiral, US Navy Conditionals and loops. Simple, but powerful tools. Enables us to harness power of the computer.