# Loops

Source: https://cca.twango.dev/AP-Computer-Science/loops

# Loops

## For loop

Schematic syntax:

```text
for (initialization; condition; update) {
    body
}
```

> [!note] 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.

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

> [!warning] 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](https://docs.oracle.com/javase/specs/jls/se17/html/jls-6.html#jls-6.3).

## While loop

```text
while (condition) {
    body
}
```

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

## Do–while loop

```text
do {
    body
} while (condition);
```

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

Related: [[logic|Logic]] · [[arrays|Arrays]] · [[recursion|Recursion]]
