Control structures are fundamental components of programming that allow developers to define the flow of a program. In Fortran, control structures enable programs to make decisions, perform repetitive operations, and handle conditional execution efficiently. Without control structures, programs would execute statements sequentially, which limits their flexibility and usefulness.
By mastering control structures in Fortran, programmers can implement complex logic, handle user input, process data arrays, and perform scientific computations effectively. This post introduces the concept of control structures, explains their types, and provides practical examples to illustrate their usage.
What Are Control Structures?
A control structure is a block of code that controls the order in which statements are executed in a program. Instead of executing statements one after another, control structures allow the program to:
- Make decisions: Execute certain code only when specific conditions are met.
- Repeat operations: Execute a block of code multiple times using loops.
- Handle multiple alternatives: Choose among several possible actions depending on conditions.
Control structures enhance program flexibility, maintainability, and efficiency. They are widely used in scientific programming, simulations, and data processing tasks.
Types of Control Structures in Fortran
Fortran provides two primary types of control structures:
- Conditional Statements: Allow programs to make decisions based on logical conditions.
- Loops: Allow programs to repeat a block of code multiple times.
Each type of control structure serves a specific purpose and can be combined with others to create complex program logic.
1. Conditional Statements
Conditional statements are used when the program needs to make decisions based on the value of a variable or the result of an expression. The main types of conditional statements in Fortran are:
- IF Statements
- IF-ELSE Statements
- IF-ELSEIF-ELSE Statements
- SELECT CASE Statements
Simple IF Statement
The simplest conditional statement in Fortran is the IF statement. It executes a block of code only if a specified condition is true.
Syntax:
if (condition) then
! code to execute if condition is true
end if
Example:
integer :: x
x = 5
if (x > 0) then
print *, "Positive"
end if
- In this example, the program checks if
xis greater than 0. - Since
x = 5, the condition is true, and the program prints “Positive”.
If the condition were false, the program would skip the print statement.
IF-ELSE Statement
The IF-ELSE statement provides an alternative block of code to execute if the condition is false.
Syntax:
if (condition) then
! code if true
else
! code if false
end if
Example:
integer :: x
x = -3
if (x > 0) then
print *, "Positive"
else
print *, "Non-positive"
end if
Output:
Non-positive
- The
elseblock executes when the condition(x > 0)is false. - This allows the program to handle multiple scenarios effectively.
IF-ELSEIF-ELSE Statement
For multiple conditions, Fortran provides the IF-ELSEIF-ELSE statement. This structure evaluates conditions sequentially and executes the first block that is true.
Syntax:
if (condition1) then
! code1
else if (condition2) then
! code2
else
! code3
end if
Example:
integer :: x
x = 0
if (x > 0) then
print *, "Positive"
else if (x < 0) then
print *, "Negative"
else
print *, "Zero"
end if
Output:
Zero
- The program evaluates
(x > 0), which is false. - Then it evaluates
(x < 0), which is also false. - Finally, the
elseblock executes, printing “Zero”.
2. SELECT CASE Statement
The SELECT CASE statement is a convenient alternative to multiple IF-ELSEIF statements when a single variable is compared against several values.
Syntax:
select case (variable)
case (value1)
! code for value1
case (value2)
! code for value2
case default
! code if none match
end select
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
Output:
Wednesday
- The program evaluates the value of
dayand executes the matchingcase. - If no case matches, the
defaultblock executes.
Loops in Fortran
Loops allow repetitive execution of a block of code. They are useful when the same operation must be performed multiple times, such as iterating through arrays, performing calculations, or generating sequences.
1. DO Loops (Counted Loops)
The DO loop executes a block of code a fixed number of times.
Syntax:
do variable = start, end, step
! code
end do
variableis the loop counter.startis the initial value.endis the final value.stepis optional and specifies the increment (default is 1).
Example:
integer :: i
do i = 1, 10
print *, i
end do
Output:
1
2
3
4
5
6
7
8
9
10
- The loop prints numbers from 1 to 10.
2. DO WHILE Loops (Conditional Loops)
DO WHILE loops execute as long as a specified condition is true. This is useful when the number of iterations is not known in advance.
Syntax:
do while (condition)
! code
end do
Example:
integer :: i
i = 1
do while (i <= 5)
print *, i
i = i + 1
end do
Output:
1
2
3
4
5
- The loop continues until
ibecomes greater than 5.
3. Nested Loops
Fortran allows loops inside loops, known as nested loops. They are commonly used in multidimensional array processing and matrix operations.
Example:
integer :: i, j
do i = 1, 3
do j = 1, 2
print *, "i =", i, ", j =", j
end do
end do
Output:
i = 1 , j = 1
i = 1 , j = 2
i = 2 , j = 1
i = 2 , j = 2
i = 3 , j = 1
i = 3 , j = 2
- The inner loop completes all its iterations for each iteration of the outer loop.
Exiting Loops: EXIT and CYCLE
Fortran provides EXIT and CYCLE statements to control loops dynamically.
- EXIT: Terminates the loop immediately.
- CYCLE: Skips the current iteration and continues with the next.
Example:
integer :: i
do i = 1, 10
if (i == 5) exit
if (i == 3) cycle
print *, i
end do
Output:
1
2
4
3is skipped due tocycle.- Loop exits when
iequals 5.
Combining Conditional Statements and Loops
Control structures can be combined to implement complex program logic. For example, loops can contain conditional statements to handle specific cases.
Example:
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
Output:
Result: 4
- Demonstrates the combination of
DOloops andIF-ELSEstatements.
Practical Applications of Control Structures
- Scientific Computations: Performing iterative calculations like summing sequences or simulating processes.
- Data Processing: Iterating through arrays and applying conditional checks.
- User Interaction: Validating input and providing responses based on conditions.
- Algorithm Implementation: Implementing sorting, searching, and numerical algorithms.
Example: Sum of Positive Numbers in an Array
integer, dimension(5) :: arr
integer :: sum, i
arr = (/ 2, -3, 5, -1, 4 /)
sum = 0
do i = 1, 5
if (arr(i) > 0) then
sum = sum + arr(i)
end if
end do
print *, "Sum of positive numbers:", sum
Output:
Sum of positive numbers: 11
Best Practices for Control Structures
- Indentation and Formatting: Use consistent indentation to improve readability.
- Limit Nested Levels: Avoid deeply nested loops or conditionals for maintainability.
- Use Descriptive Variable Names: Makes logic easier to understand.
- Combine with Comments: Explain complex conditions for clarity.
- Break Complex Expressions: Use logical variables or helper calculations to simplify conditions.
Leave a Reply