Fortran/Program flow control

If-then(-else) conditional
Conditional execution is done using the,   and   statements in the following construct:

You may have as many  statements as you desire.

The following operators can be used when making expressions: Note: The Fortran standard mandates  and   cannot be used with logicals but some compilers will not enforce the standard

To check more than one statement, use parentheses.

The following program generates a random number between 0 and 1 and tests if it is between 0 and 0.3, 0.3 and 0.6, or between 0.6 and 1.0.

There are two interesting archaic forms of : In the first form, things are pretty straightforward. In the second form, the arithmetic expression is evaluated. If the expression evaluates to a negative number, then execution continues at the first line number. If the expression evaluates to zero, then execution continues at the second line number. Otherwise, execution continues at the third line number.

case (switch)

 * select case(...) case (...); ... end select

If an if block consists of repeated tests on a single variable, it may be possible to replace it with a select case construct. For example, the code can be replaced by Fortran does not need a break statement.

Loops

 * do i=1,10 ... end do

To iterate, Fortran has a do loop. The following loop prints the squares of the integers from 1 to 10:

One can exit a loop early using exit, as shown in the code below, which prints the squares of integers until one of the squares exceeds 25.

Loops can be nested. The following code prints powers 2 through 4 of the integers from 1 to 10 In an archaic form of, a line number on which the loop(s) end is used. Here's the same loop, explicitly stating that label  is the last line of each loop: If using the archaic form, the loop must not end on an  or   statement. You may use a  statement as an anchor for a the   label.

There is also an optional increment argument when declaring a do loop. The following will count up by two's. 2, 4, 6, ...

Arguments to the do loop don't have to be numbers, they can be any integer that is defined elsewhere in the program. first, last, and increment can be any variable name.

Simple statements
will jump to the specified statement number.

will stop with the specified condition code or exit code. may be coded without an argument. Note that on many systems,  is still a failure. Also note that pre-Fortran 2008, the condition code must be a constant expression and not a variable.

will leave a loop.

can be used to end an archaic  loop when it would otherwise end on an.

will transfer the control of the program to the next  statement.

leaves a subroutine or function.