For loops
Format:
[sourcecode language=”java” toolbar=”false”]
for (initialization; termination; increment) {
statement(s)
}
[/sourcecode]
- initialization : initializes the loop; executes once at the beginning.
- when termination expression evaluates to false, the loop terminates.
- increment : is invoked after each iteration through the loop.
The order of execution:
- the variable is initialized then
- it is checked to see if the expression is true,
- if true the statements are executed,
- then the variable is incremented,
- then expression is tested,
- if true the statements are executed…
[initialized, tested, executed, incremented, tested, executed, incremented…]
[sourcecode language=”java” toolbar=”false”]
for(int x=0; x<5; x++)
for(int x=0; x<5; ++x)
[/sourcecode]
0 to 4, using a post- or pre-increment does not affect the number of loops.
[sourcecode language=”java” toolbar=”false”]
for(int x=0; x<=5; x++)
[/sourcecode]
0 to 5, using = includes the number.
[sourcecode language=”java” toolbar=”false”]
for(int x=5; x>0; x–)
[/sourcecode]
5 to 1, using < or > excludes the number.
Invalid
[sourcecode language=”java” toolbar=”false”]
for(int x = 0, int z = 0 ; x < 10; x++){}
[/sourcecode]
Cannot declare a second variable inside a for loop initialisation.
Correct
[sourcecode language=”java” toolbar=”false”]
for(int x = 0, z = 0 ; x < 10; x++){}
[/sourcecode]
But you can initialise another variable.
Leave a Reply