Java Reference
In-Depth Information
Chapter 11
Programming with Loops
Java Loop Constructs
Most programs contain many loops of different types. The programmer
needs to be familiar with all types of loops and be able to select the most
suitable one in each case. In this Chapter, you learn how to use the three
loop constructs (for loop, while loop, and do-while loop) in practical pro-
gramming situations.
Selecting a Loop Construct
The for loop is a neat mechanism that contains the three required elements:
initialization, test, and processing. This design makes the for loop suitable
in situations in which you know the loop conditions in advance. For exam-
ple, a routine to display the ASCII characters in the range 16 to 128 can be
easily coded using a for loop, as follows:
for(char ascii = 16; ascii < 129; ascii ++)
System.out.println(ascii);
Programmers note:
In the preceding code fragment, the loop variable ascii is declared in-
side the for statement. The result is that ascii is a local variable whose
scope is limited to the loop itself.
In contrast, the while loop repeats while a certain test condition is
true. This makes the while loop useful in cases in which the terminating
condition is initially unpredictable. For example, you may want a pro-
gram to repeat a set of calculations until the user types a specific ending
Search WWH ::




Custom Search