lunes, 2 de mayo de 2011

IF-THEN-END

The IF-THEN-END IF form is a simplification of the general IF-THEN-ELSE-END IF form with the ELSE part omitted:

IF (logical-expression) THEN
statements
END IF

where statements is a sequence of executable statements, and logical-expression is a logical expression. The execution of this IF-THEN-ELSE-END IF statement goes as follows:
the logical-expression is evaluated, yielding a logical value
if the result is .TRUE., the statements in statements are executed, followed by the statement following the IF-THEN-END IF statement.
if the result is .FALSE., the statement following the IF-THEN-END IF is executed. In other words, if logical-expression is .FALSE., there is no action taken.
Examples
The following program segment computes the absolute value of X and saves the result into variable Absolute_X. Recall that the absolute value of x is x if x is non-negative; otherwise, the absolute value is -x. For example, the absolute value of 5 is 5 and the absolute value of -4 is 4=-(-4). Also note that the WRITE(*,*) statement has been intentionally broken into two lines with the continuation line symbol &. The trick is that the value of X is first saved to Absolute_X whose value is changed later only if the value of X is less than zero.
REAL :: X, Absolute_X

X = .....
Absolute_X = X
IF (X < 0.0) THEN
Absolute_X = -X
END IF
WRITE(*,*) 'The absolute value of ', x, &
' is ', Absolute_X

The following program segment reads in two integer values into a and b and finds the smaller one into Smaller. Note that the WRITE(*,*) has also been broken into two lines. This uses the same trick discussed in the previous example.
INTEGER :: a, b, Smaller

READ(*,*) a, b
Smaller = a
IF (a > b) THEN
Smaller = b
END IF
Write(*,*) 'The smaller of ', a, ' and ', &
b, ' is ', Smaller

No hay comentarios:

Publicar un comentario