Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 39 ยท Control Flow

The if Statement and Logical Expressions

Make decisions in Fortran with the single-line if, if-then-else blocks, else if chains, nested ifs, logical operators and safe comparisons of real numbers.

Programs choose between actions by testing conditions. In Fortran the tool for that is the if statement, which comes in two shapes: a one-line form for a single action and a block form with then, else if and else. The conditions are logical expressions: comparisons joined with .and., .or. and .not..

The single-line if

When there is exactly one statement to guard, write it on the same line:

FORTRAN
if (temperature > 30.0) print *, "It is hot."
if (n < 0) n = -n

The condition goes in parentheses, and the statement follows with no then. Only one statement is allowed after the parentheses; for more, use a block.

The if-then-end if block

FORTRAN
if (score >= 50) then
  print *, "Pass"
  passed = passed + 1
end if

Add an else branch for the other case:

FORTRAN
if (score >= 50) then
  print *, "Pass"
else
  print *, "Try again"
end if

Note the spelling: end if (two words, or endif). then must be on the same line as the if.

else if chains

Test several conditions in order. The first true one wins, the rest are skipped:

FORTRAN
program grade
  implicit none
  integer :: score
  character :: letter

  score = 83
  if (score >= 90) then
    letter = "A"
  else if (score >= 80) then
    letter = "B"
  else if (score >= 70) then
    letter = "C"
  else
    letter = "F"
  end if
  print *, "Score", score, "gets grade ", letter
end program grade

For a score of 83 the output ends with grade B. Put the most demanding test first; here a score of 95 would also satisfy >= 80, but the earlier branch catches it.

flowchart TD
  A{"score >= 90?"} -->|yes| B["A"]
  A -->|no| C{"score >= 80?"}
  C -->|yes| D["B"]
  C -->|no| E{"score >= 70?"}
  E -->|yes| F["C"]
  E -->|no| G["F"]

An else if chain is a ladder of tests; the first match ends the search.

Python Stand-in (Python): the grade ladder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Logical expressions

Combine comparisons with .and., .or. and .not.:

FORTRAN
if (age >= 18 .and. age < 65) print *, "Working age"
if (.not. (x > 0.0)) print *, "x is not positive"
if (month == 12 .or. month <= 2) print *, "Winter (north)"

Precedence is .not. first, then .and., then .or.. When in doubt, use parentheses. A logical variable can be used directly: if (is_valid) ..., never if (is_valid == .true.).

No guaranteed short circuit

Fortran may evaluate both sides of .and. even when the first is false. This code can crash:

FORTRAN
if (i <= n .and. a(i) > 0.0) ...      ! a(i) may be read when i > n

Safe version with a nested if:

FORTRAN
if (i <= n) then
  if (a(i) > 0.0) then
    ...
  end if
end if

Nested ifs and named blocks

Blocks can be nested. For deeply nested code, name the construct; the compiler then checks that the matching end if carries the same name, which helps readability:

FORTRAN
check: if (n > 0) then
  if (mod(n, 2) == 0) then
    print *, "positive even"
  else
    print *, "positive odd"
  end if
else check
  print *, "zero or negative"
end if check

Comparing real numbers safely

Floating-point values are approximate, so x == 0.3 after x = 0.1 + 0.2 can be false. Compare with a tolerance:

FORTRAN
real, parameter :: tol = 1.0e-6
if (abs(a - b) < tol) print *, "equal enough"

For numbers of very different sizes, use a relative tolerance: abs(a - b) <= tol * max(abs(a), abs(b)).

Python Stand-in (Python): comparing reals with a tolerance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The arithmetic if (do not use)

Old Fortran had if (x) 10, 20, 30, jumping to labels for negative, zero or positive. It is deleted from the modern standard. If you meet it in legacy code, rewrite it as an if/else if/else chain.

A worked example: leap years

A year is a leap year if it is divisible by 4, except century years, which must also be divisible by 400.

FORTRAN
program leap
  implicit none
  integer :: year
  logical :: is_leap

  year = 1900
  is_leap = (mod(year, 4) == 0 .and. mod(year, 100) /= 0) .or. mod(year, 400) == 0
  if (is_leap) then
    print *, year, "is a leap year"
  else
    print *, year, "is not a leap year"
  end if
end program leap

For 1900 it reports that 1900 is not a leap year; 2000 is a leap year; 2024 is a leap year. Storing the result in a logical makes the condition easy to name and reuse.

Python Stand-in (Python): leap years

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which is valid single-line if syntax?

    The single-line form is if (condition) statement, with no then and no braces.
  2. 2. Why is if (i <= n .and. a(i) > 0.0) risky?

    Fortran does not guarantee short-circuit evaluation, so the second test may run with an invalid index.
  3. 3. In an else if chain, what happens once one condition is true?

    The first true condition's block runs, then execution jumps past the end if.
  4. 4. How should two real numbers be compared for equality?

    Rounding makes exact equality unreliable, so compare the difference to a small tolerance.

Summary

  • Single-line form: if (cond) statement; block form: if (cond) then ... else if ... else ... end if.
  • Conditions are logical expressions built with comparisons and .and., .or., .not..
  • There is no guaranteed short circuit: nest ifs when the second test depends on the first.
  • Name complex if constructs to make end if easy to match.
  • Compare reals with a tolerance, not ==.

Next: The select case Statement