Conditional execution: IF-THEN-ELSE

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) THEN
          statements to be executed if the condition is true 
      ELSE
         other statements to be executed if the condition is false
      END IF

Notice that the "condition" has to be enclosed in parentheses. In scientific computations the condition usually 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

We might have a program that does something different in the morning as compared to the afternoon:

      DO 10 I = 0, 23
      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

You can join multiple comparisons using the .AND. and .OR. operators. These work like you would expect. With the .AND. operator, the result is true if both of the comparisons being made are true. Example:

      DO 10 IHOUR = 0, 24
      IF ((IHOUR .GE. 6) .AND. (IHOUR .LE. 18)) THEN
         PRINT *, 'IT IS DAYTIME'
      ELSE
         PRINT *, 'IT IS NIGHT'
      END IF
10    CONTINUE

With the .OR. operator, the result is true if either of the comparisons is true. Example:

      DO 10 IHOUR = 0, 24
      IF ((IHOUR .LT. 6) .OR. (IHOUR .GT. 18)) THEN
         PRINT *, 'IT IS NIGHT'
      ELSE
         PRINT *, 'IT IS DAYTIME'
      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. That's one reason why it's a bad idea to use REAL variables for DO loop indices or limits. On the other hand INTEGER numbers have no fractional part, and therefore can be reliably used for exact comparisons.

Assignment:

Modify your program for the Coriolis parameter so that it prints the value of the Coriolis parameter only if it is above 0.5.

Back to the main page for the programming tutorial.