# Lecture 11 (Tychonievich) - Loops

Lecture Date: Friday 6 February

`while (X) { Y; }` means `if (X) { Y; if (X) { Y; if (X) { Y; if (X) { ...`: it repeats action `Y` as long as `X` is `true`.

`for(X; Y; Z) { W; }` is shorthand for `{ X; while (Y) { W; Z; } }`. The first part sets up the loop; the second part is the guard or condition under which we repeat; the third is an update that happens at the end of each repetition: `for(setup; guard; update) { action; }`.

The most common use of a `for` loop is to repeat something a known number of times, almost always written as `for (int i = 0; i < n; i += 1) { ... }` where `n` is the number of times to repeat the action and `i` is the index or counter variable. It is in your interest to be able to write that `for`-loop automatically; I suggest writing it out by hand on paper a dozen times to help train your mind to produce it easily.

An aside: the following all increase `x` by one:

• `x = x + 1`
• `x += 1`
• `++x`
• `x++`

We usually use `while` loops when we cannot predict how many times we’ll need to repeat something. Two common examples:

You might also find a loop visualizer that I started writing few years ago helpful.

Code:

Audio: