Simplest Case

A loop is a way of executing some code repeatedly. There are two main categories of loops:

For the latter case, we generally have:

  1. Some initialization that has to be done before the loop starts. (Once only.)
  2. A condition to check: should we go/stay in the loop (true), or should we leave (false)?
  3. The code that we want to do repeatedly.
  4. Some step to take that gets us closer to stopping. (Then go back to Step 2 and check condition.)
  5. Syntax:
    for ( <init> ; <boolean-expression> ; <step> )
        <the statement(s) to repeat>

    For example, we might want to test a talking robot by having it repeatedly say random phrases — 20 times, for example.

        for ( int i = 0; i < 20; i++ )
            // Code that produces a timestamp goes here.
            // Code that produces a random phrase goes here.

Alyce Brady, Kalamazoo College