DO s v=e1,e2,e3where s is a statement label, v is a variable (usually an integer and ei, e2, e3 are expressions (again usually integer). Program flow through a DO loop is as follows. The variable v is set to equal to e1 and then it is tested to see if it has exceeded the limit e2. If not all the code from the DO up to and including the statement whose label is s is executed. Then e3 is added to v which is then tested against e2 a second time. The program loops over the code until v exceeds the limit e2. For example the following code transfers the contents of array A to array B and then sets array A to zero
DO 100 INDX=1,N,1 B(INDX)=A(INDX) 100 A(INDX)=0
INDX starts at 1 and B(1) is set equal to A(1) and A(1) is set equal to 0. Then 1 is added to INDX and the process repeated. This continues until INDX is greater than N. Although v, e1, e2 and e3 can all be real it is usually best to avoid reals because of the problems of comparing 2 reals (see section 6.2).
The following rules apply to DO loops
DO 27 J=3,1,2This was because the loop started by setting v=e1 and not testing until statement s had been processed and e3 added to V. With FORTRAN 77 this is no longer true. Now the number of times the loop must be executed is calculated before the loop is entered for the first time and if not at least once the loop is skipped. Note that this means that this (bad) code does not loop for ever:-
N=1 DO 10 KK=1,N 10 N=N+1
DO 1000 LOC=1,N IF (A(LOC).EQ.0.) GOTO 1010 1000 CONTINUE LOC=N+1 1010 ...This finds the first element of A that is zero or sets LOC to N+1.
DIMENSION A(5,5) DO 100 I=1,5 DO 100 J=1,5 IF(I.EQ.J) THEN A(I,J)=1.0 ELSE A(I,J)=0.0 ENDIF 100 CONTINUENesting may continue to an arbitary depth.
Most FORTRANs permit DO loops to be terminated by ENDDO rather than a numbered statement. The above example could be written:-
DIMENSION A(5,5) DO I=1,5 DO J=1,5 IF(I.EQ.J) THEN A(I,J)=1.0 ELSE A(I,J)=0.0 ENDIF ENDDO ENDO
In this case though, mutiple loops cannot terminate on the same statement. This form is encouraged and, if carefully indented, easier to read.
Most FORTRANs also permit the DO WHILE extension. The form is:-
DO while (e) Statements ENDO
The expression e is evaluated and, if true, the statements in the body of the loop executed. The process repeats until e is false. For example, the following finds the first empty element of an array:-
REAL A(100) I = 1 DO WHILE (A(I).NE.0.) I+I+1 ENDO
Can you spot a weakness in the above code?