Java Reference
In-Depth Information
227
Chapter 6 Iteration
C HAPTER G OALS
ȗ
To be able to program loops with the while , , and for statements
ȗ
To avoid infinite loops and off-by-one errors
ȗ
To understand nested loops
ȗ
To learn how to process input
ȗ
To implement simulations
T To learn about the debugger
This chapter presents the various iteration constructs of the Java language. These
constructs execute one or more statements repeatedly until a goal is reached. You
will see how the techniques that you learn in this chapter can be applied to the
processing of input data and the programming of simulations.
227
228
6.1 While Loops
In this chapter you will learn how to write programs that repeatedly execute one or
more statements. We will illustrate these concepts by looking at typical investment
situations. Consider a bank account with an initial balance of $10,000 that earns 5%
interest. The interest is computed at the end of every year on the current balance and
then deposited into the bank account. For example, after the first year, the account has
earned $500 (5% of $10,000) of interest. The interest gets added to the bank account.
Next year, the interest is $525 (5% of $10,500), and the balance is $11,025. Table 1
shows how the balance grows in the first five years.
How many years does it take for the balance to reach $20,000? Of course, it won't
take longer than 20 years, because at least $500 is added to the bank account each
year. But it will take less than 20 years, because interest is computed on increasingly
larger balances. To know the exact answer, we will write a program that repeatedly
adds interest until the balance is reached.
Search WWH ::




Custom Search