Java Reference
In-Depth Information
}
Let us use this loop to find out the size of our $10,000 investment if 5% interest is
compounded for 20 years. Of course, the balance will be larger than $20,000, because
at least $500 is added every year. You may be surprised to find out just how much
larger the balance is.
S YNTAX 6.2 The for Statement
for (initialization; condition; update)
statement
Example:
for (i = 1; i <= n; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Purpose:
To execute an initialization, then keep executing a statement and updating an
expression while a condition is true
237
238
In our loop, we let i go from 1 to n , the number of years for which we want to
compound interest.
You use a for loop when a variable runs from a starting to an ending value with a
constant increment or decrement.
for (int i = 1; i <= n; i++)
{
double interest = balance * rate / 100;
balance = balance + interest;
}
Figure 2 shows the corresponding flowchart.
The three slots in the for header can contain any three expressions. You can count
down instead of up:
Search WWH ::




Custom Search