IF( expression ) statement
Only if expression
is .TRUE.
is statement
executed.
LOGICAL :: test
...
IF ( test ) WRITE(*,*) `test is true'
IF ( x.LT.0 ) x=0
IF ( a/=b ) a=b
IF ( name=='Sam' ) &
WRITE(*,*) `hello Sam...'
[name:] IF (expression) THEN
block
ENDIF [name]
expression
is .TRUE.
is block
executed.
[name:] IF (expression) THEN
block1
ELSE [name]
block2
ENDIF [name]
expression
is .TRUE.
then block1
is executed, otherwise block2
is executed.
[name:] IF (expression1) THEN
block1
ELSEIF (expression2) THEN [name]
block2
...
[ELSE [name]
block]
ENDIF [name]
expression1
is .TRUE.
then block1
is executed and control passed to ENDIF
,
expression2
is evaluated,
expression2
is .TRUE.
then block2
is executed and control passed to ENDIF
.
REAL :: cost, discount
INTEGER :: n
...
IF ( n==1 ) THEN
discount = 0.0
ELSEIF ( n<=5 ) THEN
discount = 0.1
ELSEIF ( n>5 .AND. n<=10) THEN
discount = 0.15
ELSE
discount = 0.25
ENDIF
cost = cost-(cost*discount)
WRITE(*,*) `Invoice for', cost
CASE
construct is a structured way of selecting mutually exclusive actions, based on the value of a single expression.
SELECT CASE
construct provides an alternative to the IF
construct.
[name:] SELECT CASE( expression )
CASE( value ) [name]
block
...
[CASE DEFAULT
block]
END SELECT [name]
expression
may be character, integer or logical.
value
may take single value(s) or a range of values separated by a: (character and integer only), example:
value [,...] !single value(s)
min: !from min upward
:max !from max downward
min:max !between the limits
INTEGER :: month
season: SELECT CASE( month )
CASE(4,5)
WRITE(*,*) `Spring'
CASE(6,7)
WRITE(*,*) `Summer'
CASE(8:10)
WRITE(*,*) `Autumn'
CASE(11,1:3,12)
WRITE(*,*) `Winter'
CASE DEFAULT
WRITE(*,*) `not a month'
END SELCET season
DO
constructs (or `loops') contain executable statement(s) which are to be repeated.
[name:] DO count=start, stop [, step]
block
END DO [name]
count
is an integer variable,
start
is an integer variable (or expression) indicating the initial value of count
,
stop
is an integer variable (or expresion) indicating the final value of count
,
step
is an integer variable (or expression) indicating the increment (default is 1).
frist: DO some=1,5
... !some=1,2,3,4,5
END DO first
DO i=10,16,2
... !i=10,12,14,16
END DO
DO j=-7,4,3
... !j=-7,-4,-1,2
END DO
last: DO k=20,0,-5
... !k=20,15,10,5,0
END DO last
EXIT
.
CYCLE
.
EXIT
and CYCLE
apply to the inner-most loop containing the statement, but can refer to a specific, named loop.
outer: DO
...
inner: DO k=1,5
IF ( a(k)==0 ) CYCLE
IF ( a(k)<0 ) EXIT outer
...
END DO inner
END DO outer
GOTO label
GOTO
statement transfers control to the executable statement with label
.
INTEGER :: x
...
IF ( x.LT.1 ) GOTO 10
...
10 x = 1
GOTO
statements may be easy to use initially but very hard to maintain subsequently.