1.4.2 For Loops

Basic for loops are the same as Java:

for (variable initialization; boolean expression; increment)
{
    // Will execute if boolean is true, and until the boolean 
    // expression is false
}

The for loop initializes a value, then loops while the boolean expression is true. Each time through the loop, the loop variable takes on a new value.

The boolean expression gets evaluated after the loop variable is first initialized and then each cycle after the variable increments. Once inside the block of statements, the block will continue to execute even if the loop variable changes and the boolean expression is no longer true.

Additional Examples of For Loops

Many for loops are designed to start at zero and increment up by 1 each time. For loops are a lot more versatile than this though.

For loops can start, stop, and increment with any value. Here are a few other examples:

for (int i = 10; i >= 0; i--) // counts down from 10 to 0

for (int i = 2; i <= 100; i += 2) // counts by 2s from 2 to 100

for (int i = 1; i <= 256; i *= 2) // increments in multiples of 2

Try This Example

Last updated