lunes, 2 de mayo de 2011

IF-THEN-ELSE IF-END IF

IF-THEN-ELSE IF-END IF

The Nested IF-THEN-ELSE-END IF statement could produce a deeply nested IF statement which is difficult to read. There is a short hand to overcome this problem. It is the IF-THEN-ELSE IF-END-IF version. Its syntax is shown below:

IF (logical-expression-1) THEN
statements-1
ELSE IF (logical-expression-2) THEN
statements-2
ELSE IF (logical-expression-3) THEN
statement-3
ELSE IF (.....) THEN
...........
ELSE
statements-ELSE
END IF

Fortran evaluates logical-expression-1 and if the result is .TRUE., statements-1 is executed followed by the statement after END IF. If logical-expression-1 is .FALSE., Fortran evaluates logical-expression-2 and executes statements-2 and so on. In general, if logical-expression-n is .TRUE., statements-n is executed followed by the statement after END IF; otherwise, Fortran continues to evaluate the next logical expression.
If all logical expressions are .FALSE. and if ELSE is there, Fortran executes the statements-ELSE; otherwise, Fortran executes the statement after the END IF.

Note that the statements in the THEN section, ELSE IF section, and ELSE section can be another IF statement.

Examples
Suppose we need a program segment to read a number x and display its sign. More precisely, if x is positive, a + is displayed; if x is negative, a - is displayed; otherwise, a 0 is displayed. Here is a possible solution using IF-THEN-ELSE IF-END IF:
IF (x > 0) THEN
WRITE(*,*) '+'
ELSE IF (x == 0) THEN
WRITE(*,*) '0'
ELSE
WRITE(*,*) '-'
END IF

Given a x, we want to display the value of -x if x < 0, the value of x*x if x is in the range of 0 and 1 inclusive, and the value of 2*x if x is greater than 1.
The following is a possible solution:

IF (x < 0) THEN
WRITE(*,*) -x
ELSE IF (x <= 1) THEN
WRITE(*,*) x*x
ELSE
WRITE(*,*) 2*x
END IF

Consider the following code segment:
INTEGER :: x
CHARACTER(LEN=1) :: Grade

IF (x < 50) THEN
Grade = 'F'
ELSE IF (x < 60) THEN
Grade = 'D'
ELSE IF (x < 70) THEN
Grade = 'C'
ELSE IF (x < 80) THEN
Grade = 'B'
ELSE
Grade = 'A'
END IF

No hay comentarios:

Publicar un comentario