CCA Guide
Loops

Loops

Curated by Last modified: 2 min read

View Markdown

For loop

Schematic syntax:

for (initialization; condition; update) {
    body
}

Syntax correction

The three parts are separated by semicolons, rather than the commas in the original example.

Evaluation procedure

  1. Run the initialization once.
  2. Evaluate the condition. If false, stop.
  3. Execute the body.
  4. Execute the update.
  5. Repeat from step 2.

break exits the nearest enclosing loop or switch immediately.

Scope

Variables declared inside the body are local to that block. A variable declared outside can be assigned inside; that assignment affects the same variable.

int total = 0;
for (int i = 0; i < 3; i++) {
    total += i;
}
System.out.println(total); // 3
// i is out of scope here.

Correction to the original notes

The original claim that assignments in a child scope do not affect an outer variable was incorrect. Scope determines where a name is accessible; it does not create a copy of every outer variable.

Source: Java Language Specification §6.3.

While loop

while (condition) {
    body
}

Evaluate the condition before each iteration. If true, execute the body; otherwise stop.

Do–while loop

do {
    body
} while (condition);

Execute the body first, then check the condition. The body runs at least once.

Related: Logic · Arrays · Recursion

Linked to this page