8. The if statements

An important part of any programming language are the conditional statements. The most common such statement in Fortran is the ifstatement, which actually has several forms. The simplest one is the logical if statement:
      if (logical expression) executable statement
This has to be written on one line. This example finds the absolute value of x:
      if (x .LT. 0) x = -x
If more than one statement should be executed inside the if, then the following syntax should be used:
      if (logical expression) then
         statements
      endif
The most general form of the if statement has 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.

Nested if statements

if statements can be nested in several levels. To ensure readability, it is important to use proper indentation. Here is an example:
      if (x .GT. 0) then
         if (x .GE. y) then
            write(*,*) 'x is positive and x >= y'
         else
            write(*,*) 'x is positive but x < y'
         endif
      elseif (x .LT. 0) then
         write(*,*) 'x is negative'
      else
         write(*,*) 'x is zero'
      endif
You should avoid nesting many levels of if statements since things get hard to follow.


Exercises

Exercise A
Write a Fortran 77 code segment that assignes the real variable t the following value (assume x and y have been defined previously):
     x+y       if x and y are both positive
     x-y       if x is positive and y negative
     y         if x is negative
     0         if x or y is zero


[Fortran Tutorial Home]
boman@sccm.stanford.edu