if statements

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 statement
which 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
      endif
The most general if statement comprises of the following form:
      if (logical expression) then
         statements
      elseif (logical expression) then
         statements
         :
         :
      else
         statements
      endif
The 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 $x>y$
.lt. x.lt.y true if $x<y$
.eq. x.eq.y true if $x=y$
.ne. x.ne.y true if $x\not=y$
.le. x.le.y true if $x\leq{}y$
.ge. x.ge.y true if $x\geq{}y$

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 $(x\leq{}y) \wedge (y\geq{}z)$.


operator example description
.not. .not. (x.eq.0) true if $x\not=0$
.and. (x.ge.0 .and. x.le.1) true if $0\leq{}x\leq{}1$
.or. (x.le.0 .or. x.ge.1) true if $x \in (-\infty;0\rangle \cup \langle{}1;\infty)$
.xor. x .xor. y true if only $x$ or $y$ (not both) is true (exclusive or)

Problem: Let us have a real number $x$. Write an algorithm that returns +1 if $0<x<1$, -1 for $x \in (-\infty;0) \cup (1;\infty)$ 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)