if語句構建體可具有一個或多個可選的 else-if 結構。當 if 條件不滿足,則緊跟的 else-if 被執行。當 else-if 還是失敗,其繼續下一個 else-if 語句(如果有的話)被執行,依此類推。
可選的 else 被放置在末端,當上述條件不為真時則執行。
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