3

Is there any way to run a loop for discrete values of a variable? What about in some latest version?

Something like

for i in 1  5 9 11  31 77 

used in Unix shell script?

halfer
  • 19,824
  • 17
  • 99
  • 186
hbaromega
  • 2,317
  • 2
  • 24
  • 32
  • Someone is trying to write a [tag:pascal] program in [tag:fotran]. – John Alexiou Apr 03 '14 at 13:48
  • I agree, should be able to say `DO I=(/ 1,3,5,7 /)` but you can't. Maybe it can be done with in [implicit do](http://stackoverflow.com/questions/4070528/implicit-do-loop-array-initialization). I will investigate. – John Alexiou Apr 03 '14 at 13:50
  • @ja72: your assertion that someone is trying to write a Pascal program in Fortran is strange, Pascal provides no more support for 'looping' over an arbitrary list of numbers than Fortran does. Furthermore, OP indicates that she has drawn inspiration from Unix shell scripting. – High Performance Mark Apr 03 '14 at 14:48
  • @HighPerformanceMark in pascal you can loop over an `emum` with non sequential values. They have to be constants though. – John Alexiou Apr 03 '14 at 14:55

3 Answers3

7
integer, dimension (5) :: indx = [5, 9, 11, 31, 71]

do i=1, size(indx)
   j=indx(i)
   ....
end do
M. S. B.
  • 28,968
  • 2
  • 46
  • 73
1

You can also use an implied do loop to accomplish this, but you'll have to define the array of values as above:

integer, dimension (5) :: indx = [5, 9, 11, 31, 71]
integer, dimension (5) :: rslt 
integer, external      :: func
rslt = (/ func(indx(j)), j=1,5 /)
Ben Criger
  • 150
  • 1
  • 7
0

I am not sure if this helps, but you can use arrays for indeces

program Console1

implicit none

! Variables
INTEGER :: X(4) = (/ 1, 3, 5, 7 /)
REAL :: Y(10) = 0.0

! Body of Console1
print *, X
!   1   3   5   7
Y(X) = 10.0/X
print *, Y
!   10.0    0.0    3.33   0.0    2.00   0.0    1.428    0.0 ...

end program Console1
John Alexiou
  • 28,472
  • 11
  • 77
  • 133