6

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).

Feffe
  • 173
  • 1
  • 6

2 Answers2

13

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.

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • This is exactly what I wanted. I had seen this `cycle` statement but misunderstood the reference I found about it : I thought it would basically exit the loop without doing the remaining iterations. Thank you very much. – Feffe May 11 '16 at 15:07
2

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
FredK
  • 4,094
  • 1
  • 9
  • 11
  • It's the most obvious indeed, but I was trying to use something less heavy in terms of indentation/writing of the code. Since `condition(i)` is rarely `true`, it seemed more "readable" to write it using the `cycle` function. – Feffe May 12 '16 at 12:27