Conditions
| if then else | |
| SELECT CASE | |
| Nesting vs guards | |
| Logical expressions |
if then else
An if block runs one branch when the test is true and another branch when it is false.
Each block closes with end if, and else if adds further tests in the middle without extra nesting.
program ifdemo
implicit none
integer :: n
n = 7
if (n > 10) then
print *, "large"
else if (n > 5) then
print *, "medium"
else
print *, "small"
end if
end program ifdemo
SELECT CASE
SELECT CASE compares one value against a list of clear alternatives, which reads better than long else if chains.
Each case lists values or ranges, and case default catches everything else.
program casedemo
implicit none
integer :: day
day = 3
select case (day)
case (1)
print *, "Monday"
case (2, 3, 4)
print *, "midweek"
case default
print *, "other day"
end select
end program casedemo
Nesting vs guards
Deep nesting with if inside if is hard to read, so test bad input first and leave the main path flat.
Each guard handles one simple case and stops that branch, which keeps the happy path at the lowest indent level.
program guarddemo
implicit none
integer :: n
n = -2
if (n < 0) then
print *, "negative, stop"
else
print *, "square =", n * n
end if
end program guarddemo
Logical expressions
Combine comparisons with .and., .or., and .not. to describe the exact condition in one place.
Parentheses make the intent clear even when the default priority would give the same answer.
program condemo
implicit none
integer :: age
age = 20
if ((age >= 18) .and. (age < 65)) then
print *, "working age"
end if
end program condemo
Next: DO loops
Article author: Arthur Isaev