Feffe
Feffe

Reputation: 183

Skip iterations in a do-loop (fortran)

I want to loop over N iterations, but some of the iterations should be "skipped" under particular conditions. I know I can do it using the goto statement, such as :

       do i = 1, N
          if condition(i) goto 14
          ! Execute my iteration if condition(i) is false
    14    continue
       end do

But I am a little scared of these goto statements, and I would like to know if there is another solution (I am using fortran 90 but would be interested in any solution, even if it requires a newer version).

Upvotes: 7

Views: 5991

Answers (2)

FredK
FredK

Reputation: 4084

You can also to this:

   do i = 1, N
      if ( .not. condition(i) ) then
         ! Execute my iteration if condition(i) is false
      endif
   end do

Upvotes: 2

High Performance Mark
High Performance Mark

Reputation: 78324

Try this

do i = 1, N
          if (condition(i)) cycle
          ! Execute my iteration if condition(i) is false
end do

If you need explanation, comment on what you need clarification of. Note I've dropped the archaic continue and labelled statement.

Upvotes: 14

Related Questions