Loop Tutorial Exercise Solution =============================== What do we want? We want to know how many weeks it will take to fill (or overfill) the apartment with roaches given that: - there are 100 of them at the start of the first week - they are all .001 cu. ft. in volume - the apartment is 100 cu. ft. in volume - the roach population grows 125%/week How do we start? 1. Consider the initial value of the roach volume at the start of the first week: double roachVolume = 100.0 * .001; 2. Set up a counter to keep track of the number of elapsed weeks: int weeks = 0; How are the variables related? Well, as week increases, so does roachVolume in the following way: roachVolume at week k+1 = roachVolume at week k times 2.25 Let's introduce some constants: final double APT_VOLUME = 100.; final double GROWTH_RATE = 2.25; When are we done? We're done when roachVolume is greater than (or equal to) APT_VOLUME. It seems unlikely that the volume of the roaches will exactly equal the volume of the apartment since we are looking at it only at weekly intervals, but it is possible. How do we do one step? roachVolume = roachVolume * GROWTH_RATE; weeks = weeks + 1; Here is the loop: while (roachVolume < APT_VOLUME){ roachVolume = roachVolume * GROWTH_RATE; weeks = weeks + 1; } ADDITIONAL EXCERCISES int k = Integer.parseInt(br.readLine()); int = 4; while (k*i != 12){ k--; } // this loop terminates for k >= 3 TESTING i j result ============================================ FL 123 3FL FL 1234 3FL FxL 123 3FL FxL 1234 3FL FxxL 123 3FL // for a string i of length 2 or more // and a string j of length 3 or more // Return the third character in j plus the first and // last characters in i. _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp