Skip to main content
Engineering LibreTexts

9.2: EXIT and CYCLE Statements

  • Page ID
    54280
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    The exit and cycle statements are used to modify the execution of a do-loop. The exit statement is used to exit a loop. The exit can be used alone, but it is typically used with a conditional statement to allow exiting a loop based on a specific condition. The exit statement can be used in a counter controlled loop or a conditionally controlled loop.

    For example, given the following declarations,

    integer :: i
    

    the following loop,

    do i = 1, 10
        if (i == 5) exit
        write (*,*) i
    end do
    

    will display the numbers from 1 to 4 skipping the remaining iterations. Since the variable \(i\) is checked before the write statement, the value is not displayed with \(i\) is 5 and the loop is exited without completing the remaining iterations. While it is possible to have multiple exit statements, typically only one is used. However, multiple exit statements may be required for more complex problems.

    The cycle statement will skip the remaining portion of the do-loop and start back at the top. The cycle statement can be used in a counter controlled loop or a conditionally controlled loop. If the cycle statement is used within a counter controlled loop, the next index counter is updated to the next iteration, which could terminate the loop.

    For example, given the following declarations,

    integer :: i
    

    the following loop,

    do i = 1, 10
        if (i == 5) cycle
        write (*,*) i
    end do
    

    will display the numbers from 1 to 4 and 6 to 10.


    This page titled 9.2: EXIT and CYCLE Statements is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Ed Jorgensen via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.