next up previous contents
Next: IF Construct Up: Control Flow Previous: Control Flow

 

IF Statement

 

This is the most basic form of conditional execution in that there is only an option to execute one statement or not -- the general IF construct allows a block of code to be executed. The basic form is,

 
IF(< logical-expression >)< exec-stmt >

If the .TRUE. / .FALSE. valued expression, < logical-expression >, evaluates to .TRUE. then the < exec-stmt > is executed otherwise control of the program passes to the next line. This type of IF statement still has its use as it is a lot less verbose than a block-IF with a single executable statement.

For example,

    IF (logical_val) A = 3

If logical_val is .TRUE. then A get set to 3 otherwise it does not.

A logical expression is often expressed as:

 
< expression >< relational-operator >< expression > 

For example,

    IF (x .GT. y) Maxi = x
    IF (i .NE. 0 .AND. j .NE. 0) k = 1/(i*j)
    IF (i /= 0 .AND. j /= 0) k = 1/(i*j) ! same
As REAL numbers are represented approximately, it makes little sense to use the .EQ. and .NE. relational operators between real-valued expressions. For example there is no guarantee that 3.0 and 1.5 * 2.0 are equal. If two REAL numbers / expressions are to be tested for equality then one should look at the size of the difference between the numbers and see if this is less than some sort of tolerance.

    REAL :: Tol = 0.0001
    IF (ABS(a-b) .LT. Tol) same = .TRUE.

Consider the IF statement

    IF (I > 17) Print*, "I > 17"

this maps onto the following control flow structure,

  figure4435
Figure 1: Schematic Diagram of an IF Statement

Return to corresponding overview page gif


next up previous contents
Next: IF Construct Up: Control Flow Previous: Control Flow

©University of Liverpool, 1997
Wed May 28 20:20:27 BST 1997
Not for commercial use.