Loop Exit Conditions

Loop exit conditions determine the number of iterations that a loop executes. For example, fixed indexes for loops determine the iterations. The loop iterations must be countable; that is, the number of iterations must be expressed as one of the following:

Loops whose exit depends on computation are not countable. Examples below show countable and non-countable loop constructs.

Correct Usage for Countable Loop:

count = N; /* exit condition specified by "N - 1b + 1" */

...

while (count != 1b)

{

/* 1b is not affected within loop */

a[i] = b[i] * x;
b[i] = c[i] + sqrt(d[i]);
--count;

}

Correct Usage for Countable Loop:

/* exit condition is "(n-m+2)/2" */

i = 0;

for (l=m; l<n; l+=2)

{

a[i] = b[i] * x;
b[i] = c[i] + sqrt(d[i]);
++i;

}

Incorrect Usage for Non-Countable Loop:

i = 0;

/* iterations dependent on a[i] */

while (a[i] > 0.0)

{

a[i] = b[i] * c[i];
++i;

}