Java Reference
In-Depth Information
Chapter 10
Controlling Program Flow
Repetition in Programs
Often computer programs must repeat the same task a number of times.
Think of a payroll program that estimates wages and deductions by per-
forming the same calculations for each employee in the company. If you
were developing such a program, you could write code to perform salary
calculations for each employee. If the company had 100 employees, you
would end up with 100 different routines. Although this solution would
work, it is cumbersome and awkward. A more reasonable approach is to
writeasingleroutinethatperformsthenecessarycalculations.Theroutine
is executed for each employee by changing the data set. The result is more
compact code that is much easier to develop and test.
Program repetitions usually take place by means of programming con-
structs called loops . In this chapter, we discuss the three Java loop con-
structs: the for loop , the while loop , and the do-while loop .
Loops and iterations
Loops do not offer functionality that is not otherwise available in a pro-
gramming language. Loops just save coding effort and make programs
morelogicalandefficient.Inmanycasescodingwouldbevirtuallyimpossi-
ble without loops. Imagine that you were developing a program that had to
estimate the taxliability for each resident of the state of Minnesota. With -
out loops, you would have to spend the rest of your life writing the code.
In talking about loops it is convenient to have a word that represents
one entire trip through the processing routine. We call this an iteration .
To iterate means to do something repeatedly. Each transition through the
statement or group of statements in the loop is an iteration. Thus, when
Search WWH ::




Custom Search