Welcome to AE Resources
Converted document Converted document

FORTRAN 90+: DO LOOPS

Loops are used to run a set of code instructions a specified number of times. This is useful if the code has a single equation with multiple inputs that can be changed and stored building up a solution, or simply keeping a certain one that may be needed. DO loops are initiated by typing the DO command followed by
DO control_variable = Initial_number, final_number, step_size.
The control_variable changes every time the loop runs, increasing by the step_size and when it equals the final_number the loop stops. After this one would type the script that is being executed and it will repeat until the final_number is reached and exit the loop and move on. An example is:
PROGRAM DO_Example
IMPLICIT NONE
INTEGER :: a,b,c,ans, control
ans=0
a=1
b=10
c=1
DO control=a,b,c
   ans=ans+1
END DO
WRITE(*,*) ans
END PROGRAM
This simple program adds an integer 1 to ans for every time the loop runs through resulting in 10. Another way to write a DO loop is with the EXIT command. Typing this command at a key point in the script will allow the user to stop the loop and move on to the next part of the code. This is usually implemented with an IF statement within the loop.
PROGRAM Guess
IMPLICIT NONE
INTEGER :: ans, c
c= 55
DO
   WRITE(*,*) "Guess any integer between 1 and 100"
   READ(*,*) ans
   IF (ans == c) THEN
      WRITE(*,*) "Correct"
      EXIT
   END IF
END DO
END PROGRAM
This program will continue to loop until the correct number is guessed. The program leaves the loop when the command EXIT is read by the computer. This method of leaving a loop becomes more important when there are long loops that may not need to run once the correct answer is reached reducing run time for the program. It is important to note that it is extremely important to make sure that the loop has a way to exit, whether with a count or with the EXIT command, or else one can end up with an infinite loop.
DO WHILE (...)
A DO WHILE(...) loop is another way of writing DO loops. Though it can be written in other ways it is a convenient method of using a DO loop. The result of using a DO WHILE(...) loop is that as long as the statement inside of the WHILE statement is .TRUE. the script inside the DO statement will run. As soon as the statement is .FALSE. the loop will terminate. An example of this is
PROGRAM DOLOOP
IMPLICIT NONE
INTEGER :: a=20,b=0
DO WHILE(a .NE. b)
   b=b+1 !Contained here could be any script that changes
   !’a’ ’b’ or both till they are equal
END DO
END PROGRAM DOLOOP