next up previous contents index
Next: Block-IF General Rules Up: Control Statements Previous: Other Control Statements

IF-Blocks

The simplest form of IF-block looks like this:
 
      IF(N .NE. 0) THEN 
         AVERAG = SUM / N 
         AVGSQ  = SUMSQ / N 
      END IF

The statements in the block are only executed if the condition is true. In this example the statements in the block are not executed if N is zero in order to avoid division by zero.

The IF-block can also contain an ELSE statement to handle the alternative:

 
      IF(B**2 .GE. 4.0 * A * C) THEN 
          WRITE(UNIT=*,FMT=*)'Real roots' 
      ELSE 
          WRITE(UNIT=*,FMT=*)'No real roots' 
      END IF

Since the IF statement contains a logical expression its value can only be true or false, thus one or other of these blocks will always be executed.

If there are several alternative conditions to be tested, they can be specified with ELSE IF statements: 

 
      IF(OPTION .EQ. 'PRINT') THEN 
           CALL OUTPUT(ARRAY) 
      ELSE IF(OPTION .EQ. 'READ') THEN 
           CALL INPUT(ARRAY) 
      ELSE IF(OPTION .EQ. 'QUIT') THEN 
           CLOSE(UNIT=OUT) 
           STOP 'end of program' 
      ELSE 
           WRITE(UNIT=*,FMT=*)'Incorrect reply, try again...' 
      END IF

There can be any number of ELSE IF blocks but in each case one, and only one, will be executed each time. Without an ELSE block on the end an nothing would have happened when an invalid option was selected.



 

Helen Rowlands
8/27/1998