The Nested IF-THEN-ELSE-END IF statement could produce a deeply nested IF statement which is difficult to read. There is a short hand to overcome this problem. It is the IF-THEN-ELSE IF-END-IF version. Its syntax is shown below:

IF (logical-expression-1) THEN
ELSE IF (logical-expression-2) THEN
ELSE IF (logical-expression-3) THEN
ELSE IF (.....) THEN
Fortran evaluates logical-expression-1 and if the result is .TRUE., statements-1 is executed followed by the statement after END IF. If logical-expression-1 is .FALSE., Fortran evaluates logical-expression-2 and executes statements-2 and so on. In general, if logical-expression-n is .TRUE., statements-n is executed followed by the statement after END IF; otherwise, Fortran continues to evaluate the next logical expression.

If all logical expressions are .FALSE. and if ELSE is there, Fortran executes the statements-ELSE; otherwise, Fortran executes the statement after the END IF.

Note that the statements in the THEN section, ELSE IF section, and ELSE section can be another IF statement.


The first and second examples show that IF-THEN-ELSE IF-END IF can save some space and at the same time make a program more readable. Compare these two solutions with those using nest IF.

Note also that not all nested IF can be converted to the IF-THEN-ELSE IF-ELSE-END-IF form. For example, the example of determining the smallest of three numbers cannot be converted immediately. In general, if all tests (i.e., logical expressions) are mutually exclusive, then the chance to have a successful conversion is high. Otherwise, rewriting some parts or combining logical expression can be helpful. Here is one more example:

Let us reconsider the problem of finding the smallest of three given numbers. We know that if a is the smallest, then it must be smaller than the other two. Moreover, the condition for a number being the smallest is mutually exclusive. Thus, we have a successful conversion as follows:

IF (a < b .AND. a < c) THEN
   Result = a
ELSE IF (b < a .AND. b < c) THEN
   Result = b
   Result = c