Often we want to do one sort of
calculation under certain circumstances and do a different
calculation in other circumstances. You can control Fortran
calculations in this way by using the IF-THEN-ELSE structure. This looks like:
IF (some condition is true) THEN statements to be executed ELSE other statements END IF
Notice that the "condition" has to be enclosed in parentheses. Usually this condition will be a quantitative comparison. The basic comparisons are:
Comparison Operator | Meaning |
(A .EQ. B) | A equals B |
(A .NE. B) | A is not equal to B |
(A .GT. B) | A is greater than B |
(A .LT. B) | A is less than B |
(A .GE. B) | A is greater than or equal to B |
(A .LE. B) | A is less than or equal to B |
Following our previous examples, we might have a program that does something different in the morning as compared to the afternoon:
DO 10 I = 0, 24 IF (I .LT. 12) THEN PRINT *, 'IT IS MORNING' ELSE PRINT *, 'IT IS AFTERNOON' END IF 10 CONTINUE
It is allowable for the block of statements after either the IF or ELSE statement to be empty. For example, we might want to do something only after 10 a.m., and do nothing otherwise:
DO 10 I = 0, 24 IF (I .GE. 10) THEN PRINT *, 'THE TIME IS', I ELSE END IF 10 CONTINUE
Warning: REAL numbers in Fortran are not represented exactly, but only to a certain precision (typically about 7 significant figures). Yet comparisons are done exactly - Fortran has no concept of "close enough." This means comparisons of REAL numbers that rely on exact values can be hazardous. On the other hand INTEGER numbers have no fractional part, and therefore can be reliably used for exact comparisons.
Modify the solar elevation angle calculations in Exercise 6 so that the solar elevation angle is set to zero in the nighttime.