The SELECT CASE Statement in Fortran

Fortran provides several methods to control program flow, such as if statements and loops. When a program needs to execute different actions based on the value of a single variable, the SELECT CASE statement becomes extremely useful.

SELECT CASE simplifies multiple condition checks and improves readability, maintainability, and efficiency compared to nested if-else statements. This post explores the syntax, usage, examples, and best practices for using SELECT CASE in Fortran.

1. Introduction to SELECT CASE

The SELECT CASE statement allows a program to branch execution based on the value of a single expression or variable. It is particularly useful when there are multiple discrete cases to handle.

Without SELECT CASE, programmers often use multiple nested if-else statements:

if (day == 1) then
print *, "Monday"
else if (day == 2) then
print *, "Tuesday"
else if (day == 3) then
print *, "Wednesday"
else
print *, "Other day"
end if

While functional, this approach can become hard to read and error-prone when handling many cases.

SELECT CASE provides a clean, structured, and scalable solution:

select case(day)
case(1)
print *, "Monday"
case(2)
print *, "Tuesday"
case(3)
print *, "Wednesday"
case default
print *, "Other day"
end select

2. Syntax of SELECT CASE

The general structure of SELECT CASE is:

select case (expression)
case (value1)
! code executed if expression == value1
case (value2)
! code executed if expression == value2
... case default
! code executed if none of the cases match
end select

Key Points:

  1. expression can be integer, character, or logical.
  2. Each case checks if expression matches one or more values.
  3. case default is optional but recommended for handling unexpected values.
  4. Multiple values can be included in a single case using a comma-separated list.

3. Basic Example

Example 1: Days of the Week

program select_case_example
integer :: day
day = 3
select case(day)
case(1)
    print *, "Monday"
case(2)
    print *, "Tuesday"
case(3)
    print *, "Wednesday"
case default
    print *, "Other day"
end select
end program select_case_example

Explanation:

  • day = 3, so the program executes the block under case(3) and prints "Wednesday".
  • case default handles all values not explicitly listed.

4. Using Multiple Values in a Case

You can group multiple values under a single case to avoid repetition.

Example 2: Weekday vs Weekend

program weekday_weekend
integer :: day
day = 6
select case(day)
case(1,2,3,4,5)
    print *, "Weekday"
case(6,7)
    print *, "Weekend"
case default
    print *, "Invalid day"
end select
end program weekday_weekend

Explanation:

  • case(1,2,3,4,5) groups all weekdays.
  • case(6,7) groups weekend days.
  • Enhances readability and reduces repeated code.

5. Using Ranges in Cases

Fortran allows ranges in case statements using the colon syntax:

case(1:5)   ! matches 1,2,3,4,5
case(6:7)   ! matches 6,7

Example 3: Score Evaluation

program score_evaluation
integer :: score
score = 78
select case(score)
case(90:100)
    print *, "Excellent"
case(75:89)
    print *, "Good"
case(50:74)
    print *, "Average"
case(0:49)
    print *, "Fail"
case default
    print *, "Invalid score"
end select
end program score_evaluation

Explanation:

  • score = 78 falls in case(75:89), so "Good" is printed.
  • Ranges simplify multiple value checks.

6. Character Variables in SELECT CASE

SELECT CASE works with character variables for text-based branching.

Example 4: Menu Options

program menu_example
character(len=1) :: choice
choice = 'B'
select case(choice)
case('A')
    print *, "Option A selected"
case('B')
    print *, "Option B selected"
case('C')
    print *, "Option C selected"
case default
    print *, "Invalid option"
end select
end program menu_example

Explanation:

  • Character choice is compared with each case.
  • case default ensures unlisted options are handled.

7. Logical Variables in SELECT CASE

Even logical variables can be used in SELECT CASE statements:

Example 5: Logical Flag

program logical_case
logical :: flag
flag = .true.
select case(flag)
case(.true.)
    print *, "Flag is true"
case(.false.)
    print *, "Flag is false"
end select
end program logical_case

Explanation:

  • Demonstrates flexibility of SELECT CASE with logical data types.

8. Nesting SELECT CASE Statements

SELECT CASE statements can be nested for handling multiple variables or hierarchical conditions.

Example 6: Nested Cases

program nested_case
integer :: day, month
day = 1
month = 12
select case(month)
case(12,1,2)
    print *, "Winter"
    select case(day)
    case(25)
        print *, "Merry Christmas!"
    case default
        print *, "Regular winter day"
    end select
case(3,4,5)
    print *, "Spring"
case default
    print *, "Other season"
end select
end program nested_case

Explanation:

  • Outer SELECT CASE checks the month for season.
  • Inner SELECT CASE checks for a specific holiday.
  • Allows organized multi-level decision-making.

9. Using SELECT CASE with Expressions

The expression in SELECT CASE can be a variable or a computed value.

Example 7: Expression-Based Case

program expression_case
integer :: x
x = 7
select case(mod(x,3))
case(0)
    print *, "Divisible by 3"
case(1)
    print *, "Remainder 1"
case(2)
    print *, "Remainder 2"
case default
    print *, "Unexpected"
end select
end program expression_case

Explanation:

  • mod(x,3) computes the remainder of x divided by 3.
  • SELECT CASE branches based on computed value, not just a variable.

10. Best Practices for SELECT CASE

  1. Use SELECT CASE instead of long nested IF statements for readability.
  2. Always include case default to handle unexpected values.
  3. Group multiple values or use ranges to reduce repetitive code.
  4. Use descriptive print statements or actions to clarify output.
  5. Avoid overly complex nested cases; break into subroutines if necessary.
  6. Use logical, integer, and character types appropriately for clarity.
  7. Comment complex CASE blocks for maintainability.

11. Practical Applications

SELECT CASE is widely used in:

  • Menus and user options – Handling multiple user selections.
  • Score or grade evaluation – Grouping ranges into performance categories.
  • Simulation states – Managing different scenarios in simulations.
  • Date and time handling – Mapping day numbers to weekday names.
  • Logical flags – Managing program modes and status indicators.

Example 8: Student Grade Program

program student_grade
integer :: marks
marks = 82
select case(marks)
case(90:100)
    print *, "Grade: A"
case(80:89)
    print *, "Grade: B"
case(70:79)
    print *, "Grade: C"
case(60:69)
    print *, "Grade: D"
case(0:59)
    print *, "Grade: F"
case default
    print *, "Invalid marks"
end select
end program student_grade

Explanation:

  • Efficiently assigns grades based on marks using ranges.
  • case default ensures unexpected values are handled.

12. SELECT CASE vs IF Statements

FeatureSELECT CASEIF Statement
UseSingle variable with multiple possible valuesMultiple unrelated conditions
ReadabilityHigh, structuredCan become nested and complex
Range SupportSupported with :Supported but verbose
Default Casecase defaultelse
NestingSupported but can be organizedOften more nested

Conclusion: For multiple discrete values of a single variable, SELECT CASE is cleaner and easier to maintain.


13. Summary

  • SELECT CASE simplifies multi-way branching based on a single variable or expression.
  • Supports integer, character, and logical variables.
  • Can handle multiple values and ranges in a single case.
  • case default ensures all possibilities are handled.
  • Can be nested for multi-level decision-making.
  • Improves readability, maintainability, and scalability over nested if-else statements.
  • Useful in applications like menus, grades, dates, simulations, and flags.

14. Comprehensive Example

program comprehensive_case
integer :: day, month, score
day = 25
month = 12
score = 88
! Day of the week
select case(day)
case(1)
    print *, "Monday"
case(2)
    print *, "Tuesday"
case(3)
    print *, "Wednesday"
case(4)
    print *, "Thursday"
case(5)
    print *, "Friday"
case(6,7)
    print *, "Weekend"
case default
    print *, "Invalid day"
end select
! Season check
select case(month)
case(12,1,2)
    print *, "Winter"
case(3,4,5)
    print *, "Spring"
case(6,7,8)
    print *, "Summer"
case(9,10,11)
    print *, "Autumn"
case default
    print *, "Invalid month"
end select
! Grade evaluation
select case(score)
case(90:100)
    print *, "Grade: A"
case(80:89)
    print *, "Grade: B"
case(70:79)
    print *, "Grade: C"
case(60:69)
    print *, "Grade: D"
case(0:59)
    print *, "Grade: F"
case default
    print *, "Invalid score"
end select
end program comprehensive_case

Explanation:

  • Demonstrates multiple SELECT CASE statements handling days, months, and grades.
  • Uses ranges, multiple values, and default cases.
  • Illustrates structured, readable, and maintainable multi-condition handling.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *