Fortran – Operators Precedence

Fortran operators Precedence

Operators precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

CategoryOperatorAssociativity
Logical NOT and negative sign.not. (-)Left to right
Exponentiation**Left to right
Multiplicative* /Left to right
Additive+ –Left to right
Relational< <= > >=Left to right
Equality== /=Left to right
Logical AND.and.Left to right
Logical OR.or.Left to right
Assignment=Right to left

Example

Try the following example to understand the operator precedence in Fortran −

program precedenceOp
! this program checks logical operators

implicit none  

   ! variable declaration
   integer :: a, b, c, d, e
   
   ! assigning values 
   a = 20   
   b = 10
   c = 15
   d = 5
  
   e = (a + b) * c / d      ! ( 30 * 15 ) / 5
   print *, "Value of (a + b) * c / d is :    ",  e 

   e = ((a + b) * c) / d    ! (30 * 15 ) / 5
   print *, "Value of ((a + b) * c) / d is  : ",  e 

   e = (a + b) * (c / d);   ! (30) * (15/5)
   print *, "Value of (a + b) * (c / d) is  : ",  e 

   e = a + (b * c) / d;     !  20 + (150/5)
   print *, "Value of a + (b * c) / d is  :   " ,  e 
  
end program precedenceOp

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

Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply