Loop Exit Conditions

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:

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

subroutine cnt1 (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

end

The following example demonstrates a different countable loop construct.

Example: Countable Loop

! Number of iterations is (n-m+2)/2

subroutine cnt2 (a, b, c, m, n)

  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

end

The following examples demonstrates a loop construct that is non-countable due to dependency loop variant count value.

Example: 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

end