Java Reference
In-Depth Information
5.1 Introduction
A loop can be used to tell a program to execute statements repeatedly.
Key
Point
Suppose that you need to display a string (e.g., Welcome to Java! ) a hundred times. It
would be tedious to have to write the following statement a hundred times:
problem
System.out.println( "Welcome to Java!" );
System.out.println( "Welcome to Java!" );
...
System.out.println( "Welcome to Java!" );
100 times
So, how do you solve this problem?
Java provides a powerful construct called a loop that controls how many times an operation
or a sequence of operations is performed in succession. Using a loop statement, you simply
tell the computer to display a string a hundred times without having to code the print statement
a hundred times, as follows:
loop
int count = 0 ;
while (count < 100 ) {
System.out.println( "Welcome to Java!" );
count++;
}
The variable count is initially 0 . The loop checks whether count < 100 is true . If so, it
executes the loop body to display the message Welcome to Java! and increments count
by 1 . It repeatedly executes the loop body until count < 100 becomes false . When count
< 100 is false (i.e., when count reaches 100 ), the loop terminates and the next statement
after the loop statement is executed.
Loops are constructs that control repeated executions of a block of statements. The concept
of looping is fundamental to programming. Java provides three types of loop statements:
while loops, do - while loops, and for loops.
5.2 The while Loop
A while loop executes statements repeatedly while the condition is true.
Key
Point
The syntax for the while loop is:
while loop
while (loop-continuation-condition) {
// Loop body
Statement(s);
}
FigureĀ 5.1a shows the while -loop flowchart. The part of the loop that contains the state-
ments to be repeated is called the loop body. A one-time execution of a loop body is referred to
as an iteration ( or repetition) of the loop. Each loop contains a loop-continuation-condition, a
Boolean expression that controls the execution of the body. It is evaluated each time to deter-
mine if the loop body is executed. If its evaluation is true , the loop body is executed; if its
evaluation is false , the entire loop terminates and the program control turns to the statement
that follows the while loop.
The loop for displaying Welcome to Java! a hundred times introduced in the pre-
ceding section is an example of a while loop. Its flowchart is shown in FigureĀ  5.1b. The
loop body
iteration
loop-continuation-
condition
 
 
 
 
Search WWH ::




Custom Search