Control Flow

Works with integer, character, and logical selectors (not reals).

9.1 IF constructs

if (x > 0.0) print *, "positive"            ! logical IF (single statement)

if (score >= 90) then
  grade = 'A'
else if (score >= 80) then
  grade = 'B'
else
  grade = 'F'
end if

check: if (n > 0) then                      ! named construct
  print *, "n positive"
end if check

9.2 Conditional expressions (Fortran 2023)

y = ( x > 0 ? x : -x )                      ! supported by recent compilers only

9.3 SELECT CASE

Works with integer, character, and logical selectors (not reals). select type and select rank are covered later.

select case (day)
case (1, 7)
  print *, "Weekend"
case (2:6)
  print *, "Weekday"
case default
  print *, "Invalid"
end select

select case (trim(command))
case ("start"); call start()
case ("stop");  call stop_it()
case ("a":"m"); print *, "first half of the alphabet"
end select

9.4 DO loops

The loop variable must not be modified inside the loop; the trip count is computed once at the start.

do i = 1, 10                    ! counted loop (inclusive)
  print *, i, i**2
end do

do i = 10, 1, -2                ! step
  print *, i
end do

do                              ! infinite loop
  read(*, *, iostat=ios) x
  if (ios /= 0) exit            ! leave the loop
  if (x < 0) cycle              ! skip to next iteration
  total = total + x
end do

do while (err > tol)            ! DO WHILE
  call iterate(x, err)
end do

outer: do i = 1, n              ! named loops for multi-level exit/cycle
  inner: do j = 1, m
    if (a(i, j) < 0) cycle outer
    if (a(i, j) > 100) exit outer
  end do inner
end do outer

9.5 BLOCK construct (Fortran 2008)

block
  integer :: tmp            ! local declarations in the middle of code
  tmp = a; a = b; b = tmp
end block

9.6 STOP & ERROR STOP

stop                         ! normal termination
stop 0
stop "Finished"
error stop "Fatal: matrix is singular"     ! abnormal termination (non-zero exit status)
error stop 2

🧪 Part I Exercises

Write a program that converts temperatures from Celsius to Fahrenheit for −40 to 100 in steps of 10, printing a formatted table.

Compute epsilon, huge, and tiny for real32, real64, and real128 (if available) and print them.

Demonstrate the precision bug real(dp) :: x = 0.1 vs 0.1_dp by printing both with 20 digits.

Read integers until end-of-file (iostat) and print their count, sum, mean, min, and max.

Write FizzBuzz using select case on (mod(i,3), mod(i,5)) encoded as mod(i,3)*10 + mod(i,5) or similar.

Compute the GCD and LCM of two integers with a do while loop.

Print all prime numbers below 1000 using nested loops with named cycle.

Solve a quadratic equation, handling real and complex roots using the complex type.

Estimate π with the Leibniz series to a tolerance of 1e-8; print the number of iterations.

Use system_clock to time a loop computing the harmonic series up to 10⁸.