while Loops
| Executes a block of code repeatedly | |
| while(Condition) { Statement 1; Statement 2; ... } Next Statement;
|
![]() |
| A condition controls how often the loop is executed | |
Calculating the Growth of an Investment
| Invest $10,000, 5% interest, compounded annually | ||
|
Year |
Balance |
When has the
bank account reached a particular balance? while (balance < targetBalance)
{
years++;
double interest = balance * rate / 100;
balance = balance + interest;
}
|
|
0 |
$10,000 |
|
|
1 |
$10,500 |
|
|
2 |
$11,025 |
|
|
3 |
$11,576.25 |
|
|
4 |
$12,155.06 |
|
|
5 |
$12,762.82 |
|
Click here to see the program.
Click here for accumulation of numbers
Errors:
1. Loops run forever - Infinite Loops
2. Off-by-One Errors