Loop exit conditions determine the number of iterations a loop executes. For example, fixed indexes for loops determine the iterations. The loop iterations must be countable; in other words, the number of iterations must be expressed as one of the following:
A constant
A loop invariant term
A linear function of outermost loop indices
In the case where a loops exit depends on computation, the loops are not countable. The examples below show loop constructs that are countable and non-countable.
Example: Countable Loop |
---|
void cnt1(float a[], float b[], float c[], int n, int lb) { // Exit condition specified by "N-1b+1" int cnt=n, i=0; while (cnt >= lb) { // lb is not affected within loop. a[i] = b[i] * c[i]; cnt--; i++; } } |
The following example demonstrates a different countable loop construct.
Example: Countable Loop |
---|
void cnt2(float a[], float b[], float c[], int m, int n) { // Number of iterations is "(n-m+2)/2". int i=0, l; for (l=m; l<n; l+=2) { a[i] = b[i] * c[i]; i++; } } |
The following examples demonstrates a loop construct that is non-countable due to dependency loop variant count value.
Example: Non-Countable Loop |
---|
void no_cnt(float a[], float b[], float c[]) { int i=0; // Iterations dependent on a[i]. while (a[i]>0.0) { a[i] = b[i] * c[i]; i++; } } |