Cycle

Statement Purpose

The CYCLE and exit statements were introduced to clean up both do and do while loops and serve as an alternative to go to statements for branching within a loop. The cycle statement does this by telling the compiler not to execute any code below the statement and return to the start of the loop and continue the loop, using the next value in the index.

Examples of Use

As stated above, the cycle statement was introduced to clean up loops and provide an alternative to go to statements. To illustrate this, first take a look at the following FORTRAN loop.
		    do 200 i=1,25
		      x = x + 4i
		      if (x.ge.xmax) then 
                       xarray(i) = 0
			 go to 200
                     endif
		      xarray(i) = x
		200 continue
The "go to 200" statement in this example makes the computer go back to the start of the loop and begin looping again with i incremented by one if a certain condition is met. Notice that if that condition is met the next line of code will not be executed because it will be branched over. Yes, I could have used an IF, THEN ELSE here, but in many loops more code may exist below the IF test that you wish to bypass. Now, in FORTRAN 90 the above loop could look like the following.
		   do i=1,25
		     x = x + 4i 
		     if (x.ge.xmax) then
		       xarray(i)= 0
		       cycle
		     end if 
		     xarray(i)= x
		   end do
If you have a standard sense of aesthetics, the loop with the cycle statement appears cleaner. In addition, it has a significant practical benefit, eliminating any chance that the programmer might accidentally cause the program to branch to the wrong statement label by getting rid of the GO TO statement. Neither of the above DO loop forms is right or wrong. The form that a particular programmer uses depends on how he or she feels about GO TO statements, and his or her level of confidence in matching labels and references to labels. CYCLE can also be used with the Fortran 90 named do loops, as in the following structure from sort2.f.
      jmax=n-1
      outer: do i=1,n-1
        temp=1.e38
        inner: do j=1,jmax
          if(x(j).gt.x(j+1)) cycle inner
            temp=x(j)
            x(j)=x(j+1)
            x(j+1)=temp
            itemp=iy(j)
            iy(j)=iy(j+1)
            iy(j+1)=itemp
        end do inner
        if(temp.eq.1.e38) exit outer
        jmax=jmax-1
      end do outer

For more information and examples see

lecture fifteen
example: charvr90.f

Up one level / Home


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