Java Reference
In-Depth Information
At this point, sum contains the sum of the first two numbers. Let's repeat the statements
in Lines 2 and 3 a third time. After the statement in Line 2 executes (after the program-
ming code reads the next number):
num = 7
After the statement in Line 3 executes:
sum = sum + num = 8 + 7 = 15
Now, sum contains the sum of the first three numbers. If you repeat the statements in
Lines 2 and 3 two more times, sum will contain the sum of all five numbers.
If you want to add 10 integers, you can repeat the statements in Lines 2 and 3 ten
times. And if you want to add 100 numbers, you can repeat the statements 100 times.
In either case, you do not have to declare any additional variables as you did in the
code shown previously. By repeating the statements in Lines 2 and 3 you can add any
set of integers, whereas the earlier code requires that you drastically change the code.
There are many situations in which it is necessary to repeat a set of statements. For
example, for each student in a class, the formula to determine the course grade is the
same. Java has three repetition, or looping, structures that let you repeat statements over
and over until certain conditions are met: while , for , and do ... while . The following
sections discuss these three looping (repetition) structures.
5
while Looping (Repetition) Structure
In the previous section, you saw that sometimes it is necessary to repeat a set of statements
several times. One way to do this is to type the set of statements in the program over and
over. For example, if you want to repeat a set of statements 100 times, you type the set of
statements 100 times in the program. However, this way of repeating a set of statements is
impractical, if not impossible. Fortunately, there is a simpler approach. As noted earlier,
Java has three repetition, or looping, structures that allow you to repeat a set of statements
until certain conditions are met. This section discusses the first looping structure, a while
loop.
The general form of the while statement is:
while (logical expression)
statement
In Java, while is a reserved word. The logical expression is called a loop condition
or simply a condition. The statement is called the body of the loop. Moreover, the
statement can be either a simple or compound statement. Also, note that the parenth-
eses around the logical expression are part of the syntax. Figure 5-1 shows the flow
of execution of a while loop.
 
Search WWH ::




Custom Search