next up previous contents
Next: Block IF Up: IF statements Previous: ARITHMETIC IF

   
Logical IF

The second form of IF is the LOGICAL IF. It has form:-
IF (logical expression) Statement
For example:-
IF (A.EQ.B) GOTO 100
This means that if A is exactly equal to B, GOTO 100 otherwise continue with the next statement. Logical expressions can be made by comparing expressions (integers or reals) using the RELATIONAL OPERATORS:-

    .LT.   less than
    .LE.   less than or equal to
    .EQ.   equal to
    .NE.   not equal to
    .GT.   greater than
    .GE.   greater than or equal to

Some examples of logical expressions are:-

    I.LT.3
    A+2.GT.J
    B*C.NE.D+E
If comparing a real with an integer, the integer value is converted to a real first. The statement to be executed if the logical expression is true can be almost any executable statement (i.e. a statement that is executed while the program is running - see section 18) except another IF, and END or a DO (see section 8) Be very careful about using .EQ. and .NE. with reals for two real values may fail to be equal simply because of the finite accuracy of the computer. For example try this program :-

    A=1.23456
    B=A+10.
    IF (A.NE.B-10.) PRINT *,'THE COMPUTER GOT IT WRONG!'
    STOP
    END

To see if two real values A and B are almost equal do something like this:-

    SMALL=1.0E-6*(ABS(A)+ABS(B))
    IF (ABS(A-B).GT.SMALL) PRINT *,'A AND B ARE DIFFERENT'
ABS(value) means take the absolute value of. More complex logical expressions can be constructed using the LOGICAL OPERATORS (shown in order of increasing priority):-

    .OR.    true if either expression is true
    .AND.   true if both expressions are true
    .NOT.   true if expression is false
For example
A.EQ.B.OR.C.EQ.D
which is true if A is equal to B or C is equal to D. .NOT. is usually only used with logical variables (which we have not dealt with yet) but could be used thus:-
.NOT.A.EQ.B
meaning A.NE.B, but clearly not a good way of doing things! Logical operators have lower priority than relational operators which have lower priority than arithmetic ones. Use brackets if necessary to change the meaning e.g.:-
A.EQ.B.AND.C.EQ.D.OR.E.EQ.F
is true if A.EQ.B and C.EQ.D are both true or if E.EQ.F is true. It is not the same as
A.EQ.B.AND.(C.EQ.D.OR.E.EQ.F)
which requires both A.EQ.B and either C.EQ.D or E.EQ.F

Exercise 6
Write a program to ask the user for pairs of numbers (say x and y) and count the number of time x>y, x=y and x<y. The program should loop until the user inputs two 0s when it should type out the numbers in the counters.
* * *


next up previous contents
Next: Block IF Up: IF statements Previous: ARITHMETIC IF
n west (APC)
2000-03-08