next up previous contents index
Next: Arrays Up: Basic Fortran Concepts Previous: Functions

IF-blocks

Another important control structure in Fortran is the IF statement which allows a block of statements to be executed conditionally, or allows a choice to be made between different courses of action.

One obvious defect of the function AREA3 is that has no protection against incorrect input. Many sets of three real numbers could not possibly form the sides of a triangle, for example 1.0, 2.0, and 7.0. A little analysis shows that in all such impossible cases the argument of the square root function will be negative, which is illegal. Fortran systems should detect errors like this at run-time but will vary in their response. Even so, a message like "negative argument for square-root" may not be enough to suggest to the user what is wrong. The next version of the function is slightly more user-friendly:

 
      REAL FUNCTION AREA3(A, B, C) 
*Computes the area of a triangle from lengths of its sides. 
*If arguments are invalid issues error message and returns zero. 
      REAL A, B, C 
      S = (A + B + C)/2.0 
      FACTOR = S * (S-A) * (S-B) * (S-C) 
      IF(FACTOR .LE. 0.0) THEN 
          WRITE(UNIT=*, FMT=*)'Impossible triangle', A, B, C 
          AREA3 = 0.0 
      ELSE 
          AREA3 = SQRT(FACTOR) 
      END IF 
      END
The IF statement works with the ELSE and END IF statements to enclose two blocks of code. The statements in the first block are only executed if the expression in the IF statement is true, those in the second block only if it is false. The statements in each block are indented for visibility, but this is, again, just a sensible programming practice.

With this modification, the value of FACTOR is tested and if it is negative or zero then an error message is produced; AREA3 is also set to an impossible value (zero) to flag the mistake. Note that the form ``.LE.'' is used because the less-than-or-equals character, ``<", is not present in the Fortran character set. If S is positive the calculation proceeds as before.


next up previous contents index
Next: Arrays Up: Basic Fortran Concepts Previous: Functions
Helen Rowlands
8/27/1998