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:

• A constant

• A loop invariant term

• A linear function of outermost loop indices

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

Correct Usage for Countable Loop, Example 1:

SUBROUTINE FOO (A, B, C, N, LB)
DIMENSION A(N),B(N),C(N)
INTEGER N, LB, I, COUNT
! Number of iterations is "N - LB + 1"
COUNT = N
DO WHILE (COUNT .GE. LB)
A(I) = B(I) * C(I)
COUNT = COUNT - 1
I = I + 1
ENDDO  ! LB is not defined within loop
RETURN
END

Correct Usage for Countable Loop, Example 2:

! Number of iterations is (N-M+2) /2
SUBROUTINE FOO (A, B, C, M, N, LB)
DIMENSION A(N),B(N),C(N)
INTEGER I, L, M, N
I = 1;
DO L = M,N,2
A(I) = B(I) * C(I)
I = I + 1
ENDDO
RETURN
END

Example of Incorrect Usage for Non-Countable Loop:

! Number of iterations is dependent on A(I)
SUBROUTINE FOO (A, B, C)
DIMENSION A(100),B(100),C(100)
INTEGER I
I = 1
DO WHILE (A(I) .GT. 0.0)
A(I) = B(I) * C(I)
I = I + 1
ENDDO
RETURN
END