Fortran-if-elseif-else-construct

提供:Dev Guides
移動先:案内検索

Fortran-if-else if-elseコンストラクト

*if* ステートメントの構造には、1つ以上のオプションの *else-if* 構造を含めることができます。 *if* 条件が失敗すると、すぐに続く *else-if* が実行されます。 *else-if* も失敗すると、後続の *else-if* ステートメント(存在する場合)が実行されます。

オプションのelseは最後に配置され、上記の条件のいずれも当てはまらないときに実行されます。

  • すべてのelseステートメント(else-ifおよびelse)はオプションです。
  • else-if は1回以上使用できます。
  • else は常に構造の最後に配置する必要があり、1回だけ表示する必要があります。

構文

*if ... else if ... else* ステートメントの構文は-
[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]

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

上記のコードをコンパイルして実行すると、次の結果が生成されます-

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