Could someone explain the following do loop. I suppose this is someting very elementary but I don’t see it.
I see an integer i used only once and I see two labels in the do loop.
I tought labels were obsolete.
program ch0505
implicit none
real :: p = 0.4e-4, papprox = 0.41e-4
real :: abs_error, rel_error
integer :: i
do i = 1, 3
abs_error = abs(p-papprox)
rel_error = abs(p-papprox)/abs(p)
print 100, p, papprox
100 format (’p = ’, e11.4, /, &
’papprox = ’, e11.4)
print 110, abs_error, rel_error
110 format (’abs error:’, 12x, e11.4, /, &
’rel error:’, 12x, e11.4, /)
p = p*1.0e5
papprox = papprox*1.0e5
end do
end program ch0505
Thank you, I’m aware of what the program is doing and it runs fine here.
I guess I didn"t formulate my problem well.
I just don’t understand what happens when you enter the do loop.
I suppose the loop runs for i = 1, 2, 3.
But where does i get incremented?
I copied from a pdf so I suppose this is the reason of the invalid characters.
Guess I’ll try to run line be line to see what happens within the do loop.
i is incremented automatically (+1 by default) each time you arrive at the end do, it is then compared with the right bound (3) and the loop continues if i<=3.
The number of trips through the loop is computed before the loop begins. The index variable, in this case ‘i’, is assigned a new value on each iteration.
Note that zero trips through a loop is a possibility. For example:
do, i=1, 0
… ! Nothing in here will be performed.
end do
Normally that last sentence would be correct, but in this case the variable i is never referenced, so it is likely that it is never stored and/or incremented. The only way to tell if the compiler has done this would be to examine the machine code or to use a debugger and to monitor the storage location (if it exists) for i. If the code is modified to reference i somehow, then of course the compiler would not eliminate it.
So the real magic for the do loop is the trip count. That is usually computed as a nonnegative value at the beginning of the loop and decremented by 1 each pass through the loop until it reaches 0. The test is typically at the beginning of the loop and the decrement is at the end of the loop, but a compiler is free to implement loops any way it wants with any available hardware instructions as long as the correct number of passes occurs.