Fortran provides various control structures to guide program execution, such as loops, conditional statements, and case statements. By combining these structures, programmers can implement complex logic, handle diverse scenarios, and develop sophisticated algorithms efficiently.
This post explores how to combine DO loops, IF statements, SELECT CASE statements, and logical operators in Fortran, including examples, best practices, and advanced techniques.
1. Introduction to Control Structures
Control structures in Fortran allow a program to branch or repeat execution based on certain conditions. The main categories are:
- Conditional Statements
- IF, IF-ELSE, IF-ELSEIF, SELECT CASE
- Loops
- DO loop (count-controlled)
- DO WHILE loop (condition-controlled)
- Logical Expressions
.and.,.or.,.not.for combining conditions
Combining these structures allows programs to perform iterative computations, conditional updates, and decision-based logic.
2. Combining DO Loops with IF Statements
A common pattern in Fortran is to use loops to iterate and IF statements to conditionally execute code.
Example 1: Simple DO Loop with IF-ELSE
program combine_loop_if
integer :: i, x
x = 0
do i = 1, 5
if (i > 3) then
x = x + i
else
x = x - i
end if
end do
print *, "Result:", x
end program combine_loop_if
Output:
Result: 4
Explanation:
- Loop iterates from 1 to 5.
- For
i = 1,2,3,xis decremented. - For
i = 4,5,xis incremented. - Demonstrates combining iteration with conditional logic.
3. Using Nested Loops and Conditionals
You can nest loops inside loops and include IF statements for more complex logic.
Example 2: Nested DO Loops
program nested_loops
integer :: i, j
do i = 1, 3
do j = 1, 3
if (i == j) then
print *, "i equals j:", i, j
else
print *, "i not equal j:", i, j
end if
end do
end do
end program nested_loops
Explanation:
- Outer loop controls
i, inner loop controlsj. - Conditional checks equality of
iandj. - Useful for matrix operations, grid computations, or pairwise comparisons.
4. Combining DO WHILE Loops with IF Statements
DO WHILE loops execute until a condition becomes false, making them suitable for condition-controlled iteration.
Example 3: DO WHILE with Conditional Update
program while_if_example
integer :: n, sum
n = 1
sum = 0
do while (n <= 10)
if (mod(n,2) == 0) then
sum = sum + n
end if
n = n + 1
end do
print *, "Sum of even numbers from 1 to 10:", sum
end program while_if_example
Explanation:
- Loop continues while
n <= 10. IFcondition adds only even numbers tosum.- Demonstrates combining condition-controlled loops with conditional execution.
5. Using SELECT CASE with Loops
SELECT CASE can be combined with loops to perform different actions depending on the loop variable.
Example 4: Loop with SELECT CASE
program loop_case_example
integer :: i
do i = 1, 7
select case(i)
case(1,2,3,4,5)
print *, i, "is a weekday"
case(6,7)
print *, i, "is weekend"
case default
print *, i, "invalid day"
end select
end do
end program loop_case_example
Explanation:
- Loops over days 1 to 7.
SELECT CASEcategorizes each day as weekday or weekend.- Shows structured multi-way decision inside a loop.
6. Combining Logical Operators in Control Structures
Logical operators .and., .or., .not. can be used with IF statements or loops to implement complex logic.
Example 5: Logical Expressions in IF
program logical_example
integer :: x
x = 15
if ((x > 10) .and. (x < 20)) then
print *, "x is between 10 and 20"
else
print *, "x is outside the range"
end if
end program logical_example
Explanation:
.and.requires both conditions to be true.- Logical operators allow multiple conditions to be combined effectively.
Example 6: Loop with Logical Operators
program loop_logical
integer :: i
do i = 1, 10
if ((i /= 5) .and. (mod(i,2) == 0)) then
print *, "i is even and not 5:", i
end if
end do
end program loop_logical
Explanation:
- Only prints numbers that are even and not equal to 5.
- Combines DO loop, IF statement, relational, and logical operators.
7. Nested Control Structures for Complex Logic
For complex algorithms, it’s common to nest loops, conditionals, and case statements together.
Example 7: Nested Structure for Grid Computation
program grid_example
integer :: i, j
do i = 1, 3
do j = 1, 3
if (i == j) then
print *, "Diagonal element at (", i, ",", j, ")"
else
select case(mod(i+j,2))
case(0)
print *, "Sum even at (", i, ",", j, ")"
case(1)
print *, "Sum odd at (", i, ",", j, ")"
end select
end if
end do
end do
end program grid_example
Explanation:
- Outer and inner loops traverse a 3×3 grid.
- Conditional checks if element is on diagonal.
SELECT CASEfurther categorizes remaining elements by the sum’s parity.- Demonstrates multi-level control structure combination.
8. Practical Applications
Combining control structures is essential in real-world applications:
- Scientific Computing – Nested loops with conditions for simulations.
- Data Processing – Conditional filtering and aggregation.
- Matrix Operations – Looping over rows and columns with selective operations.
- Algorithm Implementation – Sorting, searching, or optimization algorithms.
- Event-Driven Simulations – Using logical flags and nested loops for state transitions.
Example 8: Simulation of Particle Movement
program particle_simulation
integer :: t
real :: position, velocity
position = 0.0
velocity = 1.5
do t = 1, 10
if (position < 5.0) then
position = position + velocity
else
velocity = -velocity
position = position + velocity
end if
print *, "Time:", t, "Position:", position
end do
end program particle_simulation
Explanation:
- Loop simulates particle movement over time.
- Conditional reverses velocity when a threshold is reached.
- Demonstrates combined loop and conditional logic for simulation purposes.
9. Using Functions with Control Structures
Control structures can also be combined inside functions or subroutines to encapsulate logic.
Example 9: Function with Nested IF
program function_control
integer :: num
num = 7
print *, "Category:", categorize(num)
contains
function categorize(x)
integer :: x
character(len=20) :: categorize
if (x < 5) then
categorize = "Small"
else if (x <= 10) then
categorize = "Medium"
else
categorize = "Large"
end if
end function categorize
end program function_control
Explanation:
- Function
categorizecontains nested IF statements. - Main program calls the function with control structure logic encapsulated.
10. Best Practices for Combining Control Structures
- Indent consistently to visualize nested structures.
- Use comments to explain complex conditional logic.
- Avoid deeply nested structures; consider breaking logic into functions or subroutines.
- Use logical operators for combining multiple conditions clearly.
- Use SELECT CASE when multiple discrete options exist.
- Initialize variables before using them in loops or conditionals.
- Test edge cases in nested loops and conditionals to avoid logic errors.
11. Summary
- Combining DO loops, IF statements, SELECT CASE statements, and logical operators allows Fortran programs to handle complex logic.
- Nested loops with conditionals can implement algorithms for simulation, data processing, and scientific computations.
- Logical operators
.and.,.or., and.not.make conditional logic more powerful and readable. - Using functions or subroutines with control structures improves modularity and maintainability.
- Proper indentation, comments, and structured design enhance readability and reduce errors.
12. Comprehensive Example
program combined_control_comprehensive
integer :: i, j
real :: matrix(3,3), sum
! Initialize matrix
do i = 1, 3
do j = 1, 3
matrix(i,j) = real(i*j)
end do
end do
sum = 0.0
do i = 1, 3
do j = 1, 3
if (matrix(i,j) > 2.0) then
sum = sum + matrix(i,j)
else
sum = sum - matrix(i,j)
end if
end do
end do
print *, "Sum after applying conditions:", sum
end program combined_control_comprehensive
Explanation:
- Nested loops traverse a matrix.
- Conditional statement modifies the sum based on matrix element value.
- Demonstrates practical use of combined loops and conditionals for computation.
Leave a Reply