|
| BASIC |
Note: This page describes the "traditional" forloop; there is also an enhanced for loop.
A for loop is a kind of loop, which is a kind of control statement. It is a loop with the test at the top. The syntax is:
for (initialization; condition; update) { statements }
The initialization is performed first, and only once. After
that, the condition is tested and, if true, the statements
are executed and the update is performed; then control returns
to the condition. In other words, the for loop behaves almost
exactly like the following while loop:
initialization; while (condition) { statements; update; }
There is nothing unusual about the condition or the statements.
The initialization may have one of the following forms:
i = 0; int i = 0; --for
statement, and the variable cannot be used outside the loop.int i = 0, j = 0; (this
form is rarely used).The update is one of:
i++ or something similar.i++, j += 2The braces indicate a block of statements. If there is only one statement, the braces may be omitted; however, it is good style to always include the braces.
For example, the contents of an array a can be written out on
a single line by:
for (int i = 0; i < a.size(); i++) { System.out.print(a[i]); } System.out.println();
| INTERMEDIATE |
Two additional statement types, break
and continue, can also control the
behavior of for loops.
| ADVANCED |
The break and continue statements can be used with statement labels.