integer i, n, sum sum = 0 do 10 i = 1, n sum = sum + i write(*,*) 'i =', i write(*,*) 'sum =', sum 10 continueThe number 10 is a statement

The variable defined in the `do`-statement is incremented by
1 by default. However, you can define any other integer to be
the *step*. This program segment prints the even numbers between
1 and 10 in decreasing order:

integer i do 20 i = 10, 1, -2 write(*,*) 'i =', i 20 continue

The general form of the `do` loop is as follows:

dolabel var = expr1, expr2, expr3statementslabelcontinue

Note: The `do`-loop variable must never be changed by other
statements within the loop! This will cause great confusion.

Many Fortran 77 compilers allow `do`-loops to be closed
by the `enddo` statement. The advantage of this is that
the statement label can then be omitted
since it is assumed that an `enddo` closes the nearest
previous `do` statement. The `enddo` construct is
widely used, but it is not a part of ANSI Fortran 77.

whileor alternatively,(logical expr)dostatementsenddo

do whileThe statements in the body will be repeated as long as the condition in the(logical expr)statementsenddo

labelif(logical expr)thenstatementsgotolabelendif

Here is an example that calculates and prints all the powers of two that are less than or equal to 100:

integer n n = 1 10 if (n .le. 100) then n = 2*n write (*,*) n goto 10 endif

doAgain, this should be implemented in Fortran 77 by usingstatementsuntil(logical expr)

Note that the logical expression in the latter version should be the negation of the expression given in the pseudocode!labelcontinuestatementsif(logical expr)gotolabel

do i = 10, 1, -2 write(*,*) 'i =', i end doFor

doIf you have the exit condition at the beginning it is a while loop, and if it is at the end you have an until loop.statementsif(logical expr)exitstatementsend do

- Exercise A
- Rewrite these pseudo-code loops into proper Fortran 77 syntax.
Avoid
`goto`if possible.i = 1 while (i<100) do sum = sum + i i = i+2 enddo i = 0 x = 1.0 repeat x = f(x) i = i+1 until (x<0) write(*,*) i, x

- Exercise B
- The following code is poorly written. Rewrite it in good F77 style.
(Tip: Compile and run to verify that the new version gives the same
answer as the old version.)
i = 1 sum = 0 10 do 20 i = 1, 50 if (i .gt. 10) goto 30 sum = sum + i 20 continue 30 if (i. le. 20) then sum = sum - 1 goto 20 else sum = 2*sum endif write(*,*) 'Sum =', sum

[AMS Home Page] [Fortran Tutorial Home]

boman@sccm.stanford.edu