An important part of any programming language are the conditional statements. The most common such
statement in Fortran is the if
statement, which actually has several forms. This is the
simplest form of the if
statement:
if (logical expression) executable statementwhich can be used once the executable statement represents only one command. If more than one command is to be executed once the logical expression is true, then the following syntax should be used instead:
if (logical expression) then command1 command2 ..... commandN endifThe most general
if
statement comprises of the following form:
if (logical expression) then statements elseif (logical expression) then statements : : else statements endifThe execution flow is from top to bottom. The conditional expressions are evaluated in sequence until one is found to be true. Then the associated code is executed and the control jumps to the next statement after the
endif
. If none of the conditions is true, the program executes the
statements written below the else
identifier, in case that it exists. Note that you can
always use nested if
statements, provided that each if
has its corresponding
endif
. Similarly, you are also free to use more than one elseif
identifier which
must, however, precede the else
identifier, if it exists.
F77 provides the following symbols for the conditional operators which can be used in the logical
expressions of the if
statement:
operator | example | description |
.gt. |
x.gt.y |
true if |
.lt. |
x.lt.y |
true if |
.eq. |
x.eq.y |
true if |
.ne. |
x.ne.y |
true if |
.le. |
x.le.y |
true if |
.ge. |
x.ge.y |
true if |
The logical statements can be arbitrarily combined with each other by using logical operators.
Following is a table of the most important logical operators which F77 provides. Note that only
.not.
operates on a single logical expression, whereas all others operate on two expressions
simultaneously. For example, if (x.le.y .and. y.ge.z)
is satisfied and the subsequent
statement executed if and only if
.
operator | example | description |
.not. |
.not. (x.eq.0) |
true if |
.and. |
(x.ge.0 .and. x.le.1) |
true if |
.or. |
(x.le.0 .or. x.ge.1) |
true if |
.xor. |
x .xor. y |
true if only or (not both) is true (exclusive or ) |
Problem: Let us have a real number . Write an algorithm that returns +1 if ,
-1 for
and 0
otherwise.
Solution:
if (x.gt.0 .and. x.lt.1) then ret = 1 elseif (x.lt.0 .or. x.gt.1) then ret = -1 else ret = 0 endif
Roman Gröger (2015-09-23)