Java Reference
In-Depth Information
parameter counter to zero (0), as arrays are numbered beginning with zero. As the
start value is incremented or decremented at each pass of the loop, the updated
value is stored. The start value typically is declared inside the for statement.
The second parameter determines how many times the loop executes. The
parameter must be a condition that results in a boolean value. Typically, the
condition tests the value of the counter using a conditional operator. While the
value is true, the loop keeps executing; if the condition is false, the loop stops
executing. For example, if you were looping to manipulate each element of the
array, the loop should continue only while you still have array elements. If the
length of the array is 9 (elements numbering 0 through 8), the second parameter
in the for statement would compare the counter variable to less than 9 as in the
following code:
for (int counter=0; counter<9; counter++)
The for Statement
Many times students confuse the second parameter of the for
statement with a do-until concept. It is better to think of it as a
do while. The second parameter notifies the loop to keep per-
forming while a certain condition is true. For example, a loop that
prints paychecks for 100 employees might contain a loop condi-
tion of number<101 or number<=100. Assuming the loop began
with 1 and was incremented by 1 each time, either condition
would cause the loop to execute 100 times.
The third parameter manipulates the counter-control value. While a for loop
often increments or decrements the counter-control value by one, a for loop can
increment or decrement by any integer value other than one, an example of
which is shown in example 3 of Table 5-7 on the previous page. For example, if
you wanted to increment the start value by five, you might use the add and
assign operator to add five to the start value at each pass of the loop, as in the
following code:
for (int counter=5; counter<=100; counter+=5)
An assignment or unary operator typically is used to increment or decre-
ment the counter-control value. The next section discusses both assignment and
unary operators in detail.
Assignment and Unary Operators
Recall that to accumulate a running total, you declare a variable, give that
variable a beginning value, and then add to it by including the identifier name
on both sides of an assignment operator. For example, the following code:
variable = variable + newValue;
is an assignment statement that is evaluated from right to left. Therefore, in the
above example, every time the line is executed, the old value of variable is added
to newValue and then reassigned to the original identifier name.
Search WWH ::




Custom Search