go to previous page   go to home page   go to next page hear noise

Answer:

The complete program is below.


Complete Program

Here is the complete program. Notice how the pieces fit together. The counting loop is nested in the body of the result-controlled loop.

class  MillionDollarInterestRate
{

  public static void main( String[] args ) 
  {
    double initialAmount = 1000.00 ;
    double dollars = 0.0;
    double rate = -0.001 ;
 
    while ( dollars < 1000000 )
    {
       // change to the next rate
       rate = rate + 0.001;

       // compute the dollars after 40 years at the current rate
       int year =  1 ;     
       dollars = initialAmount;     
       while (  year <= 40 )
       {     
         dollars = dollars + dollars*rate  ; // add another year's interest     
         dollars = dollars + 1000 ;          // add in this year's contribution
         year    =  year + 1 ;
       }

    }

    System.out.println("After 40 years at " + rate*100 
      + " percent interest you will have " + dollars + " dollars" );
  }

}

Here is a run of the program:

Run of the program

Notice that this program has some floating point accuracy problems. In practice, financial programs are very carefully written and use floating point with extreme caution. Programming languages intended for business have special data formats for money that ensure that none of it gets lost.


QUESTION 11:

Why is this statement from the program important:


dollars = initialAmount;