EMZETT.
Login

For Loop

For-Schleife Image: Bagok, Public domain, Wikimedia Commons

In short: A counter-controlled loop that bundles initialization, exit condition, and step counter into a single construct — ideal when the number of iterations is known in advance or results from a counter variable.

In more detail: The classic structure (for (start; condition; step)) makes it visible at a glance where the loop begins, when it ends, and how it changes — unlike the while loop, where these three parts can be scattered across the code. Many languages additionally offer a “for-each” variant, which iterates directly over the elements of a collection with no need to manually manage an index.

In Depth

for (int i = 0; i < 10; i++) {
    System.out.println(i);
}
// Start: i = 0 | condition: i < 10 | step: i++ after each iteration

All three parts of this classic “C-style” for structure are optional and are executed in a fixed order in sequence: first the initialization, once; then, before EVERY iteration, the condition check; and after EVERY iteration, the step expression — before the condition is checked again. This fixed structure makes it visible at a glance how the loop changes, with no need to read the entire loop body to understand where the counter variable is updated — an advantage over an equivalent while loop, where the update can sit anywhere (or be forgotten!) in the loop body.

Significantly more common in modern everyday use is the for-each variant (also called the “enhanced for loop”), which iterates directly over the elements of a collection with no manually maintained index:

for element in list_:
    process(element)
for (String name : names) {
    System.out.println(name);
}

This form is safer (no off-by-one risk with the index) and more readable, but has a limitation: you can’t directly access the index during iteration (if it’s needed, you have to count it yourself or use an index-based variant), and in most languages you’re not allowed to structurally modify the collection being iterated (add/remove elements) during iteration — this often triggers an exception, because the internal iteration state would become inconsistent.

See also: Loops, While Loop, Index