Choosing a Loop Terminating Condition

The terminating condition of a loop is the opposite of the test condition that allows the loop to continue looping. The terminating condition is the condition that stops the looping.

Be extremely careful when choosing terminating conditions. If the condition is too "exact", requiring a particular value to stop the loop, the loop counter may never satisfy the exact condition, and the loop may not terminate.

Note the differences between the following loops. The loop test conditions are the same in all cases: i != 10. Thus, the loop terminating conditions are the same in all cases: i == 10. Only the amount of the loop increment differs in each of the examples below:

int i, increment;

i = 0;
increment = 1;

while ( i != 10 )
{
   printf("i is %d\n", i);
   i = i + increment;
}
printf("i finishes at %d\n", i);
int i, increment;

i = 0;
increment = 2;

while ( i != 10 )
{
   printf("i is %d\n", i);
   i = i + increment;
}
printf("i finishes at %d\n", i);
int i, increment;

i = 0;
increment = 3;

while ( i != 10 )
{
   printf("i is %d\n", i);
   i = i + increment;
}
printf("i finishes at %d\n", i);
int i, increment;

i = 0;
increment = 4;

while ( i != 10 )
{
   printf("i is %d\n", i);
   i = i + increment;
}
printf("i finishes at %d\n", i);

What is the output of each block of code? Which of the loops never terminate because the loop terminating condition is never met?

Because of the choice of such an "exact" terminating condition, a small change to the loop can cause the code to malfunction by making the loop counter miss the terminating condition. This is bad programming style.

What happens in each case if the loop test condition is changed to be i <= 10 instead of i != 10?

This change makes the terminating condition far less exact; it becomes i > 10, and all the loops terminate.

Using an "exact" terminating condition is a worse problem when dealing with floating-point numbers. Since floating-point numbers are approximations, a test for exact equality will often be wrong. Never test floating-point numbers for exact equality, especially in loops.


Last revised: Sunday September 27, 1998 01:06.
Email comments to Ian! D. Allen
idallen@freenet.carleton.ca