The EXIT statement provides a way to leave a do or do while loop before all the iterations of that loop are finished. This statement was introduced in FORTRAN 90 to cut back on the use of unconditional go to statements.
The EXIT and cycle statements were introduced for the sole reason of replacing go to statements in do loops. These go to's occasionally resulted in some sloppy code and go to's that sometimes branched accidentally to the wrong statement. However, if used carefully there is not much difference between the use of go to's and exit statements. For instance, in FORTRAN 77 a do loop that had an early exit condition might have appeared like the following.
do 100 i=1,1000 xarray(i) = indata(i)*a k=k+1 if(xarray(i).eq.0.or.k.eq.kmax) then go to 101 else if (i.gt.1) then results(i)=xarray(i)+xarray(i-1) else results(i)=xarray(i) 100 continue 101 if(i.lt.1000) print *, 'Exited loop early.'
While in FORTRAN 90 the same loop can be written as
do 100 i=1,1000 xarray(i)=indata(i)*a k = k+1 if (xarray(i).eq.0.or.k.eq.kmax) then exit else if (i.gt.1) results(i)=xarray(i)+xarray(i-1) else results(i)=xarray(i) end if 100 continue if (i.lt.1000) print *, 'Exited loop early'
However, there is one further feature of the EXIT statement that is worth noting. The EXIT statement can have a name of a loop placed after it. This can be invaluable if you have several loops imbedded inside of one another. In the following example this feature is used to locate the "first" instance of a match between two arrays.
iloop: do i=1,n
jloop: do j=1,m
if (p1(i,j).eq.p2(i,j)) exit iloop
end do jloop
end do iloop
lecture fifteen
example: charvr90.f
Written by Jason Wehr : jcw142@psu.edu and Maintained by John Mahaffy : jhm@cac.psu.edu