1 CS1110 Lecture 16, 26 Oct 2010 While-loops Reading for next time: Ch. 8.1-8.3 (arrays) Prelim 2: Tu Nov 9 th, 7:30-9pm. Last name A-Lewis: Olin 155 Last.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

MATH 224 – Discrete Mathematics
50.530: Software Engineering Sun Jun SUTD. Week 10: Invariant Generation.
SEARCHING AND SORTING HINT AT ASYMPTOTIC COMPLEXITY Lecture 9 CS2110 – Spring 2015 We may not cover all this material.
Reasoning About Code; Hoare Logic, continued
Designing Algorithms Csci 107 Lecture 4. Outline Last time Computing 1+2+…+n Adding 2 n-digit numbers Today: More algorithms Sequential search Variations.
1 CS March 2009 While loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim in two days: Th 7:30-9pm Uris Aud.
CS100J October 07, 2003 Loops Repetitive statements, or iterative statements, or loops “O! Thou hast damnable iteration and art, indeed, able to corrupt.
1 CS100J October 06, 2005 For Loops Reading: Secs Quote for the Day: Perhaps the most valuable result of all education is the ability to make yourself.
1 CS100J 15 March, 2006 The while loop and assertions Read chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal.
CS 1110 Prelim III: Review Session 1. Info My name: Bruno Abrahao – We have two other TA’s in the room to help you individually Beibei Zhu Suyong Zhao.
1 Recitation 7. Developing loops Introduction. This recitation concerns developing loops using their invariants and bound functions. Your recitation instructor.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Algorithms: Selected Exercises Goals Introduce the concept & basic properties of an algorithm.
1 CS1110, 20 Oct. 2009, Lec 14 Elementary graphics; intro to loops and for-loops Reading: Sec and chapter 7 on loops. The lectures on the ProgramLive.
1 CS October 2008 The while loop and assertions Read chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Quotes for the Day:
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
1 “Not all recursive solutions are better than iterative solutions…” “… recursion, however, can provide elegantly simple solutions to problems of great.
Introduction to Programming (in C++) Algorithms on sequences. Reasoning about loops: Invariants. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept.
1 CS100J 09 March, 2006 More on Loops Reading: Secs 7.1–7.4 A Billion. The next time you hear someone in government rather casually use a number that includes.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CS 61B Data Structures and Programming Methodology July 28, 2008 David Sun.
1 CS1110, 8 March 2009 Two topics: elementary graphics (for A5); loops Reading: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can.
Examples of Recursion Data Structures in Java with JUnit ©Rick Mercer.
1 CS March 2010 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal pointI'm.
Application: Correctness of Algorithms Lecture 22 Section 4.5 Fri, Mar 3, 2006.
Looping and Counting Lecture 3 Hartmut Kaiser
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 On (computational) simplicity We are trying to teach not just Java, but how to think about problem solving. Computer science has its field called computational.
Application: Correctness of Algorithms Lecture 22 Section 4.5 Fri, Feb 18, 2005.
1 CompSci 105 SS 2005 Principles of Computer Science Lecture 6: Recursion Lecturer: Santokh Singh Assignment 1 due tomorrow. Should have started working.
CS November 2010 Developing array algorithms. Reading: Haikus (5-7-5) seen on Japanese computer monitors Yesterday it worked. Today it is.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
Cosc175/operators1 Algorithms computer as the tool process – algorithm –Arithmetic: addition,subtraction,multiplication,division –Save information for.
1 CS April 2010 while loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim 2. Thursday evening, 7:30PM Watch.
Operators.
Expressions and Order of Operations Operators – There are the standard operators: add, subtract, divide, multiply – Note that * means multiply? (No times.
1 CS April 2010 while loops Reading: today: Ch. 7 and ProgramLive sections. For next time: Ch Prelim 2. Thursday evening, 7:30PM Watch.
Searching CSE 103 Lecture 20 Wednesday, October 16, 2002 prepared by Doug Hogan.
1 CS100J September 27, 2003 Loops Repetitive statements, or iterative statements, or loops “O! Thou hast damnable iteration and art, indeed, able to corrupt.
1 CS100J 06 March 2008 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal pointI'm.
CS100A, Fall Review of loops 1 CS100A, Fall 1998, Review of Loops and Loop Invariants Some students are still having trouble understanding loop invariants.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2014.
CORRECTNESS ISSUES AND LOOP INVARIANTS Lecture 8 CS2110 – Fall 2015.
Control Structures: Examples. for-loop example Q: If a=1, b=3, and x=7, what is the value of x when the loop terminates? A: x=1 for(k=a; k
Recursion (Continued)
Week 2 - Wednesday CS 121.
Correctness issues and Loop invariants
Start reading Sec and chapter 7 on loops
ECS10 10/10
Data Structures in Java with JUnit ©Rick Mercer
CS October 2009 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal point I'm.
Developing Loops from Invariants
CS October 2008 The while loop and assertions
Recursion (Continued)
Algorithms computer as the tool process – algorithm
Asymptotic complexity Searching/sorting
Output Variables {true} S {i = j} i := j; or j := i;
Binary Search and Loop invariants
Asymptotic complexity
CS November 2010 Developing array algorithms. Reading:
Developing loops from invariants
CS100A Sections Dec Loop Invariant Review C Review and Example
Developing Loops from Invariants
Searching and Sorting Hint at Asymptotic Complexity
Searching and Sorting Hint at Asymptotic Complexity
COMPUTING.
CS100J 16 Oct, 2007 Assignment A5: loops
CS October 2010 Read: Sec and chapter 7 on loops. The lectures on the ProgramLive CD can be a big help. Some anagrams A decimal point I'm.
Presentation transcript:

1 CS1110 Lecture 16, 26 Oct 2010 While-loops Reading for next time: Ch (arrays) Prelim 2: Tu Nov 9 th, 7:30-9pm. Last name A-Lewis: Olin 155 Last name Li-Z: Olin 255 Conflicts? Submit CMS "assignment" "P2 conflicts" by today. Review session: Sun Nov 7 th, 1-3pm, Phillips 101. (Set your clocks back the night before!) Reminder: A5 due Sat. Oct 30th. See assignments pg for hints on snowflake geometry. A mystery (due to von Neumann): suppose you have a biased coin with unknown probability of heads p, 0 < p < 1. How can you use this coin to simulate the output of a fair coin? (Answer: while-loops …)

2 Beyond ranges of integers: the while loop while ( ) { sequence of statements } boolean expression. = "there's still stuff to do" the In comparison to for-loops: we get a broader notion of “there’s still stuff to do” (not tied to integer ranges). But we must ensure that “condition” stops holding, since there’s no explicit increment. condition repetend false true

3 Canonical while loops // Process b..c for (int k= b; k <= c; k= k+1) { Process k; } // Process b..c int k= b; while (k <= c) { Process k; k= k+1; } Scope note: since k happened to be declared "within" the loop, k can’t be used after the loop. /* process a sequence of inputs where you don't know how many need to be taken care of */ ; while ( ) { Process next piece of input; make ready for the next piece of input; } Here’s one way to use the while loop

4 Interesting while loops (showing why they can be hard to understand) /** open question in mathematics: is there an n such that this function never returns a value (i.e., n doesn't "return to 1")? Precondition: n >=1. */ public static boolean collatz(int n) { while (n != 1) { if (n%2 == 0) { n= n/2; } else { n= 3*n +1; } return true; } /** Von Neumann’s “fair coin” from unfair coin, assuming heads prob not 0 or 1. Encode heads/tails as true/false. = "output is heads". */ public static boolean fairFlip() { while (true) { // loop "forever"… boolean f1= new unfair flip; boolean f2= new unfair flip; if (f1 && !f2) { // HT return true; // escape the loop } else if (!f1 && f2) { // TH return false; }

5 How to analyze loops: understanding assertions about lists This is an assertion about v and k, thus explaining the meaning of these variables. It is true because v[0..3] are not ‘C’ and v[6..8] are ‘C’s X Y Z X A D C C C v v is (the name of) a list of Characters. (We aren't showing v as a variable to save space.) v not C's ? all C’s k k 8 v not C 's ? all C's k k 8 v not C's ? k 0 0 k 8 v not C's A D all C’s k 4 0 k 8 This falsely asserts that v[0..3] aren't C's, v[5..8] are ‘C’s. True assertion that v[0..-1] aren't C's (nothing in the empty list is a C) True assertion: v[0..3] are not C's, v[4] is A, v[5] is D, v[6..8] are C's.)

6 Counting characters. Store in n the number of '/'s in string s. 1. How does it start? ((how) does init. make inv true?) 2. When does it stop? (From the invariant and the falsity of loop condition, deduce that result holds.) 3. (How) does it make progress toward termination? 4. How does repetend keep invariant true? R: s n is # of '/'s here 0 s.length() // Store in n to truthify diagram R P: s n is # of '/'s here ? 0 k s.length() // inv: See diagram P, below k= 0; n= 0; while ( ) { } k!= s.length() k= k + 1; if (s.charAt(k)=='/') {n= n + 1;}

7 We add the postcondition and also show where the invariant must be true: initialization; // invariant: P while ( B ) { // { P and B} repetend // { P } } // { P and !B } // { Result R } The four loopy questions Suppose we are thinking of this while loop: initialization; while ( B ) { repetend } Second box helps us develop four loopy questions for developing or understanding a loop: 1. How does loop start? Initialization must truthify invariant P. 2. When does loop stop? At end, P and !B are true, and these must imply R. Find !B that satisfies P && !B => R. 3. Make progress toward termination? Put something in repetend to ensure this. 4. How to keep invariant true? Put something in repetend to ensure this.

8 Linear search. Character c is in String s. Find its first position. 1. How does it start? ((how) does init. make inv true?) 2. When does it stop? (From the invariant and the falsity of loop condition, deduce that result holds.) 3. (How) does it make progress toward termination? 4. How does repetend keep invariant true? R: s c not here c ? 0 k s.length() // Store in k to truthify diagram R Idea: Start at beginning of s, looking for c; stop when found. How to express as an invariant? P : s c not here ? 0 k s.length() // inv: See diagram P, below k= 0; while ( ) { } s.charAt(k) != c k= k + 1;

9 Appendix examples: Develop loop to store in x the sum of How should the loop start? Make range 1..k–1 empty: k= 1; x= 0; We’ll keep this definition of x and k true: x = sum of 1..k–1 2. When can loop stop? What condition lets us know that x has desired result? When k == How can repetend make progress toward termination? k= k+1; 4. How do we keep def of x and k true? x= x + k; Four loopy questions k= 1; x= 0; // invariant: x = sum of 1..(k–1) while ( k != 101) { x= x + k; k= k + 1; } // { x = sum of }

10 Roach infestation /** = number of weeks it takes roaches to fill the apartment --see p 244 of text*/ public static int roaches() { double roachVol=.001; // Space one roach takes double aptVol= 20*20*8; // Apartment volume double growthRate= 1.25; // Population growth rate per week int w= 0; // number of weeks int pop= 100; // roach population after w weeks // inv: pop = roach population after w weeks AND // before week w, volume of the roaches < aptVol while (aptVol > pop * roachVol ) { pop= (int) (pop * growthRate); w= w + 1; } return w; }

11 Iterative version of logarithmic algorithm to calculate b**c (we’ve seen a recursive version before). /** set z to b**c, given c ≥ 0 */ int x= b; int y= c; int z= 1; // invariant: z * x**y = b**c and 0 ≤ y ≤ c while (y != 0) { if (y % 2 == 0) { x= x * x; y= y/2; } else { z= z * x; y= y – 1; } } // { z = b**c }

12 Calculate quotient and remainder when dividing x by y x/y = q + r/y 21/4= 4 + 3/4 Property: x = q * y + r and 0 ≤ r < y /** Set q to quotient and r to remainder. Note: x >= 0 and y > 0 */ int q= 0; int r= x; // invariant: x = q * y + r and 0 ≤ r while (r >= y) { r= r – y; q= q + 1; } // { x = q * y + r and 0 ≤ r < y }