Knitting a scarf: another example of nested For loopsTopCounting and For loopsCalculating Interest Example

Calculating Interest Example

Let's see another example of a for loop. Suppose that we wanted to determine how much money we would have if we invested it for 10 years, gaining 5% interest each year (compounded annually). Suppose amount represents the amount of money we have invested. After one year, we would have:

    amount + amount * 5/100.0;

How would we use a for loop to repeat this computation 10 times?

    private double amount = startInvestment;  // value of investment
    private static final int RATE = 5;   // interest rate as percent
    private static final int YEARS = 10;      // number of years for investment
    
    for (int yearNum = 1; yearNum <= YEARS; yearNum++) {
        amount = amount + amount * RATE/100.0;
    }

A more general program uses nested for loops to calculate the amount for a range of interest rates:

    private double amount = startInvestment;  // value of investment

    private static final int START_RATE = 2;   // interest rates
    private static final int END_RATE = 12;

    private static final int YEARS = 10;      // number of years for investment

    for (int rate = START_RATE; rate <= END_RATE; rate++) {
        amount = startInvestment;
        for (int yearNum = 1; yearNum <= YEARS; yearNum++) {
            amount = amount + amount * rate/100.0;
        }
        System.out.println("At "+rate+"%, the amount is: "+amount);
    }

Below is a demo and the full code for the program:

Demo: Interest rates


Knitting a scarf: another example of nested For loopsTopCounting and For loopsCalculating Interest Example