Java Reference
In-Depth Information
The statement in Line 8 stores the next number in the variable
number
. The statement in
Line 9 updates the value of
sum
by adding the value of
number
to the previous value. The
statement in Line 10 increments the value of
counter
by
1
. The statement in Line 11
outputs the sum of the numbers. The statements in Lines 12 through 15 output either the
average or the text:
Line 15: No input
.
Note that in this program, in Line 4,
sum
is initialized to
0
. In Line 9, after storing the
next number in
number
in Line 8, the program adds the next number to the sum of all
the numbers scanned before the current number. The first number read is added to zero
(because
sum
is initialized to
0
), giving the correct sum of the first number. To find the
average, divide
sum
by
counter
.If
counter
is
0
, then dividing by
0
terminates the
program and you get an error message. Therefore, before dividing
sum
by
counter
, you
must check whether or not
counter
is
0
.
Notice that in this program, the statement in Line 5 initializes the LCV
counter
to
0
.
The expression
counter < limit
in Line 7 evaluates whether
counter
is less than
limit
. The statement in Line 8 updates the value of
counter
. Note that in this program,
the
while
loop can also be written without using the variable
number
as follows:
while
(counter < limit)
{
5
sum = sum + console.nextInt();
counter++;
}
You might not know exactly how many times a set of statements needs to be executed,
but you do know that the statements need to be executed until a special value is met. This
special value is called a sentinel. For example, while processing data, you might not
know how many pieces of data (or entries) need to be read, but you do know that the last
entry is a special value. In such cases, you read the first item before entering the
while
statement. If this item does not equal the sentinel, the body of the
while
statement
executes. The
while
loop continues to execute as long as the program has not read the
sentinel. Such a
while
loop is called a sentinel-controlled
while
loop. In this case, a
while
loop might look like the following:
input the first data item into variable
//initialize the
//loop control variable
while
(variable != sentinel)
//test the loop control variable
{
.
.
.
input a data item into variable
//update the loop
//control variable
}
Search WWH ::
Custom Search