

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Gries; Class: Introduction to Computing Using Java; Subject: Computer Science; University: Cornell University; Term: Spring 2009;
Typology: Study notes
1 / 2
This page cannot be seen from the preview
Don't miss anything!


1
2
while (< condition >) { sequence of declarations and statements } < condition >: a boolean expression. < repetend >: sequence of statements.
condition repetend false true 3 Canonical while loops // simulate for ( int k= b; k <= c; k= k+1) int k= b; while (k <= c) { Process k; k= k+1; } // process a sequence of input not of fixed size
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 }
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 inv 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
This is an assertion about v and k. It is true because chars of v[0..3] are greater than ‘C’ and chars of v[6..8] are ‘Z’s.
v X Y Z X A C Z Z Z This is a list of Characters v ≥ C? all Z’s k 6 0 3 k 8 v ≥ C? all Z’s k 5 0 3 k 8 v ≥ C all Z’s k 6 0 k 8 v ≥ W A C all Z’s k 4 0 k 8
9 Appendix examples: Develop loop to store in x the sum of 1..100.
1. How should the loop start? Make range 1..k–1 empty: k= 1; x= 0;
2. When can loop stop? What condition lets us know that x has desired result? When **k == 101
/** = 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= 20208; // 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 bc (we’ve seen a recursive version before). /* set z to bc, given c ≥ 0 / int x= b; int y= c; int z= 1; // invariant: z * xy = bc 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