Fortran – Logical Operators

Fortran Logical operators

In this guide, we will discuss Fortran Logical Operators. The following table shows all the logical operators supported by Fortran. Assume variable A holds .true. and variable B holds .false. , then −

OperatorDescriptionExample
.and.Called Logical AND operator. If both the operands are non-zero, then condition becomes true.(A .and. B) is false.
.or.Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true.(A .or. B) is true.
.not.Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.!(A .and. B) is true.
.eqv.Called Logical EQUIVALENT Operator. Used to check equivalence of two logical values.(A .eqv. B) is false.
.neqv.Called Logical NON-EQUIVALENT Operator. Used to check non-equivalence of two logical values.(A .neqv. B) is true.

Example

Try the following example to understand all the logical operators available in Fortran −

program logicalOp
! this program checks logical operators
implicit none

   ! variable declaration
   logical :: a, b
   
   ! assigning values
   a = .true.
   b = .false.
   
   if (a .and. b) then
      print *, "Line 1 - Condition is true"
   else
      print *, "Line 1 - Condition is false"
   end if
   
   if (a .or. b) then
      print *, "Line 2 - Condition is true"
   else
      print *, "Line 2 - Condition is false"
   end if
   
   ! changing values
   a = .false.
   b = .true.
   
   if (.not.(a .and. b)) then
      print *, "Line 3 - Condition is true"
   else
      print *, "Line 3 - Condition is false"
   end if
   
   if (b .neqv. a) then
      print *, "Line 4 - Condition is true"
   else
      print *, "Line 4 - Condition is false"
   end if
   
   if (b .eqv. a) then
      print *, "Line 5 - Condition is true"
   else
      print *, "Line 5 - Condition is false"
   end if
   
end program logicalOp

When you compile and execute the above program it produces the following result −

Line 1 - Condition is false
Line 2 - Condition is true
Line 3 - Condition is true
Line 4 - Condition is true
Line 5 - Condition is false

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply