3

For example, I want to loop from 1 to 500 at an increment of 2. However, for every 8 loops I want to skip the next 18 loops (make the do-variable increase by 18). How do I do that?

My code is:

event = 0
do i = 1,500,2
    event = event + 1
    if (event .eq. 8) then
          i = i + 18
          event = 0
    endif
enddo

However, I got the error: "A do-variable within a DO body shall not appear in a variable definition context". Basically I can't alter the variable "i" in the loop. So how should I write the code to realize it?

Thanks.

FalloutRanger
  • 127
  • 2
  • 8
  • 1
    This is an error because Fortran is allowed to optimize your loop (and must know the number of iterations) based purely on a calculated number from your `do i ...` line. This is one of the (many) things Fortran sacrifices for optimization purposes. – casey Jun 24 '14 at 04:10

2 Answers2

5

It is forbidden to modify the loop index. You can solve your problem in several ways. For instance, here is a solution without explicit loop index :

i = -1
do
    i=i+2
    if(i > 5000) exit
    if (i == 15) i=i+18
    ...
enddo
Francois Jacq
  • 1,244
  • 10
  • 18
1

consider a nested loop for this example, something like

  do k=0,15
    do j=0,7
      i=34*k+2*j  ! 34 == 18+2*8
        ....
   end do
  end do

(probably i don't have the arithmetic right but you see the idea)

agentp
  • 6,849
  • 2
  • 19
  • 37