Control constructs

The if statement and construct

if (scalar-logical-expression) executable-statement

if (x < 0.0) x = -x ! use magnitude

For the execution of a sequence of statements (block), or alternative sequences depending on alternative conditions, more general forms are available.

if (x2 < x1) then ! swap limits
  temp = x1
  x1 = x2
  x2 = temp
end if

Statements are indented for better legibility.

! nearest integer (rounded)
if (x < 0.0) then
  ix = x - 0.5
else
  ix = x + 0.5
end if
if (...) then
  ...
else if (...) then
  ...
else
  ...
end if

If constructs may be nested.

The case construct

Only one expression is evaluated. It must be scalar and of type integer, character or logical.

select case (ihour) ! hour of the day
case(5:10)
  print *, 'Guten Morgen'
case(12:14)
  print *, 'Mahlzeit'
case(18:22)
  print *, 'Guten Abend'
case(23, 0:4)
  print *, 'Gute Nacht'
case default
  print *, 'Guten Tag'
end select

The do construct

Used for iterations.

do i = 2, 10
  x(i) = x(i) + x(i-1)
end do

Value of variable i is available after the loop (i=11 in this example).

There is an optional third parameter for increment (stride) other than +1.

Do constructs may be nested.

do j = 10, 0, -1
  do i = -5, 5, 3 ! first index runs fastest
    a(i, j) = ...
  end do
end do
do while (t <= t2)
  ...
  t = t + ...
end do

Do "forever":

do while (.true.)
  ...
end do
do
  ...
  if (...) exit
  ...
  if (...) cycle
  ...
end do

The go to statement

go to label

Usually in the form of a conditional go to.

if (month < 1 .or. month > 12) go to 999 ! error handling

Exercises

Warning: You must avoid loops that run "forever".

1. Compute a table of Celsius and corresponding Fahrenheit temperatures for a user specified Celsius range (lower and upper limits, step size; allow for non-integers). Allow also for input of the limits in arbitrary order. If step size is negative, temperatures should run from high to low values, and vice versa.

...
read *, t1, t2, tstep
...
do ...
  ...
  tf = ...
  print *, tc, 'C', tf, 'F'
  ...
end do

2. A particular Pirani type pressure gauge (0.0005 - 1000 mbar) has the following voltage vs. pressure characteristics:

U/V = lg(p/mbar) + 5.5

Compute a p/mbar vs. U/V table (2.2 - 8.5 V in steps of 0.1 V).

3. Compute the greatest common divisor (gcd) of two integer numbers, "translating" the Modula example (N. Wirth, Programming in Modula-2, 3rd ed. (1985), p. 9).

4. Compute the harmonic oscillator energy level sums of ammonia and cyclopropane up to 100 kcal/mol using the algorithm of Beyer and Swinehart, i.e., try to reproduce column 3 of Table I of the article of Stein and Rabinovitch, J. Chem. Phys. 58 (1973) 2438 - 2445, DOI:10.1063/1.1679522. Grain size 1 cm-1, 40000 points.


Revised 2017-11-21