Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Control Flow

exit, cycle and Named Constructs

Control loops precisely in Fortran: exit and cycle, naming constructs to leave outer loops, the block construct, stop and error stop, and an introduction to do concurrent.

Sometimes you need to leave a loop early, skip one pass, or break out of two nested loops at once. Fortran gives you exit and cycle, plus construct names that say exactly which loop (or if, or select case) the statement applies to. Together they replace the old goto jumps that made vintage code hard to follow.

exit: leave the loop

exit ends the innermost do loop and continues after its end do:

FORTRAN
program first_negative
  implicit none
  real :: a(6) = [3.0, 1.5, 4.0, -2.0, 7.0, -1.0]
  integer :: i, pos

  pos = 0
  do i = 1, size(a)
    if (a(i) < 0.0) then
      pos = i
      exit
    end if
  end do
  print *, "First negative at index", pos
end program first_negative

This prints position 4 (the value -2.0). If none is negative, pos stays 0, a common "not found" convention.

cycle: skip to the next pass

cycle abandons the rest of the current iteration and starts the next one. The loop variable is still incremented:

FORTRAN
do i = 1, 10
  if (mod(i, 2) == 0) cycle      ! skip even numbers
  print *, i                     ! prints 1 3 5 7 9
end do

Use cycle as a guard clause to avoid deeply nested ifs: handle the uninteresting cases at the top, then write the main logic unindented.

Python Stand-in (Python): exit and cycle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Naming constructs

You can give a name to any do, if, select case or block. Write the name and a colon before the keyword, and repeat the name on the end:

FORTRAN
outer: do i = 1, 3
  inner: do j = 1, 3
    if (j == 2) cycle inner
    print *, i, j
  end do inner
end do outer

exit name and cycle name then target that construct explicitly. The compiler checks the names match, so a misplaced end do becomes a compile error rather than a logic bug.

Leaving an outer loop

Without names, exit can only leave the innermost loop. With names you can jump out of both:

FORTRAN
program find_pair
  implicit none
  integer :: i, j

  search: do i = 1, 20
    do j = i, 20
      if (i * j == 91) then
        print *, "Found:", i, j
        exit search
      end if
    end do
  end do search
end program find_pair

It prints Found: 7 13, because the first pair with product 91 and j >= i is 7 and 13. exit search stops both loops at once.

flowchart TD
  A["search: do i"] --> B["do j"]
  B --> C{"i * j == 91?"}
  C -->|no| B
  C -->|"yes: exit search"| D["after end do search"]

A named exit jumps straight to the code after the outer loop.

Python Stand-in (Python): leaving two loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

exit from other constructs

Since Fortran 2008, exit name also leaves a named if, select case or block, which gives you a clean early exit from a long block without a loop:

FORTRAN
validate: block
  if (.not. file_ok) then
    print *, "bad file"
    exit validate
  end if
  if (.not. header_ok) then
    print *, "bad header"
    exit validate
  end if
  print *, "all checks passed"
end block validate

The block construct

block ... end block creates a scope where you can declare local variables right where they are needed, even after executable statements:

FORTRAN
do i = 1, n
  block
    real :: tmp
    tmp = x(i) * 2.0
    y(i) = tmp + 1.0
  end block
end do

tmp exists only inside the block. This is useful for temporaries, and for keeping implicit none programs tidy.

stop and error stop

stop ends the whole program normally; give it a message or an exit code:

FORTRAN
stop                           ! normal end
stop "Finished"                ! prints the text
stop 2                         ! exit status 2

error stop ends the program as an error (nonzero exit status, and in parallel programs it stops all images):

FORTRAN
if (n <= 0) error stop "n must be positive"

Use error stop for unrecoverable problems such as bad input data, so scripts and build systems notice the failure.

do concurrent: a preview

do concurrent tells the compiler that the iterations are independent and may run in any order, even in parallel:

FORTRAN
do concurrent (i = 1:n)
  b(i) = 2.0 * a(i)
end do

You promise that no iteration depends on another. The compiler can then vectorize or parallelize the loop. It does not allow exit or cycle the way a plain do does, and it is covered fully in the parallel computing chapter.

Legacy: goto and labels

Old code jumps with goto 100 to a labelled statement. Modern code avoids it. When you read legacy loops like this:

FORTRAN
      DO 10 I = 1, N
        IF (A(I) .LT. 0.0) GO TO 20
   10 CONTINUE
   20 CONTINUE

translate them to do ... exit ... end do. The result is shorter and easier to follow.

Python Stand-in (Python): search with a not-found value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does cycle do inside a do loop?

    cycle jumps to the next iteration; the loop variable is still incremented.
  2. 2. How do you leave an outer named loop from inside an inner loop?

    exit followed by the construct name leaves that construct and all loops inside it.
  3. 3. What does error stop do?

    error stop ends the program as an error, giving a nonzero exit status.
  4. 4. What is the main promise of do concurrent?

    do concurrent tells the compiler that iterations do not depend on each other, so it may reorder or parallelize them.

Summary

  • exit leaves a loop; cycle skips to the next pass.
  • Name constructs (outer: do ... end do outer) to target an outer loop with exit outer or cycle outer.
  • Since Fortran 2008, exit works on named if, select case and block constructs too.
  • block gives a local scope for temporary variables.
  • stop ends normally, error stop ends with an error, and do concurrent marks independent iterations.

Next: Arrays: The Basics