Iteration Recipes

Recipes for iterating over, looping through, and repeating stuff:

  1. Repeat Code a Specific Number of Times: I want to repeatedly execute a chunk of code, counting the repetitions.

  2. Repeat While or Until Something Is True: I want to repeatedly execute a chunk of code while or until some condition is true, however many times that may be.

  3. Stop Iteration Early: Sometimes my code needs to stop iterating before a loop has reached its normal end (of the range in for, boolean termination condition in while).

  4. Flip a Coin or Roll a Die: My code needs to randomly pick or decide something.

  5. Determine Statistics of a Sequence: I want to determine some simple statistical measures (like frequency, mean, and standard deviation) of a set of measurements, events, or data, and I don't want to store all of the individual values in memory.