24su ver.
Note: this is for the Summer 2024 iteration of CSE 121. Looking for a different quarter? Please visit https://courses.cs.washington.edu/courses/cse121/.
The For Loop¶
(repeats a group of statements a fixed number of times)
for (initialization; test; update) {
statement;
...
statement;
}
Example
for (int i = 1; i <= 10; i++) {
System.out.println(i + " squared is " + (i * i));
}
For Loop Control Flow Diagram¶
![Flow chart of for loop control with 5 steps explained below](../images/for-loop-diagram.png)
- (Step 1) First, perform the initialization once at the beginning.
- (Step 2) Then test: is the test true?
- (Step 3) If the test is true, execute the statements inside the for loop body.
- (Step 4) Perform the update and go back to Step 2.
- (Step 5) If the test is not true, execute the statements that are immediately after the for loop body.
Ways to Increment and Decrement the Update Variable¶
Statement | Description |
---|---|
i++ | increment i by 1; same as i = i + 1 |
i += 1 | increment i by 1; same as i = i + 1 |
i-- | decrement i by 1; same as i = i - 1 |
i -= 1 | decrement i by 1; same as i = i - 1 |