for

Summary

The for loop is used for iteration and allows statements to be executed repeatedly. A for loop is a loop that can be used with a counter variable.

Syntax

for ([initialization]; [condition]; [update])
    statement

Parameters

initialization
A variable declaration or valid expression. Typically initializes a counter variable with a variable declaration. If variables are declared here, they are scoped to the loop.
condition
A valid expression that must be true for the for loop's statement to be executed. When present, the condition usually checks the value of the counter variable.
update
Typically an increment or decrement expression on the counter variable but can be any valid expression.
statement
The statement to execute. In order to execute a group of statements, use a block.

Description

A for loop is distinguished from other loops primarily by its ability to use and declare a counter variable. The body (or statement) of the for loop is executed repeatedly until its condition evaluates to false.

Variables declared in the initialization part of the for loop are scoped to the for loop. For more information on scoping, see the scoping documentation.

By convention, the counter variable in a for loop is typically named i, j, or k. Consult the naming conventions page for more information.

Basic for Loop

1
2
3
for (int i = 0; i < 5; ++i) {
    int x = i * 2;
}

The same for loop can be expressed as a while loop:

1
2
3
4
5
int i = 0;
while (i < 5) {
    int x = i * 2;
    i++;
}

Essentially, a for loop is similar to a while loop but provides a convenient way to declare and utilize a counter variable. Counters are commonly needed when looping.

Note that the for loop and while loop examples are not exactly identical due to scoping. The for loop's counter variable is scoped to the for loop itself whereas the while loop's counter variable is scoped to the containing block or file. For more information on scoping, see the documentation on scopes.

Steps of the for Loop

  1. The for loop begins with its initialization component. This is typically used for declaring a counter variable and always happens first.

  2. After initialization, the for loop checks its condition. If the condition expression evaluates to true, the for loop will move to the next step; otherwise, the for loop will end.

  3. The statement(s) of the for loop's body are executed.

  4. The for loop's update component is executed. This is typically an increment or decrement operation on the counter variable.

  5. The loop begins repeating from step 2 until the condition evaluates to false.

Terminating for Loops

A for loop can be terminated prematurely using the break keyword.

For instance, in the following code, we loop from 0 to 5, but we terminate the loop at 3:

1
2
3
4
5
6
7
8
9
10
import System;
 
for (int i = 0; i <= 5; ++i) {
    Console.log(i);
     
    // Terminate the loop prematurely when 'i' equals 3
    if (i == 3) {
        break;
    }
}

If you have nested for loops and wish to terminate a specific loop, use labeled statements.

Skipping Loop Iterations

You can skip certain loop iterations and move to the next iteration using the continue keyword. When the continue statement is encountered, the for loop will exit its current iteration, run its update expression, check its condition, and, if the condition still evaluates to true after the update expression, the next loop iteration will begin from the first statement of the for loop's body.

For instance, in the following code, we loop from 0 to 5, but we skip 3:

1
2
3
4
5
6
7
8
9
10
import System;
 
for (int i = 0; i <= 5; ++i) {
    // Skip to next loop iteration when 'i' equals 3
    if (i == 3) {
        continue;
    }
     
    Console.log(i);
}

If you have nested for loops and wish to skip an iteration for a specific loop, use labeled statements.

Optional for Loop Components

All of the parameters of the for loop's syntax are optional with exception of the statement. However, if you essentially wish to effectively have no statement, use the empty statement. The initialization, condition, and update components are optional.

For example, if we want to declare a counter variable for the for loop that is not scoped to the for loop but its containing block or file, we can declare the counter variable outside the for loop and omit the for loop's initialization:

1
2
3
4
int i = 0;
for (; i < 5; ++i) {
    // ...
}

Be careful when omitting the condition as it could result in an infinite loop. When the condition is omitted, at least one break statement should be provided; otherwise, the compiler will raise a warning.Unimplemented

1
2
3
4
5
6
for (int i = 0; ; ++i) {
    // Exit the loop if 'i' is greater than 5
    if (i > 5) {
        break;
    }
}

We can also omit the update component. Here's an example where we moved the update expression to the body of the for loop:

1
2
3
for (int i = 0; i < 5; ) {
    ++i;
}

Finally, it is possible to omit all of the aforementioned components of the for loop:

1
2
3
4
for (;;) {
    // Exit the loop immediately to avoid an infinite loop
    break;
}

When all parts are omitted as illustrated above, the condition is also missing. As always, when the condition is missing, at least one break statement is expected in order to avoid infinitely looping.

Examples

Scoping for Loop Counter Variable to Containing Block Rather than for Loop Itself
1
2
3
4
5
int i = 0; // Declare the counter variable outside of the 'for' loop
for (; i < 5; ++i) {
    int x = 2;
    int y = x * 2;
}

See Also

Share

HTML | BBCode | Direct Link