Fortran, one of the earliest programming languages, is still widely used in scientific computing, numerical analysis, and engineering applications. Loops are fundamental constructs in Fortran that allow repeated execution of a block of code. Fortran primarily supports two types of loops: DO loops (count-controlled loops) and DO WHILE loops (condition-controlled loops). Understanding these loops is essential for efficient programming in Fortran.
1. Introduction to Loops
A loop is a sequence of instructions that repeats either a fixed number of times or until a certain condition is met. Loops reduce code redundancy, improve readability, and make programs easier to maintain. In Fortran, loops are extensively used in mathematical computations, array processing, and iterative simulations.
Key Features of Loops in Fortran
- Repetition of code blocks
- Control using counters or conditions
- Nesting capability (loops within loops)
- Interaction with arrays and functions
2. DO Loop (Count-Controlled Loop)
The DO loop in Fortran is count-controlled, meaning it executes a block of code a predetermined number of times. The loop is governed by a loop control variable that starts from a specified value and increments until it reaches a defined limit.
Syntax of DO Loop
do variable = start, end [, step]
! Statements to be repeated
end do
variable: loop control variablestart: initial value of the variableend: final value of the variablestep(optional): increment for each iteration; default is 1
Example 1: Basic DO Loop
program basic_do_loop
integer :: i
do i = 1, 5
print *, "i =", i
end do
end program basic_do_loop
Explanation:
- The loop variable
istarts at 1 and increments by 1 until it reaches 5. - The
print *statement outputs the current value ofiduring each iteration. - The loop executes 5 times, printing values 1 through 5.
Example 2: DO Loop with Step
program do_loop_step
integer :: i
do i = 1, 10, 2
print *, "i =", i
end do
end program do_loop_step
Explanation:
- The loop starts at 1 and increments by 2 in each iteration.
- Output: 1, 3, 5, 7, 9
Nested DO Loops
Fortran allows nested DO loops, which are loops inside other loops. This is particularly useful for processing multi-dimensional arrays or performing matrix operations.
program nested_do_loop
integer :: i, j
do i = 1, 3
do j = 1, 2
print *, "i =", i, ", j =", j
end do
end do
end program nested_do_loop
Explanation:
- The outer loop (
i) runs 3 times. - For each iteration of
i, the inner loop (j) runs 2 times. - Total iterations: 3 × 2 = 6
DO Loop with Negative Step
You can use a negative step to decrement the loop variable.
program do_loop_negative
integer :: i
do i = 5, 1, -1
print *, "i =", i
end do
end program do_loop_negative
Output: 5, 4, 3, 2, 1
This is useful when iterating backward through arrays or sequences.
Common Uses of DO Loops
- Iterating through arrays
- Performing repetitive calculations
- Generating sequences of numbers
- Implementing numerical methods like summation or integration
3. DO WHILE Loop (Condition-Controlled Loop)
The DO WHILE loop executes a block of code as long as a specified condition is true. Unlike the DO loop, it does not require knowing the number of iterations beforehand.
Syntax of DO WHILE Loop
do while (condition)
! Statements to be repeated
end do
- The
conditionis a logical expression. - The loop continues as long as the condition evaluates to
.true.
Example 1: Basic DO WHILE Loop
program do_while_example
integer :: i
i = 1
do while (i <= 5)
print *, "i =", i
i = i + 1
end do
end program do_while_example
Explanation:
- The loop starts with
i = 1. - The condition
i <= 5is checked before each iteration. - The value of
iis incremented inside the loop.
Example 2: DO WHILE with Complex Condition
program do_while_complex
integer :: sum, n
sum = 0
n = 1
do while (sum < 20)
sum = sum + n
print *, "n =", n, ", sum =", sum
n = n + 1
end do
end program do_while_complex
Explanation:
- The loop continues until
sumreaches or exceeds 20. - The number of iterations is not fixed and depends on the condition.
Advantages of DO WHILE Loops
- Flexibility: The number of iterations does not need to be predetermined.
- Condition-driven execution: Useful for user input validation or iterative computations.
4. Comparison Between DO and DO WHILE Loops
| Feature | DO Loop | DO WHILE Loop |
|---|---|---|
| Control type | Count-controlled | Condition-controlled |
| Known iterations | Yes | Not necessarily |
| Loop variable | Required | Optional |
| Step | Optional | N/A |
| Use case | Fixed number of repetitions | Condition-based repetition |
5. Advanced DO Loop Techniques
DO Loop with Exit Statement
Fortran allows breaking out of a loop prematurely using the exit statement.
program do_exit_example
integer :: i
do i = 1, 10
if (i == 6) exit
print *, "i =", i
end do
end program do_exit_example
Output: 1, 2, 3, 4, 5
Explanation: The loop exits when i reaches 6.
DO Loop with CYCLE Statement
The cycle statement skips the remaining statements in the current iteration and continues with the next iteration.
program do_cycle_example
integer :: i
do i = 1, 5
if (i == 3) cycle
print *, "i =", i
end do
end program do_cycle_example
Output: 1, 2, 4, 5
Explanation: Iteration where i = 3 is skipped.
Using DO Loops with Arrays
DO loops are commonly used to process arrays element by element.
program array_processing
integer, dimension(5) :: arr = (/1, 2, 3, 4, 5/)
integer :: i
do i = 1, 5
arr(i) = arr(i) * 2
print *, "arr(", i, ") =", arr(i)
end do
end program array_processing
Explanation:
- Each array element is doubled using a DO loop.
- Output: 2, 4, 6, 8, 10
6. Loop Optimization Tips in Fortran
- Minimize loop computations: Perform calculations outside the loop if they don’t change.
- Use array operations when possible: Modern Fortran supports array operations which are faster than explicit loops.
- Avoid deep nesting: Nested loops can increase computational complexity. Consider algorithmic optimization.
- Preallocate arrays: Reduces runtime overhead inside loops.
7. Practical Applications of Loops in Fortran
- Numerical integration: Iteratively summing areas under a curve using trapezoidal or Simpson’s rule.
- Matrix multiplication: Nested DO loops iterate over rows and columns.
- Simulation: Loops are used to model time steps or iterative calculations.
- Data processing: Reading and transforming large datasets.
Example: Matrix Multiplication
program matrix_multiplication
integer, parameter :: n = 3
integer :: i, j, k
real :: A(n,n), B(n,n), C(n,n)
! Initialize matrices
A = reshape([1,2,3,4,5,6,7,8,9], [n,n])
B = reshape([9,8,7,6,5,4,3,2,1], [n,n])
C = 0.0
do i = 1, n
do j = 1, n
do k = 1, n
C(i,j) = C(i,j) + A(i,k)*B(k,j)
end do
end do
end do
print *, "Resultant matrix C:"
do i = 1, n
print *, C(i,:)
end do
end program matrix_multiplication
Explanation:
- Nested DO loops perform the multiplication of two 3×3 matrices.
- The innermost loop calculates the sum of products for each element of matrix
C.
Leave a Reply