If Else in Co-array Fortran

Branching with if and else in Co-array Fortran is straightforward.

program if_else
  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 if_else

Note that in Co-array Fortran, you need to use then after the condition and end if to close the if block. Also, the logical operators are written as .and. and .or. instead of && and ||.

To run the program, save it in a file (e.g., if_else.f90) and compile it using a Co-array Fortran compiler:

$ caf 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

In Co-array Fortran, there is no direct equivalent to the ternary operator. You’ll need to use a full if statement even for basic conditions.