DO WHILE Loops (Conditional Loops) in Fortran

Fortran, a powerful language widely used in scientific computing, engineering simulations, and numerical analysis, offers several types of loops for repetitive execution of code. Among them, the DO WHILE loop is a conditional loop that executes a block of code repeatedly as long as a specified condition is true.

DO WHILE loops are essential when the number of iterations is not known in advance and depends on a runtime condition. This post provides a comprehensive discussion of DO WHILE loops in Fortran, including syntax, examples, variations, nesting, use with arrays, logical conditions, best practices, and advanced applications.

1. Introduction to DO WHILE Loops

A DO WHILE loop evaluates a logical condition before each iteration. If the condition is true, the loop executes; if false, the loop terminates. Unlike a standard DO loop that iterates a fixed number of times, a DO WHILE loop is conditional.

Use cases include:

  • Reading input until a sentinel value is encountered
  • Performing calculations until convergence
  • Iterating until a condition is met

2. Syntax of DO WHILE Loop

The general syntax of a DO WHILE loop in Fortran is:

do while (condition)
! code to execute
end do
  • condition is a logical expression evaluated before each iteration.
  • The code block executes only if the condition is true.
  • end do marks the end of the loop.

2.1 Basic Example

program basic_do_while
integer :: i
i = 1
do while (i <= 5)
    print *, i
    i = i + 1
end do
end program basic_do_while

Explanation:

  • Variable i is initialized to 1.
  • The loop runs while i is less than or equal to 5.
  • Each iteration prints i and increments it by 1.
  • The loop stops when i becomes 6.

3. Key Features of DO WHILE Loops

  1. Condition evaluated first: The loop may not execute if the condition is false initially.
  2. Flexible iteration: The number of iterations depends on runtime conditions.
  3. Exit control: Can be terminated using the exit statement.
  4. Works with logical expressions: Supports .and., .or., .not. operators.

4. DO WHILE with Logical Variables

Logical variables can be used directly in DO WHILE loops:

program logical_do_while
logical :: flag
integer :: i
i = 1
flag = .true.
do while (flag)
    print *, "Iteration:", i
    i = i + 1
    if (i > 5) flag = .false.
end do
end program logical_do_while

Explanation:

  • Loop continues while flag is .true.
  • Condition is controlled inside the loop to terminate after 5 iterations

4.1 Using NOT Operator

program not_operator_do_while
logical :: continue_loop
integer :: counter
counter = 1
continue_loop = .true.
do while (.not. continue_loop == .false.)
    print *, "Counter:", counter
    counter = counter + 1
    if (counter > 3) continue_loop = .false.
end do
end program not_operator_do_while

Explanation:

  • Demonstrates using .not. in the loop condition
  • Loop stops when the logical variable becomes .false.

5. Nested DO WHILE Loops

DO WHILE loops can be nested to handle multiple levels of iteration:

program nested_do_while
integer :: i, j
i = 1
do while (i <= 3)
    j = 1
    do while (j <= 2)
        print *, "i =", i, "j =", j
        j = j + 1
    end do
    i = i + 1
end do
end program nested_do_while

Explanation:

  • Outer loop controls i from 1 to 3
  • Inner loop controls j from 1 to 2
  • Each combination of i and j is printed

5.1 Nested Loops with Conditions

program nested_conditions_do_while
integer :: x, y
x = 1
do while (x <= 3)
    y = 1
    do while (y <= 3)
        if (x + y > 3) then
            print *, "x =", x, "y =", y, "sum > 3"
        end if
        y = y + 1
    end do
    x = x + 1
end do
end program nested_conditions_do_while

Explanation:

  • Nested loops combined with IF statements
  • Only prints combinations where the sum of x and y is greater than 3

6. DO WHILE with Exit Statement

You can terminate a loop prematurely using the exit statement:

program exit_do_while
integer :: i
i = 1
do while (i <= 10)
    print *, "i =", i
    if (i == 5) exit
    i = i + 1
end do
end program exit_do_while

Explanation:

  • Loop stops when i equals 5
  • exit provides flexibility to leave a loop based on a condition

6.1 Using Cycle Statement

The cycle statement skips the remaining statements in the current iteration and continues with the next iteration:

program cycle_do_while
integer :: i
i = 0
do while (i < 5)
    i = i + 1
    if (mod(i,2) == 0) cycle
    print *, "Odd number:", i
end do
end program cycle_do_while

Explanation:

  • Skips printing even numbers
  • Only odd numbers are displayed

7. DO WHILE with Real Numbers

DO WHILE loops are not limited to integers; they can work with real numbers:

program real_do_while
real :: x
x = 1.0
do while (x < 5.0)
    print *, "x =", x
    x = x + 0.5
end do
end program real_do_while

Explanation:

  • Loop iterates using fractional increments
  • Useful for scientific simulations and continuous data processing

7.1 Precision Considerations

  • Be careful with real numbers due to rounding errors
  • Avoid conditions like x != 5.0 for loop termination
  • Use tolerance if necessary:
program tolerance_do_while
real :: x, tol
x = 0.0
tol = 1.0e-5
do while (x < 1.0 - tol)
    print *, "x =", x
    x = x + 0.2
end do
end program tolerance_do_while

8. DO WHILE with Arrays

Conditional loops can process arrays until a certain condition is met:

program array_do_while
integer, dimension(5) :: arr
integer :: i
arr = (/1, 2, 3, 4, 5/)
i = 1
do while (i <= 5 .and. arr(i) < 4)
    print *, "arr(", i, ") =", arr(i)
    i = i + 1
end do
end program array_do_while

Explanation:

  • Stops when array element is 4 or index exceeds array size
  • Demonstrates combining index and value conditions

9. DO WHILE with Logical Expressions

Logical operators like .and., .or., .not. can control loop execution:

program logical_condition_do_while
integer :: i
logical :: flag
i = 1
flag = .true.
do while (i <= 10 .and. flag)
    print *, "Iteration:", i
    i = i + 1
    if (i > 5) flag = .false.
end do
end program logical_condition_do_while

Explanation:

  • Loop continues while i <= 10 AND flag is .true.
  • Stops when flag is set to .false.

10. DO WHILE with User Input

DO WHILE loops are commonly used to process input until a sentinel value is provided:

program input_do_while
integer :: num
print *, "Enter numbers (0 to stop):"
read *, num
do while (num /= 0)
    print *, "You entered:", num
    read *, num
end do
print *, "Loop ended."
end program input_do_while

Explanation:

  • Loop continues until the user enters 0
  • Useful for data entry and interactive programs

11. Best Practices for DO WHILE Loops

  1. Initialize loop variables before entering the loop
  2. Ensure the condition will eventually become false to avoid infinite loops
  3. Use exit or cycle statements for better control
  4. Be cautious with real numbers due to floating-point precision
  5. Combine logical expressions carefully for clarity
  6. Document complex conditions to enhance maintainability

12. Advanced Example: Convergence Loop

DO WHILE loops are often used for iterative calculations until convergence:

program convergence_do_while
real :: x, tol, diff
integer :: iter, max_iter
x = 1.0
tol = 1.0e-5
iter = 0
max_iter = 100
do while (iter &lt; max_iter)
    diff = 1.0/x - x  ! example iterative formula
    if (abs(diff) &lt; tol) exit
    x = x + 0.1*diff
    iter = iter + 1
end do
print *, "Converged value of x:", x
print *, "Iterations:", iter
end program convergence_do_while

Explanation:

  • Iterative calculation continues until convergence or maximum iterations
  • DO WHILE allows conditional termination based on tolerance

13. Summary

  • DO WHILE loops repeat a block of code as long as a condition is true
  • Suitable for situations where the number of iterations is not known beforehand
  • Can be combined with logical variables, arrays, nested loops, and user input
  • Controlled with exit and cycle statements
  • Works with integers, real numbers, and logical expressions
  • Best practices include initializing variables, avoiding infinite loops, and documenting conditions
  • Commonly used in iterative calculations, input processing, and simulations

14. Complete Example: DO WHILE Demonstration

program do_while_demo
implicit none
integer :: i
real :: x
logical :: flag
! Example 1: Simple loop
i = 1
do while (i &lt;= 5)
    print *, "i =", i
    i = i + 1
end do
! Example 2: Real number loop
x = 0.5
do while (x &lt; 2.0)
    print *, "x =", x
    x = x + 0.3
end do
! Example 3: Logical variable loop
i = 1
flag = .true.
do while (i &lt;= 5 .and. flag)
    print *, "Iteration:", i
    i = i + 1
    if (i &gt; 3) flag = .false.
end do
! Example 4: User input loop
print *, "Enter numbers (negative number to stop):"
read *, i
do while (i &gt;= 0)
    print *, "You entered:", i
    read *, i
end do
print *, "Input loop ended."
end program do_while_demo

Explanation:

  • Combines simple integer loops, real loops, logical conditions, and input loops
  • Illustrates flexibility and practical applications of DO WHILE loops
  • Shows best practices like variable initialization and loop control

Comments

Leave a Reply

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