for loops

Note: This page describes the "traditional" for loop; 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) {

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:

while (condition) {

There is nothing unusual about the condition or the statements.

The initialization may have one of the following forms:

The update is one of:

The 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++) {

Two additional statement types, break and continue, can also control the behavior of for loops.


The break and continue statements can be used with statement labels.