If Else in Fortran

Branching with if and else in Fortran is straight-forward.

program main
  implicit none
  integer :: num

  ! Here's a basic example.
  if (mod(7, 2) == 0) then
    print *, "7 is even"
  else
    print *, "7 is odd"
  end if

  ! You can have an 'if' statement without an else.
  if (mod(8, 4) == 0) then
    print *, "8 is divisible by 4"
  end if

  ! Logical operators like .and. and .or. are often useful in conditions.
  if (mod(8, 2) == 0 .or. mod(7, 2) == 0) then
    print *, "either 8 or 7 are even"
  end if

  ! A statement can precede conditionals; any variables
  ! declared earlier are available in the current and all subsequent branches.
  num = 9
  if (num < 0) then
    print *, num, "is negative"
  else if (num < 10) then
    print *, num, "has 1 digit"
  else
    print *, num, "has multiple digits"
  end if

end program main

To run the program, save the code in a file with a .f90 extension (e.g., if_else.f90) and use a Fortran compiler:

$ gfortran if_else.f90 -o if_else
$ ./if_else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Fortran:

  1. The if statement is followed by then and ends with end if.
  2. Logical operators are written as .and. and .or..
  3. The modulo operation is performed using the mod() function.
  4. String literals are enclosed in double quotes.
  5. The print * statement is used for console output.

Fortran doesn’t have a direct equivalent to Go’s ability to declare variables in the if statement itself. Variables need to be declared at the beginning of the program or subroutine.

There is no ternary if in Fortran, so you’ll need to use a full if statement even for basic conditions.