IF ELSEIF ELSE Statements in Fortran

Decision-making is a cornerstone of programming. In Fortran, the IF-ELSEIF-ELSE statement allows programs to evaluate multiple conditions sequentially and execute corresponding blocks of code. This control structure is essential for creating programs that respond differently based on varying inputs or states.

1. Introduction to Conditional Statements

Conditional statements allow a program to execute certain sections of code only when specific conditions are met. They are widely used in:

  • Numerical computations
  • Data validation
  • Scientific simulations
  • Decision-making algorithms

In Fortran, conditional statements are implemented using IF, ELSEIF, and ELSE.


2. Basic Syntax of IF-ELSEIF-ELSE

The general structure is:

if (condition1) then
! code block executed if condition1 is true
else if (condition2) then
! code block executed if condition2 is true
else
! code block executed if all above conditions are false
end if

Explanation:

  1. condition1, condition2 – Logical expressions that evaluate to .true. or .false.
  2. code blocks – Statements executed only when the corresponding condition is true
  3. else block – Executes when all prior conditions are false

The IF-ELSEIF-ELSE structure provides a clean way to handle multiple alternatives compared to nested IF statements.


3. Basic Example

integer :: x
x = 0

if (x > 0) then
print *, "Positive"
else if (x < 0) then
print *, "Negative"
else
print *, "Zero"
end if

Explanation:

  • x is assigned the value 0.
  • The first condition (x > 0) is false.
  • The second condition (x < 0) is false.
  • The else block executes, printing "Zero".

4. IF-ELSEIF-ELSE with Multiple Conditions

You can evaluate more than two conditions by using multiple ELSEIF statements.

integer :: score
score = 85

if (score >= 90) then
print *, "Grade A"
else if (score >= 75) then
print *, "Grade B"
else if (score >= 60) then
print *, "Grade C"
else
print *, "Grade F"
end if

Explanation:

  • Conditions are evaluated sequentially.
  • The first condition that evaluates to .true. executes its block.
  • Remaining conditions are ignored once a match is found.

5. Nested IF Statements

You can also nest IF statements inside blocks to handle more specific cases:

integer :: x, y
x = 5
y = -2

if (x > 0) then
if (y &gt; 0) then
    print *, "Both x and y are positive"
else
    print *, "x is positive, y is non-positive"
end if
else
print *, "x is non-positive"
end if

Explanation:

  • The inner IF statement evaluates only when x > 0 is true.
  • Nested IFs provide more detailed branching but can become complex if overused.

6. IF-ELSEIF-ELSE with Logical Operators

Fortran allows combining conditions using logical operators:

  • .and. – Logical AND
  • .or. – Logical OR
  • .not. – Logical NOT

Example:

integer :: age
logical :: hasPermission

age = 20
hasPermission = .true.

if (age >= 18 .and. hasPermission) then
print *, "Access granted"
else
print *, "Access denied"
end if

Explanation:

  • The condition uses .and. to ensure both criteria are met.
  • Only if both age >= 18 and hasPermission are true will the program print "Access granted".

7. Using IF-ELSEIF-ELSE in Loops

Conditional statements are frequently used inside loops to process multiple elements or cases:

integer :: i

do i = -2, 2
if (i &gt; 0) then
    print *, i, "is positive"
else if (i &lt; 0) then
    print *, i, "is negative"
else
    print *, i, "is zero"
end if
end do

Explanation:

  • The loop iterates from -2 to 2.
  • The IF-ELSEIF-ELSE block classifies each number.

Output:

-2 is negative
-1 is negative
0 is zero
1 is positive
2 is positive

8. Conditional Execution in Functions

You can also use IF-ELSEIF-ELSE inside functions to determine return values:

function grade(score) result(letter)
integer, intent(in) :: score
character :: letter
if (score &gt;= 90) then
    letter = 'A'
else if (score &gt;= 75) then
    letter = 'B'
else if (score &gt;= 60) then
    letter = 'C'
else
    letter = 'F'
end if
end function grade ! Main program integer :: s character :: g s = 82 g = grade(s) print *, "Score", s, "Grade:", g

Explanation:

  • The function evaluates multiple conditions to determine a grade.
  • IF-ELSEIF-ELSE simplifies the logic inside functions for clarity.

9. Best Practices for IF-ELSEIF-ELSE

  1. Order conditions logically: Place the most likely or restrictive conditions first.
  2. Avoid redundant checks: Once a condition is met, subsequent conditions are skipped.
  3. Use parentheses when combining multiple logical expressions.
  4. Use ELSE as a fallback: Ensures a default action if no conditions are true.
  5. Document conditions to maintain code readability.

10. Common Pitfalls

  1. Overlapping conditions: Ensure that no two conditions conflict unless intended.
  2. Nested IF complexity: Excessive nesting reduces readability; consider separate functions.
  3. Logical errors: Forgetting .and. or .or. can lead to incorrect branching.
  4. Neglecting ELSE: Without an else, some input values may not trigger any action.

11. Real-World Examples

11.1 Temperature Classification

real :: temp
temp = 15.0

if (temp >= 30.0) then
print *, "Hot"
else if (temp >= 20.0) then
print *, "Warm"
else if (temp >= 10.0) then
print *, "Cool"
else
print *, "Cold"
end if

Explanation:

  • Sequentially checks temperature ranges.
  • Only one block executes based on the temperature value.

11.2 Traffic Light System

character(len=5) :: light
light = 'Red'

if (light == 'Red') then
print *, "Stop"
else if (light == 'Yellow') then
print *, "Caution"
else
print *, "Go"
end if

Explanation:

  • Demonstrates decision-making based on string values.
  • IF-ELSEIF-ELSE can handle multiple possible states.

11.3 Loan Eligibility

integer :: age
real :: salary
age = 30
salary = 40000.0

if (age >= 21 .and. salary >= 50000.0) then
print *, "Eligible for loan"
else if (age >= 21 .and. salary < 50000.0) then
print *, "Partial eligibility"
else
print *, "Not eligible"
end if
  • Combines multiple conditions using logical operators.
  • Shows practical use in financial applications.

12. IF-ELSEIF-ELSE vs Nested IF

FeatureIF-ELSEIF-ELSENested IF
ReadabilityHighCan be complex
EvaluationSequentialConditional nesting required
Use CaseMultiple exclusive conditionsDetailed sub-conditions
MaintenanceEasy to modifyCan be error-prone

For most cases with multiple mutually exclusive conditions, IF-ELSEIF-ELSE is recommended.


Comments

Leave a Reply

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