Fortran - if-else if-else Construct


Advertisements


An if statement construct can have one or more optional else-if constructs. When the if condition fails, the immediately followed else-if is executed. When the else-if also fails, its successor else-if statement (if any) is executed, and so on.

The optional else is placed at the end and it is executed when none of the above conditions hold true.

  • All else statements (else-if and else) are optional.

  • else-if can be used one or more times.

  • else must always be placed at the end of construct and should appear only once.

Syntax

The syntax of an if...else if...else statement is −

[name:] 
if (logical expression 1) then 
   ! block 1   
else if (logical expression 2) then       
   ! block 2   
else if (logical expression 3) then       
   ! block 3  
else       
   ! block 4   
end if [name]

Example

Live Demo
program ifElseIfElseProg
implicit none

   ! local variable declaration
   integer :: a = 100
 
   ! check the logical condition using if statement
   if( a == 10 ) then
  
      ! if condition is true then print the following 
      print*, "Value of a is 10" 
   
   else if( a == 20 ) then
  
      ! if else if condition is true 
      print*, "Value of a is 20" 
  
   else if( a == 30 ) then
   
      ! if else if condition is true  
      print*, "Value of a is 30" 
  
   else
   
      ! if none of the conditions is true 
      print*, "None of the values is matching" 
      
   end if
   
   print*, "exact value of a is ", a
 
end program ifElseIfElseProg

When the above code is compiled and executed, it produces the following result −

None of the values is matching
exact value of a is 100

fortran_decisions.htm

Advertisements