Java Reference
In-Depth Information
A for loop can be a bit tricky to read until you get used to it. The execution
of the code doesn't follow a “top to bottom, left to right” reading. The increment
code executes after the body of the loop even though it is in the header.
In this example, the initialization portion of the for loop header is used to
declare the variable count as well as to give it an initial value. We are not required
to declare a variable there, but it is common practice in situations where the vari-
able is not needed outside of the loop. Because count is declared in the for loop
header, it exists only inside the loop body and cannot be referenced elsewhere.
The loop control variable is set up, checked, and modified by the actions in the
loop header. It can be referenced inside the loop body, but it should not be modi-
fied except by the actions defined in the loop header.
VideoNote
Examples using for
loops.
For Statement
for
(
;
;
)
Statement
For Init
Expression
For Update
For Init
For Update
Local Variable Declaration
Statement Expression
,
Statement Expression
,
The for statement repeatedly executes the specified Statement as
long as the boolean Expression is true. The For Init portion of the
header is executed only once, before the loop begins. The For Update
portion executes after each execution of Statement.
Examples:
for ( int value=1; value < 25; value++)
System.out.println (value + " squared is " + value*value);
for ( int num=40; num > 0; num-=3)
sum = sum + num;
The increment portion of the for loop header, despite its name, could decre-
ment a value rather than increment it. For example, the following loop prints the
integer values from 100 down to 1:
for ( int num = 100; num > 0; num--)
System.out.println (num);
 
 
Search WWH ::




Custom Search