Loops are a fundamental concept in programming, allowing repeated execution of a block of code. In many applications, particularly in scientific and engineering computations, nested loops—loops inside loops—are essential. Nested loops enable iteration over multiple dimensions, such as arrays, matrices, grids, and more complex structures.
This post explores nested loops in Fortran in detail, including syntax, examples, multidimensional arrays, practical applications, and advanced techniques.
1. Introduction to Nested Loops
A nested loop is a loop placed inside another loop. The inner loop executes completely for every single iteration of the outer loop. Nested loops are commonly used for:
- Iterating over multidimensional arrays
- Performing matrix operations
- Generating tables or grids
- Running complex computations repeatedly in multiple dimensions
Understanding nested loops is essential for efficient programming in Fortran.
2. Syntax of Nested Loops in Fortran
The general structure of a nested loop is:
do outer_variable = start, end, step
! Outer loop block
do inner_variable = start, end, step
! Inner loop block
end do
end do
- outer_variable: Loop control variable for the outer loop
- inner_variable: Loop control variable for the inner loop
- start, end, step: Define the loop range and increment (step is optional; default is 1)
The inner loop completes all iterations for each iteration of the outer loop.
3. Basic Example of Nested Loops
program nested_loop_example
integer :: i, j
do i = 1, 3
do j = 1, 2
print *, "i =", i, ", j =", j
end do
end do
end program nested_loop_example
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
Explanation: For each value of i in the outer loop, the inner loop executes fully for all values of j.
4. Using Nested Loops for Arrays
Nested loops are particularly useful for iterating through multidimensional arrays.
4.1 Example: 2D Array Initialization
program array_2d
integer, dimension(3,2) :: matrix
integer :: i, j
do i = 1, 3
do j = 1, 2
matrix(i,j) = i * j
print *, "matrix(", i, ",", j, ") =", matrix(i,j)
end do
end do
end program array_2d
Output:
matrix( 1 , 1 ) = 1
matrix( 1 , 2 ) = 2
matrix( 2 , 1 ) = 2
matrix( 2 , 2 ) = 4
matrix( 3 , 1 ) = 3
matrix( 3 , 2 ) = 6
Explanation: Nested loops traverse all elements of the 2D array systematically.
5. Nested Loops for Matrices
5.1 Example: Matrix Addition
program matrix_addition
integer, dimension(2,2) :: A = reshape((/1,2,3,4/), (/2,2/))
integer, dimension(2,2) :: B = reshape((/5,6,7,8/), (/2,2/))
integer, dimension(2,2) :: C
integer :: i, j
do i = 1, 2
do j = 1, 2
C(i,j) = A(i,j) + B(i,j)
print *, "C(", i, ",", j, ") =", C(i,j)
end do
end do
end program matrix_addition
Output:
C( 1 , 1 ) = 6
C( 1 , 2 ) = 8
C( 2 , 1 ) = 10
C( 2 , 2 ) = 12
6. Nested Loops for Multiplication Tables
Nested loops are excellent for generating tabular outputs.
program multiplication_table
integer :: i, j
do i = 1, 5
do j = 1, 5
print *, i, "x", j, "=", i*j
end do
print *, "----------------"
end do
end program multiplication_table
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
----------------
2 x 1 = 2
...
7. Nested Loops in Scientific Computations
Nested loops are widely used in numerical simulations:
- Solving systems of equations
- Computing distances in 2D or 3D grids
- Performing finite difference or finite element computations
7.1 Example: Distance Matrix
program distance_matrix
real, dimension(3,2) :: points = reshape((/0.0,0.0, 1.0,0.0, 0.0,1.0/), (/3,2/))
real :: distance
integer :: i, j
do i = 1, 3
do j = i+1, 3
distance = sqrt((points(i,1)-points(j,1))**2 + (points(i,2)-points(j,2))**2)
print *, "Distance between point", i, "and", j, "=", distance
end do
end do
end program distance_matrix
Output:
Distance between point 1 and 2 = 1.0
Distance between point 1 and 3 = 1.0
Distance between point 2 and 3 = 1.4142135
8. Nested Loops for Pattern Printing
Nested loops are often used to print patterns in programming exercises.
8.1 Example: Star Triangle
program star_triangle
integer :: i, j
do i = 1, 5
do j = 1, i
write(*,'(A)', advance="no") "*"
end do
print *, ""
end do
end program star_triangle
Output:
*
**
***
****
*****
9. Nested Loops with Arrays and Conditional Statements
Nested loops can be combined with IF statements to process array elements conditionally.
program conditional_nested
integer, dimension(3,3) :: matrix
integer :: i, j
do i = 1, 3
do j = 1, 3
matrix(i,j) = i*j
if (matrix(i,j) > 4) then
print *, "matrix(", i, ",", j, ") is greater than 4:", matrix(i,j)
end if
end do
end do
end program conditional_nested
Output:
matrix( 2 , 3 ) is greater than 4: 6
matrix( 3 , 2 ) is greater than 4: 6
matrix( 3 , 3 ) is greater than 4: 9
10. Advanced Applications of Nested Loops
10.1 Image Processing
Nested loops are used to traverse pixels in 2D images for operations like filtering, thresholding, and convolution.
10.2 Physics Simulations
Loops inside loops are essential for iterating over space and time grids in simulations like:
- Heat distribution
- Wave propagation
- Particle simulations
10.3 Data Analysis
Nested loops can iterate through multiple datasets, compute pairwise comparisons, or calculate statistical measures.
11. Best Practices for Nested Loops
- Keep loops readable: Use descriptive loop variables (
i,j,row,col). - Avoid excessive nesting: Deeply nested loops can be inefficient and hard to read.
- Use
exitandcyclestatements when appropriate to optimize loops. - Combine with arrays: Nested loops are ideal for multidimensional array operations.
- Document purpose: Add comments explaining what each loop does.
- Consider vectorization: Fortran compilers can optimize some nested loops when vectorized.
12. Nested Loops with More Than Two Levels
Nested loops can have three or more levels for higher-dimensional data:
program three_level_nested
integer :: i, j, k
do i = 1, 2
do j = 1, 2
do k = 1, 2
print *, "i =", i, ", j =", j, ", k =", k
end do
end do
end do
end program three_level_nested
Output:
i = 1 , j = 1 , k = 1
i = 1 , j = 1 , k = 2
i = 1 , j = 2 , k = 1
i = 1 , j = 2 , k = 2
i = 2 , j = 1 , k = 1
i = 2 , j = 1 , k = 2
i = 2 , j = 2 , k = 1
i = 2 , j = 2 , k = 2
Leave a Reply