12C. Standards for Loops

Only one loop per function

The standards require that a single function cannot contain more than one loop. But a function can call other functions that contain loops. If you seem to need more than one loop, move at least one of the loops into a separate function.

Code that is done at the end of the loop should be written after the loop.

The standards require that code that is done when a loop is finished should be written after the loop, not in the loop body. That seems to be common sense, but beginners frequently violate that rule. See an example of what to avoid.

Do not simulate nested loops

Beginners often create a complicated loop that is really simulating more than one loop. See here

Do not change the value of a for-loop control variable in the loop body

The intent of a for-loop is that one control variable is managed in the loop heading. For example,
  for(int k = 0; k < n; k++)
  {
    …
  }
shows that k steps from 0 up to n−1.

Do not change the value of k (or whatever the control variable is called) in the loop body. If you do, then you make a lie out of what the loop heading suggests. See the link for an example.


Do not engage in other sneaky ways to make a lie out of a for-loop heading

Don't make a lie out of the loop heading in other ways. For example,
  for(i = 1; i < n; i++) 
  {
    ...
    if(condition)
    {
      n = 0;
    }
    ...
  }
is not a good way to cause the loop to end. If you want to exit a for-loop, use break or return.