Lesson 18: for loop
When you know how many times to repeat, for is handy: it packs three things on one line — for (int i = 0; i < n; i++). Part 1: start (int i = 0). Part 2: keep-going test (i < n). Part 3: step after each round (i++). The three parts are separated by semicolons.
for is a tidy while: the start, the test, and the step are written together at the top of the loop, so it's hard to forget to advance the counter.
- for (init; cond; step)
- A loop that packs start, condition and step on one line.
- init
- The first part: creates and initializes the counter, e.g. int i = 0.
- step
- The third part: runs after each round, e.g. i++.
- ; separators
- The three for parts are separated by two semicolons.