Other variations |
The interest example showed us incrementing on each loop, but we didn't start at 0 or 1.
Other variations are possible. We could count down instead of up:
for (int countdown = 10; countdown >= 1; countdown--) { System.out.println(countdown); } System.out.println ("Blast off!");
We could increment by a value other than 1. For example, we could have kept our interest rate as a double and then incremented by .01.
private double amount = startInvestment; // value of investment private static final double START_RATE = .02; // interest rates private static final double END_RATE = .12; private static final double RATE_INCREMENT = .01; private static final int YEARS = 10; // number of years for investment for (double rate = START_RATE; rate <= END_RATE; rate = rate + RATE_INCREMENT) { amount = startInvestment; for (int yearNum = 1; yearNum <= YEARS; yearNum++) { amount = amount + amount * rate; } System.out.println("At "+ (rate * 100) +"%, the amount is: "+amount); }
Warning: Note that you need to be very careful when testing for equality of floating point numbers. Due to roundoff errors, your numbers might not be what you expect.
Other variations |