Do While

Statement Purpose

The DO WHILE statement is the first statement in a DO WHILE construct, which is a variant of the older FORTRAN construct the do loop. The use of the DO WHILE statement indicates that you want to execute the following block of statements as long as the logical expression specified in the DO WHILE evaluates to be true.

Rules and Examples

As stated above, the DO WHILE construct is a block of code that a programmer wants to execute as long as some logical expression evaluates to be true. Therefore a DO WHILE loop takes on the basic form illustrated in the following example.
		Do while (n.le.10.or.xdiff.gt.1.0E-3)
		  x1= x2
		  dx= (2*x1)-27-(45/(x1**2))
		  fx= (x1**2)-(27*x1)+(45/x1)
		  x2= x1 - (fx/dx)
		  xdiff=x2-x1
		  xdiff = abs(xdiff)
		  n=n+1
		end do
All of the mathematical expressions in the above example will be executed until the logical expression enclosed in parenthesis after the do while command evaluates to be false. There are two other variations of this loop that are worth noting. First is the named do while loop. When the loop is named it must be terminated with a named end do statement. This prevents confusion as to which loop is being terminated when several loops are nested inside of each other. So, if a named do while loop was used in the above example, it might be look similar to this:
		newton: do while (n.le.10.or.xdiff.gt.1.0E-3)
		  x1= x2
		  dx= (2*x1)-27-(45/(x1**2))
		  fx= (x1**2)-(27*x1)+(45/x1)
		  x2= x1 - (fx/dx)
		  xdiff=x2-x1
		  xdiff = abs(xdiff)
		  n=n+1
		end do newton
The last version of the do while loop is one that references a statement label as the last line in the loop. If this version was used in the first example, the first line of the loop would have looked like this:
		do 100 while (n.le.10.or.xdiff.gt.1.0e-3)
The number one hundred after the word do is the statement label of the last line in the loop. Possible final labeled lines for the Newton example are:
      100 end do
or
      100 continue
or
      100 n=n+1

For more information and examples see

lecture twelve

cycle

exit

examples: newton1.f and iftests.f

Up one level / Home


Written by Jason Wehr : jcw142@psu.edu and Maintained by John Mahaffy : jhm@cac.psu.edu