ENGR 131: While in Action

Repeat N times

Count Down from 10

     int i = 10;
     while (i != 0) {
       System.out.print(i+" ... ");
       i = i - 1;
     } 

     System.out.println("Liftoff!");

Roll Die 13 times

     int roll, numberOfRolls;

     numberOfRolls = 0;

     while (numberOfRolls < 13) {
       roll = (int) (Math.random()*6)+1;
       System.out.print(roll+" ");
       numberOfRolls = numberOfRolls + 1;
     }

     System.out.println();

Repeat until found

Roll Die Until You Get a 5

     int numberOfRolls, roll;

     roll = (int) (Math.random()*6)+1;
     System.out.print(roll);
     numberOfRolls = 1;

     while (roll != 5) {
       roll = (int) (Math.random()*6)+1;
       System.out.print(roll);
       numberOfRolls = numberOfRolls + 1;
     }

     System.out.println("\nIt took " + numberOfRolls + " rolls");

Repeat until threshold

How long to a billion?

Assumes: currentSavings ($) and interestRate (5) will be given before iteration starts
     int years;
     double principal, multiplier, currentSavings, interestRate;

     years = 0;
     principal = currentSavings;
     multiplier = 1.0 + interestRate/100.0;

     while (principal < 1E9) {
       principal = principal * multiplier;
       years = years + 1;
     }

     System.out.println("It will take " + years + " years");

Pharmokinetics of Ibuprofen OR How may hours until 1 mg?

Reference: http://www.rxlist.com/cgi/generic/ibup_cp.htm

Assumes: initial dose is given before iteration starts

     double dose, serumAmount, hours;

     // peak level is up to 80% of dose after 1-2 hours
     serumAmount = 0.8*dose;
     hours = 1.5;

     // half-life is 1.8 to 2 hrs
     while (serumAmount>1.0) {
       serumAmount = 0.5*serumAmount;
       hours = hours + 1.9;
     } 

     System.out.println("It will take " + hours + " hours");

Repeat until convergence

Newton iteration for the square root function

Reference: http://en.wikipedia.org/wiki/N-th_root_algorithm

Assumes: A is given before iteration starts


   double guess, A;

   guess = 1.0;

   while (Math.abs(guess-A/guess)>1E-6) {
     guess = 0.5*(guess + A/guess);
   } 

   System.out.println("Answer (to sixth decimal place): " + guess);


Created: 2007-09-13. Last Modified: 2007-09-17. © Michael S. Branicky